org.netbeans.editor.Utilities Java Examples

The following examples show how to use org.netbeans.editor.Utilities. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean allComments(BaseDocument doc, int startOffset, int lineCount) throws BadLocationException {
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
        if (firstNonWhitePos == -1) {
            return false;
        }
        
        if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos < lineCommentStringLen) {
            return false;
        }
        
        CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
        if (!CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
            return false;
        }
        
        offset = Utilities.getRowStart(doc, offset, +1);
    }
    return true;
}
 
Example #2
Source File: JspPaletteActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {

      ActiveEditorDrop drop = (ActiveEditorDrop) item.lookup(ActiveEditorDrop.class);
      
      JTextComponent target = Utilities.getFocusedComponent();
      if (target == null) {
          String msg = NbBundle.getMessage(JspPaletteActions.class, "MSG_ErrorNoFocusedDocument");
          DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
          return;
      }
      
      try {
          drop.handleTransfer(target);
      }
      finally {
          Utilities.requestFocus(target);
      }
      
      try {
          PaletteController pc = JspPaletteFactory.getPalette();
          pc.clearSelection();
      }
      catch (IOException ioe) {
          //should not occur
      } 
  }
 
Example #3
Source File: ToggleCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void commentLine(BaseDocument doc, String mimeType, int offset) throws BadLocationException {
    Feature feature = null;
    try {
        Language language = LanguagesManager.getDefault().getLanguage(mimeType);
        feature = language.getFeatureList ().getFeature (CodeCommentAction.COMMENT_LINE);
    } catch (LanguageDefinitionNotFoundException e) {
    }
    if (feature != null) {
        String prefix = (String) feature.getValue("prefix"); // NOI18N
        if (prefix == null) {
            return;
        }
        String suffix = (String) feature.getValue("suffix"); // NOI18N
        if (suffix != null) {
            int end = Utilities.getRowEnd(doc, offset);
            doc.insertString(end, suffix, null);
        }
        doc.insertString(offset, prefix, null);
    }
}
 
Example #4
Source File: NbToolTip.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static int getOffsetForPoint(Point p, JTextComponent c, BaseDocument doc) throws BadLocationException {
    if (p.x >= 0 && p.y >= 0) {
        int offset = c.viewToModel(p);
        Rectangle r = c.modelToView(offset);
        EditorUI eui = Utilities.getEditorUI(c);

        // Check that p is on a line with text and not completely below text,
        // ie. behind EOF.
        int relY = p.y - r.y;
        if (eui != null && relY < eui.getLineHeight()) {
            // Check that p is on a line with text before its EOL.
            if (offset < Utilities.getRowEnd(doc, offset)) {
                return offset;
            }
        }
    }
    
    return -1;
}
 
Example #5
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean allComments(BaseDocument doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
    final int lineCommentStringLen = lineCommentString.length();
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
        if (firstNonWhitePos == -1) {
            return false;
        }

        if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos < lineCommentStringLen) {
            return false;
        }

        CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
        if (!CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
            return false;
        }

        offset = Utilities.getRowStart(doc, offset, +1);
    }
    return true;
}
 
Example #6
Source File: NbEditorUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void stateChanged(ChangeEvent e) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            EditorUI eui = Utilities.getEditorUI(component);
            if (eui != null) {
                JComponent ec = eui.getExtComponent();
                if (ec != null) {
                    JScrollPane scroller = (JScrollPane) ec.getComponent(0);
                    // remove prior to creating new sidebars
                    ec.removeAll();
                    scroller.setRowHeaderView(null);
                    scroller.setColumnHeaderView(null);
                    Map newMap = CustomizableSideBar.getSideBars(component);
                    processSideBars(newMap, ec, scroller);
                    ec.revalidate();
                    ec.repaint();
                }
            }
        }
    });
}
 
