private ITypedRegion getPartition(IDocument doc, int offset) throws BadLocationException {
   ITypedRegion part =
       TextUtilities.getPartition(
           doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset, true);
   if (part.getType() == IDocument.DEFAULT_CONTENT_TYPE
       && part.getLength() == 0
       && offset == doc.getLength()
       && offset > 0) {
     // A special case because when cursor at end of document and just after a '=' sign, then we
     // get a DEFAULT content type
     // with a empty region. We rather would get the non-empty 'Value' partition just before that
     // (which has the assignment in it.
     char assign = doc.getChar(offset - 1);
     if (isAssign(assign)) {
       return new TypedRegion(offset - 1, 1, IPropertiesFilePartitions.PROPERTY_VALUE);
     } else {
       // For a similar case but where there's extra spaces after the '='
       ITypedRegion previousPart =
           TextUtilities.getPartition(
               doc, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, offset - 1, true);
       int previousEnd = previousPart.getOffset() + previousPart.getLength();
       if (previousEnd == offset) {
         // prefer this over a 0 length partition ending at the same location
         return previousPart;
       }
     }
   }
   return part;
 }
 protected static boolean isLineDelimiter(IDocument d, String text) {
   String[] delimiters = d.getLegalLineDelimiters();
   if (delimiters == null) {
     return false;
   }
   return TextUtilities.equals(delimiters, text) > -1;
 }
示例#3
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
   */
  public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    ScriptStackFrame frame = getFrame();
    if (frame == null) {
      return null;
    }
    IDocument document = textViewer.getDocument();
    if (document == null) {
      return null;
    }
    try {
      String str =
          TextUtilities.getContentType(
              document,
              IDocumentExtension3.DEFAULT_PARTITIONING,
              hoverRegion.getOffset() + 1,
              true);

      String variableName = document.get(hoverRegion.getOffset(), hoverRegion.getLength());

      if (JSPartitionScanner.JS_KEYWORD.equals(str) && !"this".equals(variableName)) // $NON-NLS-1$
      {
        return null;
      }
      ScriptValue var = ((ScriptDebugTarget) frame.getDebugTarget()).evaluate(frame, variableName);
      if (var != null) {
        return getVariableText(var);
      }
    } catch (BadLocationException e) {
      return null;
    }
    return null;
  }
示例#4
0
  private String normalizeBlockIndentation(ITextSelection selection, String selectedText)
      throws Throwable {
    String[] lines = selectedText.split("\\n");
    if (lines.length < 2) {
      return selectedText;
    }

    String firstLine =
        doc.get(
            doc.getLineOffset(selection.getStartLine()),
            doc.getLineLength(selection.getStartLine()));
    String lineDelimiter = TextUtilities.getDefaultLineDelimiter(doc);

    String indentation = "";
    int bodyIndent = 0;
    while (firstLine.startsWith(" ")) {
      indentation += " ";
      firstLine = firstLine.substring(1);
      bodyIndent += 1;
    }

    if (bodyIndent > 0) {
      StringBuffer selectedCode = new StringBuffer();
      for (String line : lines) {
        if (line.startsWith(indentation)) {
          selectedCode.append(line.substring(bodyIndent) + lineDelimiter);
        } else {
          selectedCode.append(line + lineDelimiter);
        }
      }
      selectedText = selectedCode.toString();
    }
    return selectedText;
  }
  protected void appendSpaceBefore(ICSSNode node, String toAppend, StringBuffer source) {
    if (node == null || source == null) return;
    if (isCleanup() && !getCleanupStrategy(node).isFormatSource())
      return; // for not formatting case on cleanup action

    Preferences preferences = CSSCorePlugin.getDefault().getPluginPreferences();
    if (toAppend != null
        && toAppend.startsWith("{")
        && preferences.getBoolean(
            CSSCorePreferenceNames.WRAPPING_NEWLINE_ON_OPEN_BRACE)) { // $NON-NLS-1$
      source.append(getLineDelimiter(node));
      source.append(getIndent(node));
      return;
    } else if (
    /* ! mgr.isOnePropertyPerLine() && */ preferences.getInt(CSSCorePreferenceNames.LINE_WIDTH) > 0
        && (!preferences.getBoolean(CSSCorePreferenceNames.WRAPPING_PROHIBIT_WRAP_ON_ATTR)
            || node.getOwnerDocument().getNodeType() != ICSSNode.STYLEDECLARATION_NODE)) {
      int n = getLastLineLength(node, source);
      int append =
          (toAppend != null)
              ? TextUtilities.indexOf(DefaultLineTracker.DELIMITERS, toAppend, 0)[0]
              : 0;
      if (toAppend != null) append = (append < 0) ? toAppend.length() : append;
      if (n + append + 1 > preferences.getInt(CSSCorePreferenceNames.LINE_WIDTH)) {
        source.append(getLineDelimiter(node));
        source.append(getIndent(node));
        source.append(getIndentString());
        return;
      }
    }
    source.append(" "); // $NON-NLS-1$
  }
