Java Code Examples for org.netbeans.editor.Utilities#getDocument()

The following examples show how to use org.netbeans.editor.Utilities#getDocument() . 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: SchemaBasedCompletionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public int getAutoQueryTypes(JTextComponent component, String typedText) {
       BaseDocument doc = Utilities.getDocument(component);
if ( typedText ==null || typedText.trim().length() ==0 ){
           return 0;
       }
       // do not pop up if the end of text contains some whitespaces.
       if (Character.isWhitespace(typedText.charAt(typedText.length() - 1) )) {
           return 0;
       }
       if(doc == null)
           return 0;
       XMLSyntaxSupport support = XMLSyntaxSupport.getSyntaxSupport(doc);
       if(support != null && CompletionUtil.noCompletion(component) || 
               !CompletionUtil.canProvideCompletion(doc)) {
           return 0;
       }
       
       return COMPLETION_QUERY_TYPE;
   }
 
Example 2
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public PlainTextEditor (final String text) {
  initComponents();

  final JEditorPane editor = UI_COMPO_FACTORY.makeEditorPane();
  editor.setEditorKit(getEditorKit());
  this.document = Utilities.getDocument(editor);

  setText(text);

  final Preferences docPreferences = CodeStylePreferences.get(this.document).getPreferences();
  this.oldWrapping = Wrapping.findFor(docPreferences.get(SimpleValueNames.TEXT_LINE_WRAP, "none"));
  this.wrapping = oldWrapping;

  this.lastComponent = makeEditorForText(this.document);
  this.lastComponent.setPreferredSize(new Dimension(620, 440));
  this.add(this.lastComponent, BorderLayout.CENTER);

  this.labelWrapMode.setMinimumSize(new Dimension(55, this.labelWrapMode.getMinimumSize().height));

  updateBottomPanel();
}
 
Example 3
Source File: ToolTipUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    EditorUI eui = Utilities.getEditorUI(editorPane);
    Point location = et.getLocation();
    location = eui.getStickyWindowSupport().convertPoint(location);
    eui.getToolTipSupport().setToolTipVisible(false);
    DebuggerManager dbMgr = DebuggerManager.getDebuggerManager();
    BaseDocument document = Utilities.getDocument(editorPane);
    DataObject dobj = (DataObject) document.getProperty(Document.StreamDescriptionProperty);
    FileObject fo = dobj.getPrimaryFile();
    Watch.Pin pin = new EditorPin(fo, pinnable.line, location);
    final Watch w = dbMgr.createPinnedWatch(pinnable.expression, pin);
    SwingUtilities.invokeLater(() -> {
        try {
            PinWatchUISupport.getDefault().pin(w, pinnable.valueProviderId);
        } catch (IllegalArgumentException ex) {
            Exceptions.printStackTrace(ex);
        }
    });
}
 
Example 4
Source File: CopyStyleAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    BaseDocument bdoc = Utilities.getDocument(target);
    if(bdoc == null) {
        return ; //no document?!?!
    }
    DataObject csso = NbEditorUtilities.getDataObject(bdoc);
    if(csso == null) {
        return ; //document not backuped by DataObject
    }
    
    String pi = createText(csso);
    StringSelection ss = new StringSelection(pi);
    ExClipboard clipboard = Lookup.getDefault().lookup(ExClipboard.class);
    clipboard.setContents(ss, null);
    StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage(CopyStyleAction.class, "MSG_Style_tag_in_clipboard"));  // NOI18N
    
}
 
Example 5
Source File: ExtKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public boolean gotoDeclaration(JTextComponent target) {
    BaseDocument doc = Utilities.getDocument(target);
    if (doc == null)
        return false;
    try {
        Caret caret = target.getCaret();
        int dotPos = caret.getDot();
        int[] idBlk = Utilities.getIdentifierBlock(doc, dotPos);
        ExtSyntaxSupport extSup = (ExtSyntaxSupport)doc.getSyntaxSupport();
        if (idBlk != null) {
            int decPos = extSup.findDeclarationPosition(doc.getText(idBlk), idBlk[1]);
            if (decPos >= 0) {
                caret.setDot(decPos);
                return true;
            }
        }
    } catch (BadLocationException e) {
    }
    return false;
}
 