Example #7
Source File: YamlKeystrokeHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static int getLineIndent(BaseDocument doc, int offset) {
    try {
        int start = Utilities.getRowStart(doc, offset);
        int end;

        if (Utilities.isRowWhite(doc, start)) {
            end = Utilities.getRowEnd(doc, offset);
        } else {
            end = Utilities.getRowFirstNonWhite(doc, start);
        }

        int indent = Utilities.getVisualColumn(doc, end);

        return indent;
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);

        return 0;
    }
}
 
Example #8
Source File: HierarchyTopComponent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
    if (refreshButton == e.getSource()) {
        final JTextComponent lastFocusedComponent = EditorRegistry.lastFocusedComponent();
        if (lastFocusedComponent != null) {
            final JavaSource js = JavaSource.forDocument(Utilities.getDocument(lastFocusedComponent));
            if (js != null) {
                setContext(js, lastFocusedComponent);
            }
        }
    } else if (jdocButton == e.getSource()) {
        final TopComponent win = JavadocTopComponent.findInstance();
        if (win != null && !win.isShowing()) {
            win.open();
            win.requestVisible();
            jdocTask.schedule(NOW);
        }
    } else if (historyCombo == e.getSource()) {
        refresh();
    } else if (viewTypeCombo == e.getSource()) {
        refresh();
    }
}
 
Example #9
Source File: NbEditorToolBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** See issue #57773 for details. Toolbar should be updated with possible changes after
   module install/uninstall */
private void installModulesInstallationListener(){
    moduleRegListener = new FileChangeAdapter() {
        public @Override void fileChanged(FileEvent fe) {
            //some module installed/uninstalled. Refresh toolbar content
            Runnable r = new Runnable() {
                public void run() {
                    if (isToolbarVisible()) {
                        checkPresentersRemoved();
                        checkPresentersAdded();                                
                    }
                }
             };
            Utilities.runInEventDispatchThread(r);
        }
    };

    FileObject moduleRegistry = FileUtil.getConfigFile("Modules"); //NOI18N

    if (moduleRegistry !=null){
        moduleRegistry.addFileChangeListener(
            FileUtil.weakFileChangeListener(moduleRegListener, moduleRegistry));
    }
}
 
Example #10
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new instance initializing final fields.
 */
public AnnotationBar(JTextComponent target) {
    this.textComponent = target;
    this.editorUI = Utilities.getEditorUI(target);
    this.foldHierarchy = FoldHierarchy.get(editorUI.getComponent());
    this.doc = editorUI.getDocument();
    setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
    elementAnnotationsSubstitute = "";                              //NOI18N
    if (textComponent instanceof JEditorPane) {
        String mimeType = org.netbeans.lib.editor.util.swing.DocumentUtilities.getMimeType(textComponent);
        FontColorSettings fcs = MimeLookup.getLookup(mimeType).lookup(FontColorSettings.class);
        renderingHints = (Map) fcs.getFontColors(FontColorNames.DEFAULT_COLORING).getAttribute(EditorStyleConstants.RenderingHints);
    } else {
        renderingHints = null;
    }
}
 
Example #11
Source File: GroovyFormatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isEndIndent(BaseDocument doc, int offset) throws BadLocationException {
    int lineBegin = Utilities.getRowFirstNonWhite(doc, offset);

    if (lineBegin != -1) {
        Token<GroovyTokenId> token = LexUtilities.getToken(doc, lineBegin);

        if (token == null) {
            return false;
        }

        TokenId id = token.id();

        // If the line starts with an end-marker, such as "end", "}", "]", etc.,
        // find the corresponding opening marker, and indent the line to the same
        // offset as the beginning of that line.
        return (LexUtilities.isIndentToken(id) && !LexUtilities.isBeginToken(id, doc, offset)) ||
            id == GroovyTokenId.RBRACE || id == GroovyTokenId.RBRACKET || id == GroovyTokenId.RPAREN;
    }

    return false;
}
 
