YAMLKeyValue (final YAMLFile file, final String[] key, final String text) { final YAMLDocument root = file.getDocuments().get(0); assert root != null; assert key.length > 0; YAMLMapping rootMapping = PsiTreeUtil.findChildOfType(root, YAMLMapping.class); if (rootMapping == null) { final YAMLFile yamlFile = YAMLElementGenerator.getInstance(file.getProject()).createDummyYamlWithText(key[0] + ":"); final YAMLMapping mapping = (YAMLMapping) yamlFile.getDocuments().get(0).getTopLevelValue(); assert mapping != null; rootMapping = ((YAMLMapping)root.add(mapping)); } YAMLMapping current = rootMapping; final int keyLength = key.length; int i; for (i = 0; i < keyLength; i++) { final YAMLKeyValue existingRec = current.getKeyValueByKey(key[i]); if (existingRec != null){ final YAMLMapping nextMapping = ObjectUtils.tryCast(existingRec.getValue(), YAMLMapping.class); if (nextMapping != null) { current = nextMapping; continue; } } // Calc current key indent String indent = StringUtil.repeatSymbol(' ', getIndentInThisLine(current)); // Generate items final StringBuilder builder = new StringBuilder(); builder.append("---"); for (int j = i; j < keyLength; j++) { builder.append("\n").append(indent); builder.append(key[j]).append(":"); indent += " "; } builder.append(" ").append(text); // Create dummy mapping final YAMLFile fileWithKey = YAMLElementGenerator.getInstance(file.getProject()).createDummyYamlWithText(builder.toString()); final YAMLMapping dummyMapping = PsiTreeUtil.findChildOfType(fileWithKey.getDocuments().get(0), YAMLMapping.class); assert dummyMapping != null && dummyMapping.getKeyValues().size() == 1; // Add or replace final YAMLKeyValue dummyKeyValue = dummyMapping.getKeyValues().iterator().next(); current.putKeyValue(dummyKeyValue); if (!(dummyKeyValue.getValue() instanceof YAMLMapping)) { return dummyKeyValue; } else { current = ((YAMLMapping)dummyKeyValue.getValue()); } } // Conflict with existing value final StringBuilder builder = new StringBuilder(); final int top = Math.min(i + 1, keyLength); for (int j=0;j<top;j++){ if (builder.length() > 0){ builder.append('.'); } builder.append(key[j]); } throw new IncorrectOperationException(YAMLBundle.message("new.name.conflicts.with", builder.toString())); }