private void replaceIteratorNext(
     PsiElement element,
     String contentVariableName,
     String iteratorName,
     PsiElement childToSkip,
     StringBuilder out,
     PsiType contentType) {
   if (isIteratorNext(element, iteratorName, contentType)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceIteratorNext(
               child, contentVariableName, iteratorName, childToSkip, out, contentType);
         }
       }
     }
   }
 }
 private void replaceCollectionGetAccess(
     PsiElement element,
     String contentVariableName,
     PsiVariable listVariable,
     String indexName,
     PsiElement childToSkip,
     StringBuilder out) {
   if (isListGetLookup(element, indexName, listVariable)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceCollectionGetAccess(
               child, contentVariableName, listVariable, indexName, childToSkip, out);
         }
       }
     }
   }
 }
  private static void generateNameByString(
      Set<String> possibleNames,
      String value,
      NameValidator validator,
      boolean forStaticVariable,
      Project project) {
    if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return;
    if (forStaticVariable) {
      StringBuilder buffer = new StringBuilder(value.length() + 10);
      char[] chars = new char[value.length()];
      value.getChars(0, value.length(), chars, 0);
      boolean wasLow = Character.isLowerCase(chars[0]);

      buffer.append(Character.toUpperCase(chars[0]));
      for (int i = 1; i < chars.length; i++) {
        if (Character.isUpperCase(chars[i])) {
          if (wasLow) {
            buffer.append('_');
            wasLow = false;
          }
        } else {
          wasLow = true;
        }

        buffer.append(Character.toUpperCase(chars[i]));
      }
      possibleNames.add(validator.validateName(buffer.toString(), true));
    } else {
      possibleNames.add(validator.validateName(value, true));
    }
  }
Beispiel #4
1
  @Override
  protected void updateTitle(@Nullable final PsiVariable variable, final String value) {
    final PsiElement declarationScope =
        variable != null ? ((PsiParameter) variable).getDeclarationScope() : null;
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<>();
      TextRange addedRange = null;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        } else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }
        buf.append(parameter.getType().getPresentableText())
            .append(" ")
            .append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        } else if (myPanel.isParamToRemove(parameter)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
      }

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel =
          DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            0,
            getTestAttributesForRemoval(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(
          addedRange.getStartOffset(),
          addedRange.getEndOffset(),
          0,
          getTextAttributesForAdd(),
          HighlighterTargetArea.EXACT_RANGE);
      revalidate();
    }
  }
  private static void appendInferredType(
      PsiElement originalElement, GrVariable variable, StringBuilder buffer) {
    PsiType inferredType = null;
    if (PsiImplUtil.isWhiteSpaceOrNls(originalElement)) {
      originalElement = PsiTreeUtil.prevLeaf(originalElement);
    }
    if (originalElement != null
        && originalElement.getNode().getElementType() == GroovyTokenTypes.mIDENT) {
      originalElement = originalElement.getParent();
    }
    if (originalElement instanceof GrReferenceExpression) {
      inferredType = ((GrReferenceExpression) originalElement).getType();
    } else if (originalElement instanceof GrVariableDeclaration) {
      inferredType = variable.getTypeGroovy();
    } else if (originalElement instanceof GrVariable) {
      inferredType = ((GrVariable) originalElement).getTypeGroovy();
    }

    if (inferredType != null) {
      buffer.append("[inferred type] ");
      appendTypeString(buffer, inferredType, originalElement);
    } else {
      buffer.append("[cannot infer type]");
    }
  }
  private static void generateVariableInfo(
      PsiElement originalElement, StringBuilder buffer, PsiVariable variable) {
    if (variable instanceof PsiField) {
      final PsiClass parentClass = ((PsiField) variable).getContainingClass();
      if (parentClass != null) {
        buffer.append(JavaDocUtil.getShortestClassName(parentClass, variable));
        newLine(buffer);
      }
      generateModifiers(buffer, variable);
    }
    final PsiType type =
        variable instanceof GrVariable
            ? ((GrVariable) variable).getDeclaredType()
            : variable.getType();
    PsiImplUtil.appendTypeString(
        buffer, calcSubstitutor(originalElement).substitute(type), originalElement);
    buffer.append(" ");
    buffer.append(variable.getName());

    if (variable instanceof GrVariable) {
      newLine(buffer);

      while (originalElement != null) {
        PsiReference ref = originalElement.getReference();
        if (ref != null && ref.resolve() != null) break;

        originalElement = originalElement.getParent();
      }

      if (originalElement != null) {
        appendInferredType(originalElement, (GrVariable) variable, buffer);
      }
    }
  }
 public void emit(Emitter emitter) {
   StringBuilder sb = emitter.getTextBuffer();
   if (getCustomizedPrecedingComment().length() > 0) {
     sb.append("\n");
     sb.append(getCustomizedPrecedingComment());
   }
   emitAllElements(sb, emitter.getDocument());
   if (getCustomizedTrailingComment().length() > 0) {
     sb.append("\n");
     sb.append(getCustomizedTrailingComment());
   }
   /** emit corresponding setter, overloaded methods, and related methods, if any. */
   ListIterator li;
   if (isGetter()) {
     for (MethodEntry entry : myCorrespondingGetterSetters) {
       entry.emit(emitter);
     }
   }
   for (MethodEntry me : myOverloadedMethods) {
     me.emit(emitter);
   }
   for (MethodEntry me : sortedMethods) {
     me.emit(emitter);
   }
 }
  public String calcGenerics(@NotNull PsiElement context, InsertionContext insertionContext) {
    if (insertionContext.getCompletionChar() == '<') {
      return "";
    }

    assert context.isValid();
    if (myDiamond) {
      return "<>";
    }

    if (getObject() instanceof PsiClass) {
      PsiClass psiClass = (PsiClass) getObject();
      PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(psiClass.getProject()).getResolveHelper();
      PsiSubstitutor substitutor = getSubstitutor();
      StringBuilder builder = new StringBuilder();
      for (PsiTypeParameter parameter : psiClass.getTypeParameters()) {
        PsiType substitute = substitutor.substitute(parameter);
        if (substitute == null
            || (PsiUtil.resolveClassInType(substitute) == parameter
                && resolveHelper.resolveReferencedClass(parameter.getName(), context)
                    != CompletionUtil.getOriginalOrSelf(parameter))) {
          return "";
        }
        if (builder.length() > 0) {
          builder.append(", ");
        }
        builder.append(substitute.getCanonicalText());
      }
      if (builder.length() > 0) {
        return "<" + builder + ">";
      }
    }
    return "";
  }