Example #12
Source File: HintsUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void keyReleased(KeyEvent e) {
    // Fix (workaround) for issue #186557
    if (org.openide.util.Utilities.isWindows()) {
        if (Boolean.getBoolean("HintsUI.disable.AltEnter.hack")) { // NOI18N
            return;
        }

        if (altEnterPressed && e.getKeyCode() == KeyEvent.VK_ALT) {
            e.consume();
            altReleased = true;
        } else if (altEnterPressed && e.getKeyCode() == KeyEvent.VK_ENTER) {
            altEnterPressed = false;
            if (altReleased) {
                try {
                    java.awt.Robot r = new java.awt.Robot();
                    r.keyRelease(KeyEvent.VK_ALT);
                } catch (AWTException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
}
 
Example #13
Source File: CodeCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void modifyLine(BaseDocument doc, String mimeType, int offset) throws BadLocationException {
    Feature feature = null;
    try {
        Language language = LanguagesManager.getDefault().getLanguage(mimeType);
        feature = language.getFeatureList ().getFeature (COMMENT_LINE);
    } catch (LanguageDefinitionNotFoundException e) {
    }
    if (feature != null) {
        String prefix = (String) feature.getValue("prefix"); // NOI18N
        if (prefix == null) {
            return;
        }
        String suffix = (String) feature.getValue("suffix"); // NOI18N
        if (suffix != null) {
            int end = Utilities.getRowEnd(doc, offset);
            doc.insertString(end, suffix, null);
        }
        doc.insertString(offset, prefix, null);
    }
}
 
Example #14
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void uncomment(BaseDocument doc, int startOffset, int lineCount) throws BadLocationException {
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        // Get the first non-whitespace char on the current line
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);

        // If there is any, check wheter it's the line-comment-chars and remove them
        if (firstNonWhitePos != -1) {
            if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= lineCommentStringLen) {
                CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
                if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
                    doc.remove(firstNonWhitePos, lineCommentStringLen);
                }
            }
        }

        offset = Utilities.getRowStart(doc, offset, +1);
    }
}
 
Example #15
Source File: MulticaretHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private MulticaretHandler(final JTextComponent c) {
    this.doc = c.getDocument();
    doc.render(() -> {
        Caret caret = c.getCaret();
        if (caret instanceof EditorCaret) {
            List<CaretInfo> carets = ((EditorCaret) caret).getCarets();
            if (carets.size() > 1) {
                this.regions = new ArrayList<>(carets.size());
                carets.forEach((ci) -> {
                    try {
                        int[] block = ci.isSelectionShowing() ? null : Utilities.getIdentifierBlock(c, ci.getDot());
                        Position start = NbDocument.createPosition(doc, block != null ? block[0] : ci.getSelectionStart(), Position.Bias.Backward);
                        Position end = NbDocument.createPosition(doc, block != null ? block[1] : ci.getSelectionEnd(), Position.Bias.Forward);
                        regions.add(new MutablePositionRegion(start, end));
                    } catch (BadLocationException ex) {}
                });
                Collections.reverse(regions);
            }
        }
    });
}
 
Example #16
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new instance initializing final fields.
 */
public AnnotationBar(JTextComponent target) {
    this.textComponent = target;
    this.editorUI = Utilities.getEditorUI(target);
    this.foldHierarchy = FoldHierarchy.get(editorUI.getComponent());
    this.doc = editorUI.getDocument();
    setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
    elementAnnotationsSubstitute = "";                              //NOI18N
    if (textComponent instanceof JEditorPane) {
        String mimeType = org.netbeans.lib.editor.util.swing.DocumentUtilities.getMimeType(textComponent);
        FontColorSettings fcs = MimeLookup.getLookup(mimeType).lookup(FontColorSettings.class);
        renderingHints = (Map) fcs.getFontColors(FontColorNames.DEFAULT_COLORING).getAttribute(EditorStyleConstants.RenderingHints);
    } else {
        renderingHints = null;
    }
}
 