Example 6
Source File: NextErrorAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private int findNextUnused(JTextComponent comp, int offset) {
    try {
        BaseDocument doc = Utilities.getDocument(comp);
        int lineStart = Utilities.getRowStart(doc, offset);
        // "unused-browseable" in java.editor/.../ColoringManager and csl.api/.../ColoringManager
        HighlightsSequence s = HighlightingManager.getInstance(comp).getBottomHighlights().getHighlights(lineStart, Integer.MAX_VALUE);
        int lastUnusedEndOffset = -1;

        while (s.moveNext()) {
            AttributeSet attrs = s.getAttributes();
            if (attrs != null && attrs.containsAttribute("unused-browseable", Boolean.TRUE)) {
                
                if (lastUnusedEndOffset != s.getStartOffset() && s.getStartOffset() >= offset) {
                    return s.getStartOffset();
                }
                lastUnusedEndOffset = s.getEndOffset();
            }
        }

        return -1;
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
        return -1;
    }
}
 
Example 7
Source File: NextErrorAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<ErrorDescription> findNextError(JTextComponent comp, int offset) {
    Document doc = Utilities.getDocument(comp);
    Object stream = doc.getProperty(Document.StreamDescriptionProperty);
    
    if (!(stream instanceof DataObject)) {
        return Collections.emptyList();
    }
    
    AnnotationHolder holder = AnnotationHolder.getInstance(((DataObject) stream).getPrimaryFile());
    
    List<ErrorDescription> errors = holder.getErrorsGE(offset);
    
    return errors;
}
 
Example 8
Source File: ShowMembersAtCaretAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JavaSource getContext(JTextComponent target) {
    final Document doc = Utilities.getDocument(target);
    if (doc == null) {
        return null;
    }
    return JavaSource.forDocument(doc);
}
 
Example 9
Source File: SelectConnectionAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target == null) {
        return;
    }

    Document doc = Utilities.getDocument(target);
    DatabaseConnectionSupport.selectDatabaseConnection(doc);
}
 
Example 10
Source File: ExtFormatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean hasTextBefore(JTextComponent target, String typedText) {
    BaseDocument doc = Utilities.getDocument(target);
    int dotPos = target.getCaret().getDot();
    try {
        int fnw = Utilities.getRowFirstNonWhite(doc, dotPos);
        return dotPos != fnw+typedText.length();
    } catch (BadLocationException e) {
        return false;
    }
}
 
Example 11
Source File: GotoAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    String actionName = actionName();
    if (EditorActionNames.gotoDeclaration.equals(actionName)) {
        resetCaretMagicPosition(target);
        if (target != null) {
            if (hyperlinkGoTo(target)) {
                return;
            }
            
            BaseDocument doc = Utilities.getDocument(target);
            if (doc != null) {
                try {
                    Caret caret = target.getCaret();
                    int dotPos = caret.getDot();
                    int[] idBlk = Utilities.getIdentifierBlock(doc, dotPos);
                    ExtSyntaxSupport extSup = (ExtSyntaxSupport) doc.getSyntaxSupport();
                    if (idBlk != null) {
                        int decPos = extSup.findDeclarationPosition(doc.getText(idBlk), idBlk[1]);
                        if (decPos >= 0) {
                            caret.setDot(decPos);
                        }
                    }
                } catch (BadLocationException e) {
                }
            }
        }
    }
}
 
Example 12
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 13
Source File: CompletionJListOperator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void start() {
    JTextComponent jtc = EditorRegistry.lastFocusedComponent();
    doc = jtc != null ? Utilities.getDocument(jtc) : null;
    if (doc != null) {
        doc.addDocumentListener(listener);
    }
    modified = false;
    active = true;
}
 