Beispiel #9
0
 public static @Nullable PsiType resolveMethod(
     Project proj,
     PsiElement context,
     String clas,
     String methodName,
     @NotNull PsiExpression... args) {
   StringBuilder sb = new StringBuilder();
   sb.append(clas).append(".").append(methodName).append("(");
   boolean comma = false;
   for (PsiExpression arg : args) {
     if (comma) sb.append(",");
     sb.append(arg.getText());
     comma = true;
   }
   sb.append(")");
   PsiExpression exp =
       JavaPsiFacade.getElementFactory(proj).createExpressionFromText(sb.toString(), context);
   return exp.getType();
   /*if (clas == null || methodName == null) return null;
   PsiType[] argTypes = new PsiType[args.length];
   for (int i = 0; i < args.length; i++) {
       if (args[i] == null) return null;
       argTypes[i] = args[i].getType();
   }
   return resolveMethod(clas.getType(), methodName, argTypes);*/
 }
  @Override
  public String getEventMessage(LocatableEvent event) {
    final Location location = event.location();
    String sourceName;
    try {
      sourceName = location.sourceName();
    } catch (AbsentInformationException e) {
      sourceName = getFileName();
    }

    final boolean printFullTrace = Registry.is("debugger.breakpoint.message.full.trace");

    StringBuilder builder = new StringBuilder();
    if (printFullTrace) {
      builder.append(
          DebuggerBundle.message(
              "status.line.breakpoint.reached.full.trace",
              DebuggerUtilsEx.getLocationMethodQName(location)));
      try {
        final List<StackFrame> frames = event.thread().frames();
        renderTrace(frames, builder);
      } catch (IncompatibleThreadStateException e) {
        builder.append("Stacktrace not available: ").append(e.getMessage());
      }
    } else {
      builder.append(
          DebuggerBundle.message(
              "status.line.breakpoint.reached",
              DebuggerUtilsEx.getLocationMethodQName(location),
              sourceName,
              getLineIndex() + 1));
    }
    return builder.toString();
  }