Example #17
Source File: JsTypedBreakInterceptor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the indentation of the next line (after the line break).
 * 
 * @param doc document
 * @param offset current offset
 * @return indentation size
 * @throws BadLocationException 
 */
private int getNextLineIndentation(BaseDocument doc, int offset) throws BadLocationException {
    int indent = GsfUtilities.getLineIndent(doc, offset);
    int currentOffset = offset;
    while (currentOffset > 0) {
        if (!Utilities.isRowEmpty(doc, currentOffset) && !Utilities.isRowWhite(doc, currentOffset)
                && !isCommentOnlyLine(doc, currentOffset, language)) {
            indent = GsfUtilities.getLineIndent(doc, currentOffset);
            int parenBalance = getLineBalance(doc, currentOffset,
                    JsTokenId.BRACKET_LEFT_PAREN, JsTokenId.BRACKET_RIGHT_PAREN);
            if (parenBalance < 0) {
                break;
            }
            int curlyBalance = getLineBalance(doc, currentOffset,
                    JsTokenId.BRACKET_LEFT_CURLY, JsTokenId.BRACKET_RIGHT_CURLY);
            if (curlyBalance > 0) {
                indent += IndentUtils.indentLevelSize(doc);
            }
            return indent;
        }
        currentOffset = Utilities.getRowStart(doc, currentOffset) - 1;
    }

    return indent;
}
 
Example #18
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new instance initializing final fields.
 */
public AnnotationBar(JTextComponent target) {
    this.textComponent = target;
    this.editorUI = Utilities.getEditorUI(target);
    this.foldHierarchy = FoldHierarchy.get(editorUI.getComponent());
    this.doc = editorUI.getDocument();
    if (textComponent instanceof JEditorPane) {
        String mimeType = org.netbeans.lib.editor.util.swing.DocumentUtilities.getMimeType(textComponent);
        FontColorSettings fcs = MimeLookup.getLookup(mimeType).lookup(FontColorSettings.class);
        renderingHints = (Map) fcs.getFontColors(FontColorNames.DEFAULT_COLORING).getAttribute(EditorStyleConstants.RenderingHints);
    } else {
        renderingHints = null;
    }
    setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
    elementAnnotationsSubstitute = "";                              //NOI18N
}
 
Example #19
Source File: ToolTipSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Update the tooltip by running corresponding action
 * {@link ExtKit#buildToolTipAction}. This method gets
 * called once the enterTimer fires and it can be overriden
 * by children.
 */
protected void updateToolTip() {
    EditorUI ui = extEditorUI;
    if (ui == null)
        return;
    JTextComponent comp = ui.getComponent();
    if (comp == null)
        return;
    
    JComponent oldTooltip = this.toolTip;
    if (isGlyphGutterMouseEvent(lastMouseEvent)) {
        setToolTipText(extEditorUI.getGlyphGutter().getToolTipText(lastMouseEvent));
    } else { // over the text component
        BaseKit kit = Utilities.getKit(comp);
        if (kit != null) {
            Action a = kit.getActionByName(ExtKit.buildToolTipAction);
            if (a != null) {
                a.actionPerformed(new ActionEvent(comp, 0, "")); // NOI18N
            }
        }
    }
    // tooltip has changed, mark it as 'automatic'
    if (this.toolTip != oldTooltip) {
        tooltipFromView = true;
    }
}
 
Example #20
Source File: CssExternalDropHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<File> textURIListToFileList(String data) {
    List<File> list = new ArrayList<>(1);
    for (StringTokenizer st = new StringTokenizer(data, "\r\n\u0000");
            st.hasMoreTokens();) {
        String s = st.nextToken();
        if (s.startsWith("#")) {
            // the line is a comment (as per the RFC 2483)
            continue;
        }
        try {
            URI uri = new URI(s);
            File file = org.openide.util.Utilities.toFile(uri);
            list.add(file);
        } catch (URISyntaxException | IllegalArgumentException e) {
            // malformed URI
        }
    }
    return list;
}
 
Example #21
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void uncomment(BaseDocument doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
    final int lineCommentStringLen = lineCommentString.length();
    for (int offset = startOffset; lineCount > 0; lineCount--) {
        // Get the first non-whitespace char on the current line
        int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);

        // If there is any, check wheter it's the line-comment-chars and remove them
        if (firstNonWhitePos != -1) {
            if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= lineCommentStringLen) {
                CharSequence maybeLineComment = DocumentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
                if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
                    doc.remove(firstNonWhitePos, lineCommentStringLen);
                }
            }
        }

        offset = Utilities.getRowStart(doc, offset, +1);
    }
}
 