示例#6
0
  /**
   * Determines whether each line is prefixed by one of the prefixes.
   *
   * @param startLine Start line in document
   * @param endLine End line in document
   * @param prefixes Possible comment prefixes
   * @param document The document
   * @return <code>true</code> iff each line from <code>startLine</code> to and including <code>
   *     endLine</code> is prepended by one of the <code>prefixes</code>, ignoring whitespace at the
   *     begin of line
   */
  private boolean isBlockCommented(
      int startLine, int endLine, String[] prefixes, IDocument document) {

    try {

      // check for occurrences of prefixes in the given lines
      for (int i = startLine; i <= endLine; i++) {

        IRegion line = document.getLineInformation(i);
        String text = document.get(line.getOffset(), line.getLength());

        int[] found = TextUtilities.indexOf(prefixes, text, 0);

        if (found[0] == -1)
          // found a line which is not commented
          return false;

        String s = document.get(line.getOffset(), found[0]);
        s = s.trim();
        if (s.length() != 0)
          // found a line which is not commented
          return false;
      }

      return true;

    } catch (BadLocationException x) {
      // should not happen
      // FIXME			Activator.getPlugin().log(x);
    }

    return false;
  }
示例#7
0
  /**
   * Returns the indentation of the line <code>line</code> in <code>document</code>. The returned
   * string may contain pairs of leading slashes that are considered part of the indentation. The
   * space before the asterix in a javadoc-like comment is not considered part of the indentation.
   *
   * @param document the document
   * @param line the line
   * @return the indentation of <code>line</code> in <code>document</code>
   * @throws BadLocationException if the document is changed concurrently
   */
  private static String getCurrentIndent(IDocument document, int line) throws BadLocationException {
    IRegion region = document.getLineInformation(line);
    int from = region.getOffset();
    int endOffset = region.getOffset() + region.getLength();

    // go behind line comments
    int to = from;
    while (to < endOffset - 2 && document.get(to, 2).equals(SLASHES)) to += 2;

    while (to < endOffset) {
      char ch = document.getChar(to);
      if (!Character.isWhitespace(ch)) break;
      to++;
    }

    // don't count the space before javadoc like, asterix-style comment lines
    if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { // $NON-NLS-1$
      String type =
          TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to, true);
      if (type.equals(IJavaPartitions.JAVA_DOC)
          || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) to--;
    }

    return document.get(from, to - from);
  }
  /**
   * Performs the rewrite: The rewrite events are translated to the corresponding in text changes.
   * The given options can be null in which case the global options {@link JavaCore#getOptions()
   * JavaCore.getOptions()} will be used.
   *
   * @param document Document which describes the code of the AST that is passed in in the
   *     constructor. This document is accessed read-only.
   * @param options the given options
   * @throws IllegalArgumentException if the rewrite fails
   * @return Returns the edit describing the text changes.
   */
  public TextEdit rewriteAST(IDocument document, Map options) {
    TextEdit result = new MultiTextEdit();

    final CompilationUnit rootNode = getRootNode();
    if (rootNode != null) {
      TargetSourceRangeComputer xsrComputer =
          new TargetSourceRangeComputer() {
            /**
             * This implementation of {@link TargetSourceRangeComputer#computeSourceRange(ASTNode)}
             * is specialized to work in the case of internal AST rewriting, where the original AST
             * has been modified from its original form. This means that one cannot trust that the
             * root of the given node is the compilation unit.
             */
            public SourceRange computeSourceRange(ASTNode node) {
              int extendedStartPosition = rootNode.getExtendedStartPosition(node);
              int extendedLength = rootNode.getExtendedLength(node);
              return new SourceRange(extendedStartPosition, extendedLength);
            }
          };
      char[] content = document.get().toCharArray();
      LineInformation lineInfo = LineInformation.create(document);
      String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
      List comments = rootNode.getCommentList();

      // MERGECONFLICT
      // AspectJ Extension - use the factory instead of building one directly
      // old code:
      // ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result,
      // this.eventStore, this.nodeStore, comments, options, xsrComputer);
      // new code:
      //			ASTVisitor visitor = ASTRewriteAnalyzer.getAnalyzerVisitor(content, lineInfo,
      // lineInfoneDelim, result, this.eventStore, this.nodeStore, comments, options, xsrComputer);
      // End AspectJ Extension

      Map currentOptions = options == null ? JavaCore.getOptions() : options;
      // OLD
      //			ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result,
      // this.eventStore, this.nodeStore, comments, currentOptions, xsrComputer,
      // (RecoveryScannerData)rootNode.getStatementsRecoveryData());

      // NEW  CAST NEEDED???
      ASTRewriteAnalyzer visitor =
          (ASTRewriteAnalyzer)
              ASTRewriteAnalyzer.getAnalyzerVisitor(
                  content,
                  lineInfo,
                  lineDelim,
                  result,
                  this.eventStore,
                  this.nodeStore,
                  comments,
                  currentOptions,
                  xsrComputer,
                  (RecoveryScannerData) rootNode.getStatementsRecoveryData());
      rootNode.accept(visitor);
    }
    return result;
  }
 private void stopRewriteSession(ITextFileBuffer fileBuffer, Object stateData) {
   IDocument document = fileBuffer.getDocument();
   if (document instanceof IDocumentExtension4) {
     IDocumentExtension4 extension = (IDocumentExtension4) document;
     extension.stopRewriteSession(fDocumentRewriteSession);
     fDocumentRewriteSession = null;
   } else if (stateData instanceof Map)
     TextUtilities.addDocumentPartitioners(document, (Map) stateData);
 }
 public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
   if (c.length == 0
       && c.text != null
       && TextUtilities.endsWith(d.getLegalLineDelimiters(), c.text) != -1) {
     autoIndentAfterNewLine(d, c);
   } else if (c.text.equals("\t")) {
     c.text = INDENT_STRING;
   }
 }
 /**
  * Returns true if the character at the specified offset is a less-than sign, rather than an type
  * parameter list open angle bracket.
  *
  * @param document a document
  * @param offset an offset within the document
  * @return true if the character at the specified offset is not a type parameter start bracket
  * @throws BadLocationException
  */
 private boolean isLessThanOperator(IDocument document, int offset) throws BadLocationException {
   if (offset < 0) return false;
   JavaHeuristicScanner scanner =
       new JavaHeuristicScanner(
           document,
           IJavaPartitions.JAVA_PARTITIONING,
           TextUtilities.getContentType(
               document, IJavaPartitions.JAVA_PARTITIONING, offset, false));
   return !isTypeParameterBracket(offset, document, scanner);
 }
  private void autoEditAfterNewLine(IDocument document, DocumentCommand command) {
    if (command.offset == -1 || document.getLength() == 0) {
      return;
    }

    try {
      int p = command.offset == document.getLength() ? command.offset - 1 : command.offset;
      IRegion info = document.getLineInformationOfOffset(p);
      int start = info.getOffset();

      StringBuffer buf = new StringBuffer(command.text);

      int end = findEndOfWhiteSpaceAfter(document, start, command.offset);

      String lineSpaces = (end > start) ? document.get(start, end - start) : "";
      buf.append(lineSpaces);

      if (isAfterOpenBrace(document, command.offset - 1, start)) {
        buf.append(
            IndenterUtil.createWhiteSpace(1, 0, TextUtilities.getDefaultLineDelimiter(document)));

        if (isBeforeCloseBrace(document, command.offset, info.getOffset() + info.getLength())) {
          command.shiftsCaret = false;
          command.caretOffset = command.offset + buf.length();

          buf.append(command.text);
          buf.append(lineSpaces);
        }
        command.text = buf.toString();
      } else {
        int indent = computeIndentCount(document, command.offset);
        if (isBeforeCloseBrace(document, command.offset, info.getOffset() + info.getLength())) {
          indent--;
        }
        command.text +=
            IndenterUtil.createWhiteSpace(
                indent, 0, TextUtilities.getDefaultLineDelimiter(document));
      }
    } catch (BadLocationException e) {
      KotlinLogger.logAndThrow(e);
    }
  }
  private Object startRewriteSession(ITextFileBuffer fileBuffer) {
    Object stateData = null;

    IDocument document = fileBuffer.getDocument();
    if (document instanceof IDocumentExtension4) {
      IDocumentExtension4 extension = (IDocumentExtension4) document;
      fDocumentRewriteSession = extension.startRewriteSession(getDocumentRewriteSessionType());
    } else stateData = TextUtilities.removeDocumentPartitioners(document);

    return stateData;
  }
 @Override
 protected int createBackwardBound(final int start) throws BadLocationException {
   final IPartitionConstraint matcher = getPartitionConstraint();
   assert (!matcher.matches(IDocument.DEFAULT_CONTENT_TYPE));
   if (matcher.matches(Rweave.R_DEFAULT_CONTENT_TYPE)) {
     final ITypedRegion cat = Rweave.R_TEX_CAT_UTIL.getCat(fDocument, start);
     return cat.getOffset();
   }
   final ITypedRegion partition =
       TextUtilities.getPartition(fDocument, getPartitioning(), start, false);
   return partition.getOffset();
 }
  /**
   * Checks whether <code>position</code> resides in a default (Java) partition of <code>document
   * </code>.
   *
   * @param document the document being modified
   * @param position the position to be checked
   * @param partitioning the document partitioning
   * @return <code>true</code> if <code>position</code> is in the default partition of <code>
   *     document</code>, <code>false</code> otherwise
   */
  private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
    Assert.isTrue(position >= 0);
    Assert.isTrue(position <= document.getLength());

    try {
      ITypedRegion region = TextUtilities.getPartition(document, partitioning, position, false);
      return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);

    } catch (BadLocationException e) {
    }

    return false;
  }
 @Override
 protected String resolve(final TemplateContext context) {
   String value = super.resolve(context);
   final int length = value.length();
   if (length > 0 && context instanceof DocumentTemplateContext) {
     final char c = value.charAt(length - 1);
     if (c != '\n' && c != '\r') {
       value +=
           TextUtilities.getDefaultLineDelimiter(
               ((DocumentTemplateContext) context).getDocument());
     }
   }
   return value;
 }
  private static boolean isInJavadoc(JavaEditor editor) {
    ITextSelection selection = getTextSelection(editor);
    if (selection == null) return false;

    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    try {
      String contentType =
          TextUtilities.getContentType(
              document, IJavaPartitions.JAVA_PARTITIONING, selection.getOffset(), true);
      return contentType.equals(IJavaPartitions.JAVA_DOC);
    } catch (BadLocationException e) {
      return false;
    }
  }
  private void AtlStringIndentAfterNewLine(IDocument document, DocumentCommand command)
      throws BadLocationException {

    ITypedRegion partition =
        TextUtilities.getPartition(document, fPartitioning, command.offset, true);
    int offset = partition.getOffset();
    int length = partition.getLength();

    if (command.offset == offset + length && document.getChar(offset + length - 1) == '\'') return;

    String indentation = getLineIndentation(document, command.offset);
    String delimiter = TextUtilities.getDefaultLineDelimiter(document);

    IRegion line = document.getLineInformationOfOffset(offset);
    String string = document.get(line.getOffset(), offset - line.getOffset());
    if (string.trim().length() != 0) indentation += String.valueOf("\t\t");

    IPreferenceStore preferenceStore = AtlUIPlugin.getDefault().getPreferenceStore();
    if (isLineDelimiter(document, command.text))
      command.text = "\' +" + command.text + indentation + "\'";
    else if (command.text.length() > 1
        && preferenceStore.getBoolean(AtlPreferenceConstants.TYPING_ESCAPE_STRINGS))
      command.text = getModifiedText(command.text, indentation, delimiter);
  }
 private ITypedRegion getPartition(IDocument doc, int offset) {
   ITypedRegion tr = null;
   // not sure why document would ever be null, but put in this
   // guard for
   // https://bugs.eclipse.org/bugs/show_bug.cgi?id=86069
   if (doc != null) {
     try {
       tr =
           TextUtilities.getPartition(
               doc, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, offset, false);
     } catch (BadLocationException e) {
       if (DEBUG) Logger.logException("problem getting partition at: " + offset, e); // $NON-NLS-1$
     }
   }
   return tr;
 }