Example 14
Source File: LayoutCompletionProvider.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public int getAutoQueryTypes(JTextComponent component, String typedText) {
    BaseDocument doc = Utilities.getDocument(component);
    if (typedText == null || typedText.trim().length() == 0) {
        return 0;
    }
    // do not pop up if the end of text contains some whitespaces.
    if (Character.isWhitespace(typedText.charAt(typedText.length() - 1))) {
        return 0;
    }
    if (doc == null) {
        return 0;
    }
    XMLSyntaxSupport support = XMLSyntaxSupport.getSyntaxSupport(doc);
    if (support != null && CompletionUtil.noCompletion(component)
            || !CompletionUtil.canProvideCompletion(doc)) {
        return 0;
    }
    FileObject primaryFile = CompletionUtil.getPrimaryFile(component.getDocument());
    Project owner = FileOwnerQuery.getOwner(primaryFile);
    if (owner instanceof NbAndroidProject) {
        AndroidProject androidProject = owner.getLookup().lookup(AndroidProject.class);
        if (androidProject != null) {
            String next = androidProject.getBootClasspath().iterator().next();
            AndroidJavaPlatform findPlatform = AndroidJavaPlatformProvider.findPlatform(next, androidProject.getCompileTarget());
            if (findPlatform == null) {
                return 0;
            }
        } else {
            return 0;
        }
    } else {
        return 0;
    }

    return COMPLETION_QUERY_TYPE;
}
 
Example 15
Source File: ShowHierarchyAtCaretAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JavaSource getContext(JTextComponent target) {
    final Document doc = Utilities.getDocument(target);
    if (doc == null) {
        return null;
    }
    return JavaSource.forDocument(doc);
}
 
Example 16
Source File: CodeFoldingSideBar.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void performActionAt(Mark mark, int mouseY) throws BadLocationException {
    if (mark != null) {
        return;
    }
    BaseDocument bdoc = Utilities.getDocument(component);
    BaseTextUI textUI = (BaseTextUI)component.getUI();

    View rootView = Utilities.getDocumentView(component);
    if (rootView == null) return;
    
    bdoc.readLock();
    try {
        int yOffset = textUI.getPosFromY(mouseY);
        FoldHierarchy hierarchy = FoldHierarchy.get(component);
        hierarchy.lock();
        try {
            Fold f = FoldUtilities.findOffsetFold(hierarchy, yOffset);
            if (f == null) {
                return;
            }
            if (f.isCollapsed()) {
                LOG.log(Level.WARNING, "Clicked on a collapsed fold {0} at {1}", new Object[] { f, mouseY });
                return;
            }
            int startOffset = f.getStartOffset();
            int endOffset = f.getEndOffset();
            
            int startY = textUI.getYFromPos(startOffset);
            int nextLineOffset = Utilities.getRowStart(bdoc, startOffset, 1);
            int nextY = textUI.getYFromPos(nextLineOffset);

            if (mouseY >= startY && mouseY <= nextY) {
                LOG.log(Level.FINEST, "Starting line clicked, ignoring. MouseY={0}, startY={1}, nextY={2}",
                        new Object[] { mouseY, startY, nextY });
                return;
            }

            startY = textUI.getYFromPos(endOffset);
            nextLineOffset = Utilities.getRowStart(bdoc, endOffset, 1);
            nextY = textUI.getYFromPos(nextLineOffset);

            if (mouseY >= startY && mouseY <= nextY) {
                // the mouse can be positioned above the marker (the fold found above), or
                // below it; in that case, the immediate enclosing fold should be used - should be the fold
                // that corresponds to the nextLineOffset, if any
                int h2 = (startY + nextY) / 2;
                if (mouseY >= h2) {
                    Fold f2 = f;
                    
                    f = FoldUtilities.findOffsetFold(hierarchy, nextLineOffset);
                    if (f == null) {
                        // fold does not exist for the position below end-of-fold indicator
                        return;
                    }
                }
                
            }
            
            LOG.log(Level.FINEST, "Collapsing fold: {0}", f);
            hierarchy.collapse(f);
        } finally {
            hierarchy.unlock();
        }
    } finally {
        bdoc.readUnlock();
    }        
}
 
Example 17
Source File: GotoDialogSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Perform the goto operation.
 * @return whether the dialog should be made invisible or not
 */