Example #22
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    final AtomicBoolean processedHere = new AtomicBoolean(false);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled() || !(target.getDocument() instanceof BaseDocument)) {
            target.getToolkit().beep();
            return;
        }
        final int caretOffset = Utilities.isSelectionShowing(target) ? target.getSelectionStart() : target.getCaretPosition();
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                performCustomAction(doc, caretOffset, processedHere);
            }
        });
        if (!processedHere.get()) {
            performDefaultAction(evt, target);
        }
    }
}
 
Example #23
Source File: TagBasedLexerFormatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TextBounds findTokenSequenceBounds(BaseDocument doc, TokenSequence tokenSequence) throws BadLocationException {
        tokenSequence.moveStart();
        tokenSequence.moveNext();
        int absoluteStart = tokenSequence.offset();
        tokenSequence.moveEnd();
        tokenSequence.movePrevious();
        int absoluteEnd = tokenSequence.offset() + tokenSequence.token().length();

//         trim whitespaces from both ends
        while (isWSToken(tokenSequence.token())) {
            if (!tokenSequence.movePrevious()) {
                return new TextBounds(absoluteStart, absoluteEnd); // a block of empty text
            }
        }

        int whiteSpaceSuffixLen = 0;

        while (Character.isWhitespace(tokenSequence.token().text().charAt(tokenSequence.token().length() - 1 - whiteSpaceSuffixLen))) {
            whiteSpaceSuffixLen++;
        }

        int languageBlockEnd = tokenSequence.offset() + tokenSequence.token().length() - whiteSpaceSuffixLen;

        tokenSequence.moveStart();

        do {
            tokenSequence.moveNext();
        } while (isWSToken(tokenSequence.token()));

        int whiteSpacePrefixLen = 0;

        while (Character.isWhitespace(tokenSequence.token().text().charAt(whiteSpacePrefixLen))) {
            whiteSpacePrefixLen++;
        }

        int languageBlockStart = tokenSequence.offset() + whiteSpacePrefixLen;
        int firstLineOfTheLanguageBlock = Utilities.getLineOffset(doc, languageBlockStart);
        int lastLineOfTheLanguageBlock = Utilities.getLineOffset(doc, languageBlockEnd);
        return new TextBounds(absoluteStart, absoluteEnd, languageBlockStart, languageBlockEnd, firstLineOfTheLanguageBlock, lastLineOfTheLanguageBlock);
    }
 
Example #24
Source File: StrutsConfigHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages({
        "lbl.goto.formbean.not.found=ActionForm Bean {0} not found."
    })
private void findForm(String name, BaseDocument doc){
    ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport();
    
    int offset = findDefinitionInSection(sup, "form-beans", "form-bean", "name", name);
    if (offset > 0){
        JTextComponent target = Utilities.getFocusedComponent();
        target.setCaretPosition(offset);
    } else {
        StatusDisplayer.getDefault().setStatusText(Bundle.lbl_goto_formbean_not_found(name));
    }
}
 