示例#20
0
  /**
   * Is the given selection single-line commented?
   *
   * @param selection Selection to check
   * @return <code>true</code> iff all selected lines are commented
   */
  private boolean isSelectionCommented(ISelection selection) {
    if (!(selection instanceof ITextSelection)) return false;

    ITextSelection textSelection = (ITextSelection) selection;
    if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) return false;

    IDocument document = fViewer.getDocument();

    try {

      IRegion block = getTextBlockFromSelection(textSelection, document);
      ITypedRegion[] regions =
          TextUtilities.computePartitioning(
              document, fDocumentPartitioning, block.getOffset(), block.getLength(), false);

      //			int lineCount= 0;
      int[] lines = new int[regions.length * 2]; // [startline, endline, startline, endline, ...]
      for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
        // start line of region
        lines[j] = getFirstCompleteLineOfRegion(regions[i], document);
        // end line of region
        int length = regions[i].getLength();
        int offset = regions[i].getOffset() + length;
        if (length > 0) offset--;
        lines[j + 1] = (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));
        //				lineCount += lines[j + 1] - lines[j] + 1;
      }

      // Perform the check
      for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
        String[] prefixes = fPrefixesMap.get(regions[i].getType());
        if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0)
          if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document)) return false;
      }

      return true;

    } catch (BadLocationException x) {
      // should not happen
      // FIXME			Activator.getPlugin().log(x);
    }

    return false;
  }
  private void autoEditBeforeCloseBrace(IDocument document, DocumentCommand command) {
    if (isNewLineBefore(document, command.offset)) {
      try {
        int spaceLength =
            command.offset - findEndOfWhiteSpaceBefore(document, command.offset - 1, 0) - 1;

        command.text =
            IndenterUtil.createWhiteSpace(
                    computeIndentCount(document, command.offset) - 1,
                    0,
                    TextUtilities.getDefaultLineDelimiter(document))
                + CLOSING_BRACE_STRING;
        command.offset -= spaceLength;
        document.replace(command.offset, spaceLength, "");
      } catch (BadLocationException e) {
        KotlinLogger.logAndThrow(e);
      }
    }
  }
  /*
   * @see org.eclipse.jdt.internal.ui.text.spelling.SpellingEngine#check(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IRegion[], org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker, org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector, org.eclipse.core.runtime.IProgressMonitor)
   */
  protected void check(
      IDocument document,
      IRegion[] regions,
      ISpellChecker checker,
      ISpellingProblemCollector collector,
      IProgressMonitor monitor) {
    SpellEventListener listener = new SpellEventListener(collector, document);
    boolean isIgnoringJavaStrings =
        PreferenceConstants.getPreferenceStore()
            .getBoolean(PreferenceConstants.SPELLING_IGNORE_JAVA_STRINGS);
    try {
      for (int i = 0; i < regions.length; i++) {
        IRegion region = regions[i];
        ITypedRegion[] partitions =
            TextUtilities.computePartitioning(
                document,
                IJavaPartitions.JAVA_PARTITIONING,
                region.getOffset(),
                region.getLength(),
                false);
        for (int index = 0; index < partitions.length; index++) {
          if (monitor != null && monitor.isCanceled()) return;

          if (listener.isProblemsThresholdReached()) return;

          ITypedRegion partition = partitions[index];
          final String type = partition.getType();

          if (isIgnoringJavaStrings && type.equals(IJavaPartitions.JAVA_STRING)) continue;

          if (!type.equals(IDocument.DEFAULT_CONTENT_TYPE)
              && !type.equals(IJavaPartitions.JAVA_CHARACTER))
            checker.execute(
                listener, new SpellCheckIterator(document, partition, checker.getLocale()));
        }
      }
    } catch (BadLocationException x) {
      // ignore: the document has been changed in another thread and will be checked again
    } catch (AssertionFailedException x) {
      // ignore: the document has been changed in another thread and will be checked again
    }
  }