Beispiel #11
0
  /**
   * Returns the original comment info of the specified element or null
   *
   * @param element the specified element
   * @return text chunk
   */
  @Nullable
  private static String getOrigCommentInfo(PsiDocCommentOwner element) {
    StringBuilder sb = new StringBuilder();
    PsiElement e = element.getFirstChild();
    if (!(e instanceof PsiComment)) {
      // no comments for this element
      return null;
    } else {
      boolean first = true;
      while (true) {
        if (e instanceof PsiDocComment) {
          PsiComment cm = (PsiComment) e;
          String text = cm.getText();
          if (text.startsWith("//")) {
            if (!first) sb.append('\n');
            sb.append(text.substring(2).trim());
          } else if (text.startsWith("/*")) {
            if (text.charAt(2) == '*') {
              text = text.substring(3, Math.max(3, text.length() - 2));
            } else {
              text = text.substring(2, Math.max(2, text.length() - 2));
            }
            sb.append(text);
          }
        } else if (!(e instanceof PsiWhiteSpace) && !(e instanceof PsiComment)) {
          break;
        }
        first = false;
        e = e.getNextSibling();
      }

      return sb.toString();
    }
  }
  private static boolean generateDelegate(GrChangeInfoImpl grInfo) {
    final GrMethod method = grInfo.getMethod();
    final PsiClass psiClass = method.getContainingClass();
    GrMethod newMethod = (GrMethod) method.copy();
    newMethod = (GrMethod) psiClass.addAfter(newMethod, method);
    StringBuilder buffer = new StringBuilder();
    buffer.append("\n");
    if (method.isConstructor()) {
      buffer.append("this");
    } else {
      if (!PsiType.VOID.equals(method.getReturnType())) {
        buffer.append("return ");
      }
      buffer.append(
          GrChangeSignatureUtil.getNameWithQuotesIfNeeded(
              grInfo.getNewName(), method.getProject()));
    }

    generateParametersForDelegateCall(grInfo, method, buffer);

    final GrCodeBlock codeBlock =
        GroovyPsiElementFactory.getInstance(method.getProject())
            .createMethodBodyFromText(buffer.toString());
    newMethod.setBlock(codeBlock);
    newMethod.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);

    CodeStyleManager.getInstance(method.getProject()).reformat(newMethod);
    return processPrimaryMethodInner(grInfo, method, null);
  }
Beispiel #13
0
 private void suggestNamesFromGenericParameters(
     final PsiType type,
     final VariableKind variableKind,
     final Collection<String> suggestions,
     boolean correctKeywords) {
   if (!(type instanceof PsiClassType)) {
     return;
   }
   StringBuilder fullNameBuilder = new StringBuilder();
   final PsiType[] parameters = ((PsiClassType) type).getParameters();
   for (PsiType parameter : parameters) {
     if (parameter instanceof PsiClassType) {
       final String typeName = normalizeTypeName(getTypeName(parameter));
       if (typeName != null) {
         fullNameBuilder.append(typeName);
       }
     }
   }
   String baseName = normalizeTypeName(getTypeName(type));
   if (baseName != null) {
     fullNameBuilder.append(baseName);
     ContainerUtil.addAll(
         suggestions,
         getSuggestionsByName(fullNameBuilder.toString(), variableKind, false, correctKeywords));
   }
 }
  private static String genIteratorVar(
      GrVariableDeclaration variableDeclaration,
      StringBuilder builder,
      ExpressionContext expressionContext,
      @NotNull GrExpression tupleInitializer,
      PsiType iteratorType,
      GroovyResolveResult iteratorMethodResult) {

    final String iteratorName =
        suggestVarName(iteratorType, variableDeclaration, expressionContext);
    builder.append("final ");
    writeType(builder, iteratorType, variableDeclaration);
    builder.append(' ').append(iteratorName).append(" = ");

    invokeMethodByResolveResult(
        tupleInitializer,
        iteratorMethodResult,
        "iterator",
        GrExpression.EMPTY_ARRAY,
        GrNamedArgument.EMPTY_ARRAY,
        GrClosableBlock.EMPTY_ARRAY,
        new ExpressionGenerator(builder, expressionContext),
        variableDeclaration);
    builder.append(";\n");
    return iteratorName;
  }
  @Override
  public String getSignature(@NotNull final PsiElement element) {
    StringBuilder buffer = null;
    for (PsiElement current = element;
        current != null && !(current instanceof PsiFile);
        current = current.getParent()) {
      int length = buffer == null ? 0 : buffer.length();
      StringBuilder b = getSignature(current, buffer);
      if (b == null
          && buffer != null
          && current.getParent() instanceof PsiFile
          && canResolveTopLevelChild(current)) {
        buffer
            .append(TYPE_MARKER)
            .append(ELEMENT_TOKENS_SEPARATOR)
            .append(TOP_LEVEL_CHILD_MARKER)
            .append(ELEMENTS_SEPARATOR);
        break;
      }
      buffer = b;
      if (buffer == null || length >= buffer.length()) {
        return null;
      }
      buffer.append(ELEMENTS_SEPARATOR);
    }

    if (buffer == null) {
      return null;
    }

    buffer.setLength(buffer.length() - 1);
    return buffer.toString();
  }