Example #25
Source File: AbstractIndenter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int findPreviousOccuranceOfOurLanguage(JoinedTokenSequence<T1> ts, int start) throws BadLocationException {
    // this method finds previous non-empty line and
    // will try to find our language there:

    // find line start and move to previous line if possible:
    int lineStart = Utilities.getRowStart(getDocument(), start);
    if (lineStart > 0) {
        lineStart--;
    }
    // find first non-whitespace character going backwards:
    int offset = Utilities.getFirstNonWhiteRow(getDocument(), start, false);
    if (offset == -1) {
        offset = 0;
    }
    // find beginning of this line
    lineStart = Utilities.getRowStart(getDocument(), offset);

    // use line start as beginning for our language search:
    if (ts.move(lineStart, true)) {
        if (!ts.moveNext()) {
            ts.movePrevious();
        }
        offset = ts.offset();
        if (offset > start) {
            return -1;
        } else {
            return offset;
        }
    }
    return -1;
}
 
Example #26
Source File: JavaJspCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public CompletionTask createTask(int queryType, final JTextComponent component) {
    if ((queryType & COMPLETION_QUERY_TYPE) != 0){
        Document doc = Utilities.getDocument(component);
        int caretOffset = component.getCaret().getDot();

        if (isWithinScriptlet(doc, caretOffset)){
            //delegate to java cc provider if the context is really java code
            return new AsyncCompletionTask(new EmbeddedJavaCompletionQuery(component, queryType), component);
        }
    }

    return null;
}
 
Example #27
Source File: XMLLexerFormatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int updateIndent(boolean increase, int targetLevel, boolean preserveAfter) {
    if (preserveAfter) {
        return indentLevel;
    }
    int save = this.indentLevel;
    if (tokenInSelectionRange) {
        if (targetLevel != -1) {
            indentLevel = save = targetLevel;
        }
        if (increase) {
            indentLevel += spacesPerTab;
        } else {
            indentLevel = Math.max(- spacesPerTab, indentLevel - spacesPerTab);
        }
        return save;
    } else {
        try {
            // align with the actual tag:
            indentLevel = Utilities.getVisualColumn((BaseDocument)basedoc, 
                    LineDocumentUtils.getNextNonWhitespace(basedoc, 
                    LineDocumentUtils.getLineStart(basedoc, tokenSequence.offset())));
            if (!increase) {
                indentLevel = Math.max(- spacesPerTab, indentLevel - spacesPerTab);
            }
            return save;
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
            return indentLevel;
        }
    }
}
 
Example #28
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target.isEditable() && target.isEnabled()) {
        final BaseDocument doc = (BaseDocument) target.getDocument();
        final Indent indenter = Indent.get(doc);
        final class R implements Runnable {

            @Override
            public void run() {
                try {
                    Caret caret = target.getCaret();
                    int caretPosition = caret.getDot();
                    int eolOffset = Utilities.getRowEnd(target, caretPosition);
                    doc.insertString(eolOffset, SEMICOLON, null);
                    newLineProcessor.processNewLine(eolOffset, caret, indenter);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        indenter.lock();
        try {
            doc.runAtomicAsUser(new R());
        } finally {
            indenter.unlock();
        }
    }
}
 
Example #29
Source File: ImportHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns line index (line number - 1) of the package statement or {@literal -1}
 * if no package statement was found within this in {@link BaseDocument}.
 *
 * @param doc document
 * @return line index (line number - 1) of the package statement or {@literal -1}
 *         if no package statement was found within this {@link BaseDocument}.
 */
private static int getPackageLineIndex(BaseDocument doc) {
    try {
        int lastPackageOffset = getLastPackageStatementOffset(doc);
        if (lastPackageOffset != -1) {
            return Utilities.getLineOffset(doc, lastPackageOffset);
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    return -1;
}
 
Example #30
Source File: DiffSidebar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void paintComponent(final Graphics g) {
    super.paintComponent(g);
    Utilities.runViewHierarchyTransaction(textComponent, true,
        new Runnable() {
            @Override
            public void run() {
                paintComponentUnderLock(g);
            }
        }
    );
}