示例#23
0
  public void run(IStructuredSelection selection) {
    final ModuleCollector collector = new ModuleCollector();

    // Add by Oliver. Fill the source model into collector.modules.
    initSelectedVjoType(selection, collector);

    if (!collector.modules.isEmpty()) {
      for (Iterator i = collector.modules.iterator(); i.hasNext(); ) {
        final ISourceModule module = (ISourceModule) i.next();
        final IResource resource = module.getResource();
        if (resource != null && resource.getType() == IResource.FILE && resource.exists()) {
          final IScriptProject project = module.getScriptProject();
          final IScriptFormatterFactory formatterFactory =
              ScriptFormatterManager.getSelected(project);
          if (formatterFactory != null) {
            try {
              final String source = module.getSource();
              final Document document = new Document(source);
              final String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
              final Map preferences =
                  formatterFactory.retrievePreferences(new PreferencesLookupDelegate(project));
              final IScriptFormatter formatter =
                  formatterFactory.createFormatter(lineDelimiter, preferences);
              final TextEdit edit = formatter.format(source, 0, source.length(), 0);
              if (edit != null) {
                edit.apply(document);
                final String newSource = document.get();
                if (!source.equals(newSource)) {
                  module.becomeWorkingCopy(null, null);
                  module.getBuffer().setContents(newSource);
                  module.commitWorkingCopy(true, null);
                }
              }
            } catch (Exception e) {
              DLTKUIPlugin.log(e);
              break;
            }
          }
        }
      }
    }
  }
  /*
   * @see TemplateContext#evaluate(Template template)
   */
  @Override
  public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
    clear();

    if (!canEvaluate(template))
      throw new TemplateException(JavaTemplateMessages.Context_error_cannot_evaluate);

    TemplateTranslator translator =
        new TemplateTranslator() {
          @Override
          protected TemplateVariable createVariable(
              TemplateVariableType type, String name, int[] offsets) {
            //				TemplateVariableResolver resolver= getContextType().getResolver(type.getName());
            //				return resolver.createVariable();

            MultiVariable variable = new JavaVariable(type, name, offsets);
            fVariables.put(name, variable);
            return variable;
          }
        };
    TemplateBuffer buffer = translator.translate(template);

    getContextType().resolve(buffer, this);

    rewriteImports();

    IPreferenceStore prefs = JavaPlugin.getDefault().getPreferenceStore();
    boolean useCodeFormatter = prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);

    IJavaProject project = getJavaProject();
    JavaFormatter formatter =
        new JavaFormatter(
            TextUtilities.getDefaultLineDelimiter(getDocument()),
            getIndentation(),
            useCodeFormatter,
            project);
    formatter.format(buffer, this);

    clear();

    return buffer;
  }
    @Override
    protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
      try {
        String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
        final IJavaProject project = getCompilationUnit().getJavaProject();
        IRegion region = document.getLineInformationOfOffset(fInsertPosition);

        String lineContent = document.get(region.getOffset(), region.getLength());
        String indentString = Strings.getIndentString(lineContent, project);
        String str = Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
        InsertEdit edit = new InsertEdit(fInsertPosition, str);
        rootEdit.addChild(edit);
        if (fComment.charAt(fComment.length() - 1) != '\n') {
          rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
          rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
        }
      } catch (BadLocationException e) {
        throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
      }
    }