protected boolean performGoto() {
    JTextComponent c = EditorRegistry.lastFocusedComponent();
    if (c != null) {
        try {
            int line = Integer.parseInt(getGotoValueText());

            //issue 188976
            if (line==0)
                line = 1;
            //end of issue 188976
            
            BaseDocument doc = Utilities.getDocument(c);
            if (doc != null) {
                int rowCount = Utilities.getRowCount(doc);
                if (line > rowCount)
                    line = rowCount;
                
                // Obtain the offset where to jump
                int pos = Utilities.getRowStartFromLineOffset(doc, line - 1);
                
                BaseKit kit = Utilities.getKit(c);
                if (kit != null) {
                    Action a = kit.getActionByName(ExtKit.gotoAction);
                    if (a instanceof ExtKit.GotoAction) {
                        pos = ((ExtKit.GotoAction)a).getOffsetFromLine(doc, line - 1);
                    }
                }
                
                if (pos != -1) {
                    Caret caret = c.getCaret();
                    caret.setDot(pos);
                } else {
                    c.getToolkit().beep();
                    return false;
                }
            }
        } catch (NumberFormatException e) {
            c.getToolkit().beep();
            return false;
        }
    }
    return true;
}
 
Example 18
Source File: TagBasedFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override public int[] getReformatBlock(JTextComponent target, String typedText) {
    BaseDocument doc = Utilities.getDocument(target);
    
    if (!hasValidSyntaxSupport(doc)){
        return null;
    }
    
    char lastChar = typedText.charAt(typedText.length() - 1);
    
    try{
        int dotPos = target.getCaret().getDot();
        
        if (lastChar == '>') {
            TokenItem tknPrecedingToken = getTagTokenEndingAtPosition(doc, dotPos - 1);
            
            if (isClosingTag(tknPrecedingToken)){
                // the user has just entered a closing tag
                // - reformat it unless matching opening tag is on the same line 
                
                TokenItem tknOpeningTag = getMatchingOpeningTag(tknPrecedingToken);
                
                if (tknOpeningTag != null){
                    int openingTagLine = Utilities.getLineOffset(doc, tknOpeningTag.getOffset());
                    int closingTagSymbolLine = Utilities.getLineOffset(doc, dotPos);
                    
                    if(openingTagLine != closingTagSymbolLine){
                        return new int[]{tknPrecedingToken.getOffset(), dotPos};
                    }
                }
            }
        }
        
        else if(lastChar == '\n') {
            // just pressed enter
            enterPressed(target, dotPos);
        }
        
    } catch (Exception e){
        ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
    }
    
    return null;
}
 
Example 19
Source File: MacroDialogSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("actionCommand='" + evt.getActionCommand() //NOI18N
                + "', modifiers=" + evt.getModifiers() //NOI18N
                + ", when=" + evt.getWhen() //NOI18N
                + ", paramString='" + evt.paramString() + "'"); //NOI18N
    }
    
    if (target == null) {
        return;
    }

    BaseKit kit = Utilities.getKit(target);
    if (kit == null) {
        return;
    }

    BaseDocument doc = Utilities.getDocument(target);
    if (doc == null) {
        return;
    }

    // changed as reponse to #250157: other events may get fired during
    // the course of key binding processing and if an event is processed
    // as nested (i.e. hierarchy change resulting from a component retracting from the screen),
    // thie following test would fail.
    AWTEvent maybeKeyEvent = EventQueue.getCurrentEvent();
    KeyStroke keyStroke = null;
    
    if (maybeKeyEvent instanceof KeyEvent) {
        keyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent) maybeKeyEvent);
    }

    // try simple keystorkes first
    MimePath mimeType = MimePath.parse(NbEditorUtilities.getMimeType(target));
    MacroDescription macro = null;
    if (keyStroke != null) {
        macro = findMacro(mimeType, keyStroke);
    } else {
        LOG.warning("KeyStroke could not be created for event " + maybeKeyEvent);
    }
    if (macro == null) {
        // if not found, try action command, which should contain complete multi keystroke
        KeyStroke[] shortcut = KeyStrokeUtils.getKeyStrokes(evt.getActionCommand());
        if (shortcut != null) {
            macro = findMacro(mimeType, shortcut);
        } else {
            LOG.warning("KeyStroke could not be created for action command " + evt.getActionCommand());
        }
    }

    if (macro == null) {
        error(target, "macro-not-found", KeyStrokeUtils.getKeyStrokeAsText(keyStroke)); // NOI18N
        return;
    }

    if (!runningActions.add(macro.getName())) { // this macro is already running, beware of loops
        error(target, "macro-loop", macro.getName()); // NOI18N
        return;
    }
    try {
        runMacro(target, doc, kit, macro);
    } finally {
        runningActions.remove(macro.getName());
    }
}