Beispiel #16
0
  @Override
  public String variableNameToPropertyName(String name, VariableKind variableKind) {
    if (variableKind == VariableKind.STATIC_FINAL_FIELD
        || variableKind == VariableKind.STATIC_FIELD && name.contains("_")) {
      StringBuilder buffer = new StringBuilder();
      for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        if (c != '_') {
          if (Character.isLowerCase(c)) {
            return variableNameToPropertyNameInner(name, variableKind);
          }

          buffer.append(Character.toLowerCase(c));
          continue;
        }
        //noinspection AssignmentToForLoopParameter
        i++;
        if (i < name.length()) {
          c = name.charAt(i);
          buffer.append(c);
        }
      }
      return buffer.toString();
    }

    return variableNameToPropertyNameInner(name, variableKind);
  }
 private static void appendElementText(
     @NotNull PsiElement element,
     @NotNull PsiElement elementToReplace,
     @Nullable PsiExpression replacementExpression,
     @NotNull StringBuilder out) {
   if (element.equals(elementToReplace)) {
     final String replacementText =
         (replacementExpression == null) ? "" : replacementExpression.getText();
     out.append(replacementText);
     return;
   }
   final PsiElement[] children = element.getChildren();
   if (children.length == 0) {
     out.append(element.getText());
     if (element instanceof PsiComment) {
       final PsiComment comment = (PsiComment) element;
       final IElementType tokenType = comment.getTokenType();
       if (tokenType == JavaTokenType.END_OF_LINE_COMMENT) {
         out.append('\n');
       }
     }
     return;
   }
   for (PsiElement child : children) {
     appendElementText(child, elementToReplace, replacementExpression, out);
   }
 }
  private static PsiField createField(
      PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) {
    @NonNls StringBuilder pattern = new StringBuilder();
    pattern.append("private int ");
    pattern.append(fieldName);
    if (local.getInitializer() == null) {
      includeInitializer = false;
    }
    if (includeInitializer) {
      pattern.append("=0");
    }
    pattern.append(";");
    final Project project = local.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    try {
      PsiField field = factory.createFieldFromText(pattern.toString(), null);

      field.getTypeElement().replace(factory.createTypeElement(forcedType));
      if (includeInitializer) {
        PsiExpression initializer =
            RefactoringUtil.convertInitializerToNormalExpression(
                local.getInitializer(), forcedType);
        field.getInitializer().replace(initializer);
      }

      for (PsiAnnotation annotation : local.getModifierList().getAnnotations()) {
        field.getModifierList().add(annotation.copy());
      }
      return field;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
 private static void genForPart(
     StringBuilder builder, GroovyPsiElement part, final Generator visitor) {
   part.accept(visitor);
   for (String statement : visitor.getContext().myStatements) {
     builder.append(statement).append(", ");
   }
   builder.append(visitor.getBuilder());
 }
Beispiel #20
0
 private static String constantValueToConstantName(final String[] names) {
   final StringBuilder result = new StringBuilder();
   for (int i = 0; i < names.length; i++) {
     if (i > 0) result.append("_");
     result.append(names[i]);
   }
   return result.toString();
 }
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
Beispiel #22
0
 private static String stripSpaces(String text) {
   String[] lines = LineTokenizer.tokenize(text.toCharArray(), false);
   StringBuilder buf = new StringBuilder(text.length());
   for (int i = 0; i < lines.length; i++) {
     if (i > 0) buf.append('\n');
     buf.append(rTrim(lines[i]));
   }
   return buf.toString();
 }
  private static void generateModifiers(StringBuilder buffer, PsiElement element) {
    String modifiers =
        PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY);

    if (!modifiers.isEmpty()) {
      buffer.append(modifiers);
      buffer.append(" ");
    }
  }
 private static void createElementLink(
     @NonNls final StringBuilder sb, final PsiElement element, final String str) {
   sb.append("&nbsp;&nbsp;<a href=\"psi_element://");
   sb.append(JavaDocUtil.getReferenceText(element.getProject(), element));
   sb.append("\">");
   sb.append(str);
   sb.append("</a>");
   sb.append("<br>");
 }
 @Override
 public void visitFlowInterruptStatement(GrFlowInterruptingStatement statement) {
   builder.append(statement.getStatementText());
   final String name = statement.getLabelName();
   if (name != null) {
     builder.append(' ').append(name); // todo check incorrect labels
   }
   builder.append(';');
 }
Beispiel #26
0
 public static String getLocationMethodQName(@NotNull Location location) {
   StringBuilder res = new StringBuilder();
   ReferenceType type = location.declaringType();
   if (type != null) {
     res.append(type.name()).append('.');
   }
   res.append(location.method().name());
   return res.toString();
 }
 private static void generateTraitType(
     @NotNull StringBuilder buffer, @NotNull GrTraitType type, PsiElement context) {
   appendTypeString(buffer, type.getExprType(), context);
   buffer.append(" as ");
   for (PsiType traitType : type.getTraitTypes()) {
     appendTypeString(buffer, traitType, context);
     buffer.append(", ");
   }
   buffer.delete(buffer.length() - 2, buffer.length());
 }
 @Override
 public void visitCatchClause(GrCatchClause catchClause) {
   final GrParameter parameter = catchClause.getParameter();
   builder.append("catch (");
   writeVariableWithoutSemicolonAndInitializer(builder, parameter, context);
   builder.append(") ");
   final GrOpenBlock body = catchClause.getBody();
   if (body != null) {
     body.accept(this);
   }
 }
 private void commitToOriginalInner() {
   final String text = myNewDocument.getText();
   final Map<
           PsiLanguageInjectionHost,
           Set<Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>>>
       map =
           ContainerUtil.classify(
               myMarkers.iterator(),
               new Convertor<
                   Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>,
                   PsiLanguageInjectionHost>() {
                 @Override
                 public PsiLanguageInjectionHost convert(
                     final Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> o) {
                   final PsiElement element = o.third.getElement();
                   return (PsiLanguageInjectionHost) element;
                 }
               });
   PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
   documentManager.commitDocument(myOrigDocument); // commit here and after each manipulator update
   int localInsideFileCursor = 0;
   for (PsiLanguageInjectionHost host : map.keySet()) {
     if (host == null) continue;
     String hostText = host.getText();
     ProperTextRange insideHost = null;
     StringBuilder sb = new StringBuilder();
     for (Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> entry : map.get(host)) {
       RangeMarker origMarker = entry.first; // check for validity?
       int hostOffset = host.getTextRange().getStartOffset();
       ProperTextRange localInsideHost =
           new ProperTextRange(
               origMarker.getStartOffset() - hostOffset, origMarker.getEndOffset() - hostOffset);
       RangeMarker rangeMarker = entry.second;
       ProperTextRange localInsideFile =
           new ProperTextRange(
               Math.max(localInsideFileCursor, rangeMarker.getStartOffset()),
               rangeMarker.getEndOffset());
       if (insideHost != null) {
         // append unchanged inter-markers fragment
         sb.append(
             hostText.substring(insideHost.getEndOffset(), localInsideHost.getStartOffset()));
       }
       sb.append(
           localInsideFile.getEndOffset() <= text.length() && !localInsideFile.isEmpty()
               ? localInsideFile.substring(text)
               : "");
       localInsideFileCursor = localInsideFile.getEndOffset();
       insideHost = insideHost == null ? localInsideHost : insideHost.union(localInsideHost);
     }
     assert insideHost != null;
     ElementManipulators.getManipulator(host).handleContentChange(host, insideHost, sb.toString());
     documentManager.commitDocument(myOrigDocument);
   }
 }
 public String getFlagsString() {
   final StringBuilder result = new StringBuilder();
   result.append(returnFlag).append(':');
   boolean first = true;
   for (boolean b : paramFlags) {
     if (first) first = false;
     else result.append(',');
     result.append(b);
   }
   return result.toString();
 }