示例#26
0
 /**
  * Override a DocumentCommand if it ends with a line delim (CR) to include space characters for
  * autoindentation
  *
  * @param d the document
  * @param c the command
  */
 @Override
 public void customizeDocumentCommand(final IDocument d, final DocumentCommand c) {
   if (c.length == 0 && c.text != null) {
     if (TextUtilities.endsWith(d.getLegalLineDelimiters(), c.text) != -1) {
       autoIndentAfterNewLine(d, c);
     } else if (c.text.endsWith(",")) {
       autoIndentAfterNewLine(d, c);
     } else if (c.text.endsWith(";")) {
       autoIndentAfterNewLine(d, c);
     } else if (c.text.endsWith(".")) {
       autoIndentAfterNewLine(d, c);
     } else if (c.text.endsWith(">")) {
       try {
         if (c.offset > 0 && c.offset <= d.getLength() && d.getChar(c.offset - 1) == '-') {
           autoIndentAfterNewLine(d, c);
         }
       } catch (final BadLocationException e) {
         // never mind...
       }
     }
   }
 }
  @Override
  public void customizeDocumentCommand(final IDocument d, final DocumentCommand c) {
    if (TextUtilities.endsWith(d.getLegalLineDelimiters(), c.text) != -1) {
      // Start autoindentation after a cabal section (e.g., global, executable, library)
      try {
        IRegion r = d.getLineInformation(d.getLineOfOffset(c.offset));
        String s = d.get(r.getOffset(), r.getLength()).toLowerCase();

        for (String section : CabalSyntax.sections.keySet()) {
          if (s.equals(section) || s.startsWith(section + " ")) { // $NON-NLS-1$
            char[] ch = new char[getTabWidth()];
            Arrays.fill(ch, ' ');
            c.text = c.text + new String(ch);
          }
        }
      } catch (BadLocationException ble) {
        // ignore
      }
    } else {
      // Superclass takes care of autoindentation
      super.customizeDocumentCommand(d, c);
    }
  }
示例#28
0
    /**
     * Tries to make a text hover focusable (or "sticky").
     *
     * @param sourceViewer the source viewer to display the hover over
     * @param textHover the hover to make focusable
     * @return <code>true</code> if successful, <code>false</code> otherwise
     */
    @SuppressWarnings("deprecation")
    private boolean makeTextHoverFocusable(ISourceViewer sourceViewer, ITextHover textHover) {
      Point hoverEventLocation = ((ITextViewerExtension2) sourceViewer).getHoverEventLocation();
      int offset =
          computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
      if (offset == -1) return false;

      try {
        IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset);
        if (hoverRegion == null) return false;

        String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion);

        IInformationControlCreator controlCreator = null;
        if (textHover instanceof IInformationProviderExtension2)
          controlCreator =
              ((IInformationProviderExtension2) textHover).getInformationPresenterControlCreator();

        IInformationProvider informationProvider =
            new InformationProvider(hoverRegion, hoverInfo, controlCreator);

        fInformationPresenter.setOffset(offset);
        fInformationPresenter.setAnchor(AbstractInformationControlManager.ANCHOR_BOTTOM);
        fInformationPresenter.setMargins(
            6, 6); // default values from AbstractInformationControlManager
        String contentType =
            TextUtilities.getContentType(
                sourceViewer.getDocument(), AutoconfPartitionScanner.AUTOCONF_MACRO, offset, true);
        fInformationPresenter.setInformationProvider(informationProvider, contentType);
        fInformationPresenter.showInformation();

        return true;

      } catch (BadLocationException e) {
        return false;
      }
    }
 /**
  * Returns the partition type located at offset in the document
  *
  * @param document - assumes document is not null
  * @param offset
  * @return String partition type
  */
 protected String getPartitionType(IDocument document, int offset) {
   String type = null;
   try {
     // TODO: provide partitioning information so we're not using a default like this
     if (document instanceof IStructuredDocument) {
       type =
           TextUtilities.getContentType(
               document, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, offset, false);
     }
   } catch (BadLocationException e1) {
   } finally {
     if (type == null) {
       try {
         ITypedRegion region = document.getPartition(offset);
         if (region != null) {
           type = region.getType();
         }
       } catch (BadLocationException e) {
         type = null;
       }
     }
   }
   return type;
 }
  /**
   * Returns a segmentation of the line of the given document appropriate for Bidi rendering.
   *
   * @param document the document
   * @param baseLevel the base level of the line
   * @param lineStart the offset of the line
   * @param lineText Text of the line to retrieve Bidi segments for
   * @return the line's Bidi segmentation
   * @throws BadLocationException in case lineOffset is not valid in document
   */
  protected static int[] getBidiLineSegments(
      IDocument document, int baseLevel, int lineStart, String lineText)
      throws BadLocationException {

    if (lineText == null || document == null) return null;

    int lineLength = lineText.length();
    if (lineLength <= 2) return null;

    // Have ICU compute embedding levels. Consume these levels to reduce
    // the Bidi impact, by creating selective segments (preceding
    // character runs with a level mismatching the base level).
    // XXX: Alternatively, we could apply TextLayout. Pros would be full
    // synchronization with the underlying StyledText's (i.e. native) Bidi
    // implementation. Cons are performance penalty because of
    // unavailability of such methods as isLeftToRight and getLevels.

    Bidi bidi = new Bidi(lineText, baseLevel);
    if (bidi.isLeftToRight())
      // Bail out if this is not Bidi text.
      return null;

    IRegion line = document.getLineInformationOfOffset(lineStart);
    ITypedRegion[] linePartitioning =
        TextUtilities.computePartitioning(
            document, IJavaPartitions.JAVA_PARTITIONING, lineStart, line.getLength(), false);
    if (linePartitioning == null || linePartitioning.length < 1) return null;

    int segmentIndex = 1;
    int[] segments = new int[lineLength + 1];
    byte[] levels = bidi.getLevels();
    int nPartitions = linePartitioning.length;
    for (int partitionIndex = 0; partitionIndex < nPartitions; partitionIndex++) {

      ITypedRegion partition = linePartitioning[partitionIndex];
      int lineOffset = partition.getOffset() - lineStart;
      // Assert.isTrue(lineOffset >= 0 && lineOffset < lineLength);

      if (lineOffset > 0
          && isMismatchingLevel(levels[lineOffset], baseLevel)
          && isMismatchingLevel(levels[lineOffset - 1], baseLevel)) {
        // Indicate a Bidi segment at the partition start - provided
        // levels of both character at the current offset and its
        // preceding character mismatch the base paragraph level.
        // Partition end will be covered either by the start of the next
        // partition, a delimiter inside a next partition, or end of line.
        segments[segmentIndex++] = lineOffset;
      }
      if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
        int partitionEnd = Math.min(lineLength, lineOffset + partition.getLength());
        while (++lineOffset < partitionEnd) {
          if (isMismatchingLevel(levels[lineOffset], baseLevel)
              && String.valueOf(lineText.charAt(lineOffset)).matches(BIDI_DELIMITERS)) {
            // For default content types, indicate a segment before
            // a delimiting character with a mismatching embedding
            // level.
            segments[segmentIndex++] = lineOffset;
          }
        }
      }
    }
    if (segmentIndex <= 1) return null;

    segments[0] = 0;
    if (segments[segmentIndex - 1] != lineLength) segments[segmentIndex++] = lineLength;

    if (segmentIndex == segments.length) return segments;

    int[] newSegments = new int[segmentIndex];
    System.arraycopy(segments, 0, newSegments, 0, segmentIndex);
    return newSegments;
  }