org.openide.text.NbDocument Java Examples

The following examples show how to use org.openide.text.NbDocument. 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: UndoableEditWrapperTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapping() throws Exception {
        MimePath mimePath = MimePath.EMPTY;
        MockMimeLookup.setInstances(mimePath, new TestingUndoableEditWrapper(), new TestingUndoableEditWrapper2());
        CESEnv env = new CESEnv();
        Document doc = env.support.openDocument();
//        doc.addUndoableEditListener(new UndoableEditListener() {
//            @Override
//            public void undoableEditHappened(UndoableEditEvent e) {
//                UndoableEdit edit = e.getEdit();
//            }
//        });
        doc.insertString(0, "Test", null);
        Class wrapEditClass = TestingUndoableEditWrapper.WrapCompoundEdit.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass));
        Class wrapEditClass2 = TestingUndoableEditWrapper2.WrapCompoundEdit2.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass2));
        
        // A trick to get whole edit
        UndoableEdit wholeEdit = NbDocument.getEditToBeUndoneOfType(env.support, UndoableEdit.class);
        assertTrue(wholeEdit instanceof List);
        @SuppressWarnings("unchecked")
        List<? extends UndoableEdit> listEdit = (List<? extends UndoableEdit>) wholeEdit;
        assertEquals(3, listEdit.size());
        assertEquals(wrapEditClass, listEdit.get(1).getClass());
        assertEquals(wrapEditClass2, listEdit.get(2).getClass());
    }
 
Example #2
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 #3
Source File: XmlMultiViewElement.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void runInAwt() {
    if (doc instanceof NbDocument.CustomToolbar) {
        realToolBar = ((NbDocument.CustomToolbar) doc).createToolbar(editorPane);
    }
    synchronized (XmlMultiViewElement.this) {
        if (realToolBar == null) {
            toolbar = new JPanel();
        } else {
            toolbar = realToolBar;
        }
        initializer = null;
    }
    if (realToolBar == null) {
        return;
    }
    
    // patch existing toolbars
    for (JComponent p : toolbarPanels) {
        if (p.isValid()) {
            p.add(realToolBar, BorderLayout.CENTER);
        }
    }
}
 
Example #4
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Add the line offset into the jump history */
private void addPositionToJumpList(String url, Line l, int column) {
    DataObject dataObject = getDataObject (url);
    if (dataObject != null) {
        EditorCookie ec = dataObject.getLookup().lookup(EditorCookie.class);
        if (ec != null) {
            try {
                StyledDocument doc = ec.openDocument();
                JEditorPane[] eps = ec.getOpenedPanes();
                if (eps != null && eps.length > 0) {
                    JumpList.addEntry(eps[0], NbDocument.findLineOffset(doc, l.getLineNumber()) + column);
                }
            } catch (java.io.IOException ioex) {
                ErrorManager.getDefault().notify(ioex);
            }
        }
    }
}
 
Example #5
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** return the offset of the first non-whitespace character on the line,
           or -1 when the line does not exist
 */
private static int findLineOffset(StyledDocument doc, int lineNumber) {
    int offset;
    try {
        offset = NbDocument.findLineOffset (doc, lineNumber - 1);
        int offset2 = NbDocument.findLineOffset (doc, lineNumber);
        try {
            String lineStr = doc.getText(offset, offset2 - offset);
            for (int i = 0; i < lineStr.length(); i++) {
                if (!Character.isWhitespace(lineStr.charAt(i))) {
                    offset += i;
                    break;
                }
            }
        } catch (BadLocationException ex) {
            // ignore
        }
    } catch (IndexOutOfBoundsException ioobex) {
        return -1;
    }
    return offset;
}
 
Example #6
Source File: BiAnalyser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void regenerateSourceImpl(StyledDocument doc) {
    NbDocument.runAtomic(doc, new Runnable() {
            public void run()  {
                regenerateBeanDescriptor();
                regenerateProperties();
                regenerateEvents();
                if (!olderVersion) {
                    regenerateMethods();
                }
                regenerateIcons();
                regenerateDefaultIdx();
                regenerateSuperclass();
                isModified = false;
                isIconModified = false;
            }
    } );
}
 
Example #7
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void findResult() {
    
    if (isCanceled())
        return;

    int len = sdoc.getLength();

    if (startOffset >= len || endOffset > len) {
        if (!isCanceled() && ERR.isLoggable(ErrorManager.WARNING)) {
            ERR.log(ErrorManager.WARNING, "document changed, but not canceled?" );
            ERR.log(ErrorManager.WARNING, "len = " + len );
            ERR.log(ErrorManager.WARNING, "startOffset = " + startOffset );
            ERR.log(ErrorManager.WARNING, "endOffset = " + endOffset );
        }
        cancel();

        return;
    }

    try {
        result[0] = NbDocument.createPosition(sdoc, startOffset, Bias.Forward);
        result[1] = NbDocument.createPosition(sdoc, endOffset, Bias.Backward);
    } catch (BadLocationException e) {
        ERR.notify(ErrorManager.ERROR, e);
    }
}
 
Example #8
Source File: ComputeAnnotations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Position getPosition(final StyledDocument doc, final int offset) {
    class Impl implements Runnable {
        private Position pos;
        public void run() {
            if (offset < 0 || offset >= doc.getLength())
                return ;

            try {
                pos = doc.createPosition(offset - NbDocument.findLineColumn(doc, offset));
            } catch (BadLocationException ex) {
                //should not happen?
                Logger.getLogger(ComputeAnnotations.class.getName()).log(Level.FINE, null, ex);
            }
        }
    }

    Impl i = new Impl();

    doc.render(i);

    return i.pos;
}
 
Example #9
Source File: GenerateJavadocAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void generate(final Document doc, final Descriptor desc, final JTextComponent jtc) throws BadLocationException {
    final Indent ie = Indent.get(doc);
    try {
        ie.lock();
        NbDocument.runAtomicAsUser((StyledDocument) doc, new Runnable() {

            public void run() {
                try {
                    int caretPos = jtc.getCaretPosition();
                    generateJavadoc(doc, desc, ie);
                    // move caret
                    jtc.setCaretPosition(caretPos);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

        });
    } finally {
        ie.unlock();
    }
}
 
Example #10
Source File: SourceFileObject.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public synchronized @Override void close() throws IOException {
    try {
        NbDocument.runAtomic(this.doc,
            new Runnable () {
                @Override
                public void run () {
                    try {
                        doc.remove(0,doc.getLength());
                        doc.insertString(0,new String(
                            data,
                            0,
                            pos,
                            FileEncodingQuery.getEncoding(getHandle().resolveFileObject(false))),
                        null);
                    } catch (BadLocationException e) {
                        if (LOG.isLoggable(Level.SEVERE))
                            LOG.log(Level.SEVERE, e.getMessage(), e);
                    }
                }
            });
    } finally {
        resetCaches();
    }
}
 
Example #11
Source File: JmePaletteUtilities.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void insert(final String s,final JTextComponent target) throws BadLocationException {

        final StyledDocument doc = (StyledDocument)target.getDocument();

        class AtomicChange implements Runnable {

            public void run() {
                Document value = target.getDocument();
                if (value == null)
                    return;
                try {
                    insert(s, target, doc);
                } catch (BadLocationException e) {}
            }
        }

        try {
            NbDocument.runAtomicAsUser(doc, new AtomicChange());
        } catch (BadLocationException ex) {}

    }
 
Example #12
Source File: ResourceConfigurationHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the content of the document by the graph.
 */
public static void replaceDocument(final StyledDocument doc, BaseBean graph) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        graph.write(out);
    } catch (IOException ioe) {
        LOGGER.log(Level.WARNING, null, ioe);
    }
    NbDocument.runAtomic(doc, new Runnable() {
        public void run() {
            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, out.toString(), null);
            } catch (BadLocationException ble) {
                LOGGER.log(Level.WARNING, null, ble);
            }
        }
    });
}
 
Example #13
Source File: TestSingleMethodSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean canHandle(Node activatedNode) {
    FileObject fileObject = CommandUtils.getFileObject(activatedNode);
    if (fileObject == null) {
        return false;
    }
    PhpProject project = PhpProjectUtils.getPhpProject(fileObject);
    if (project == null) {
        return false;
    }
    final EditorCookie editorCookie = activatedNode.getLookup().lookup(EditorCookie.class);
    if (editorCookie == null) {
        return false;
    }
    JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
        @Override
        public JEditorPane run() {
            return NbDocument.findRecentEditorPane(editorCookie);
        }

    });
    if (pane == null) {
        return false;
    }
    return getTestMethod(pane.getDocument(), pane.getCaret().getDot()) != null;
}
 
Example #14
Source File: FXMLCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        @Override
        public void run() {
            Document doc = component.getDocument();
            
            try {
                doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset);
                doc.insertString(substituteOffset, getText(), null);
            } catch (BadLocationException e) {
                Logger.getLogger(FXMLCompletionItem.class.getName()).log(Level.FINE, null, e);
            }
        }
    });
}
 
Example #15
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
private Component makeEditorForText (final Document document) {
  if (this.lastEditor != null) {
    this.lastEditor.removeCaretListener(this);
  }

  this.lastEditor = UI_COMPO_FACTORY.makeEditorPane();
  this.lastEditor.setEditorKit(getEditorKit());
  this.lastEditor.setDocument(document);

  this.lastEditor.addCaretListener(this);

  final Component result;
  if (document instanceof NbDocument.CustomEditor) {
    NbDocument.CustomEditor ce = (NbDocument.CustomEditor) document;
    result = ce.createEditor(this.lastEditor);
  }
  else {
    final JScrollPane scroll = UI_COMPO_FACTORY.makeScrollPane();
    scroll.setViewportView(this.lastEditor);
    result = scroll;
  }

  this.caretUpdate(null);

  return result;
}
 
Example #16
Source File: HintsControllerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int[] computeLineSpan(Document doc, int lineNumber) throws BadLocationException {
    lineNumber = Math.min(lineNumber, NbDocument.findLineRootElement((StyledDocument) doc).getElementCount());
    
    int lineStartOffset = NbDocument.findLineOffset((StyledDocument) doc, Math.max(0, lineNumber - 1));
    int lineEndOffset;
    
    if (doc instanceof BaseDocument) {
        lineEndOffset = Utilities.getRowEnd((BaseDocument) doc, lineStartOffset);
    } else {
        //XXX: performance:
        String lineText = doc.getText(lineStartOffset, doc.getLength() - lineStartOffset);
        
        lineText = lineText.indexOf('\n') != (-1) ? lineText.substring(0, lineText.indexOf('\n')) : lineText;
        lineEndOffset = lineStartOffset + lineText.length();
    }
    
    int[] span = new int[] {lineStartOffset, lineEndOffset};
    
    computeLineSpan(doc, span);
    
    return span;
}
 
Example #17
Source File: IDEServicesImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
@NbBundle.Messages({"LBL_OpenDocument=Open Document", 
                    "# {0} - to be opened documents path",  "MSG_CannotOpen=Could not open document with path\n {0}",
                    "# {0} - to be found documents path",  "MSG_CannotFind=Could not find document with path\n {0}"})
public void openDocument(final String path, final int offset) {
    final FileObject fo = findFile(path);
    if ( fo != null ) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    DataObject od = DataObject.find(fo);
                    boolean ret = NbDocument.openDocument(od, offset, -1, Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
                    if(!ret) {
                        notifyError(Bundle.LBL_OpenDocument(), Bundle.MSG_CannotOpen(path));
                    }
                } catch (DataObjectNotFoundException e) {
                    IDEServicesImpl.LOG.log(Level.SEVERE, null, e);
                }
            }
        });
    } else {
        notifyError(Bundle.LBL_OpenDocument(), Bundle.MSG_CannotFind(path));
    }
}
 
Example #18
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line of the caret in the most recent editor.
 * This returns the current line in the current editor if there's one,
 * or a line of the caret in the editor, that was most recently active.
 * @return the line or <code>null</code> when there was no recent active editor.
 */
public Line getMostRecentLine() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return null;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return null;
    StyledDocument d = e.getDocument ();
    if (d == null) return null;
    Caret caret = ep.getCaret ();
    if (caret == null) return null;
    int lineNumber = NbDocument.findLineNumber(d, caret.getDot());
    Line.Set lineSet = e.getLineSet();
    try {
        return lineSet.getCurrent(lineNumber);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
 
Example #19
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Locates AnnotateLine associated with given line. The
 * line is translated to Element that is used as map lookup key.
 * The map is initially filled up with Elements sampled on
 * annotate() method.
 *
 * <p>Key trick is that Element's identity is maintained
 * until line removal (and is restored on undo).
 *
 * @param line
 * @return found AnnotateLine or <code>null</code>
 */
private VcsAnnotation getAnnotateLine(int line) {
    StyledDocument sd = (StyledDocument) doc;
    int lineOffset = NbDocument.findLineOffset(sd, line);
    Element element = sd.getParagraphElement(lineOffset);
    VcsAnnotation al = elementAnnotations.get(element);

    if (al != null) {
        int startOffset = element.getStartOffset();
        int endOffset = element.getEndOffset();
        try {
            int len = endOffset - startOffset;
            String text = doc.getText(startOffset, len -1);
            String content = al.getDocumentText();
            if (text.equals(content)) {
                return al;
            }
        } catch (BadLocationException e) {
            ErrorManager err = ErrorManager.getDefault();
            err.annotate(e, "CVS.AB: can not locate line annotation."); // NOI18N
            err.notify(ErrorManager.INFORMATIONAL, e);
        }
    }

    return null;
}
 
Example #20
Source File: EditorOperator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Returns offset of the beginning of a line.
 * @param lineNumber number of line (starts at 1)
 * @return offset offset of line from the beginning of a file
 */
private int getLineOffset(int lineNumber) {
    try {
        StyledDocument doc = (StyledDocument) txtEditorPane().getDocument();
        return NbDocument.findLineOffset(doc, lineNumber - 1);
    } catch (IndexOutOfBoundsException e) {
        throw new JemmyException("Invalid line number " + lineNumber, e);
    }
}
 
Example #21
Source File: SourceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeadlock164258() throws Exception {
    final StyledDocument doc = (StyledDocument) createDocument("text/plain", "");
    final Source source = Source.create(doc);
    assertNotNull("No Source for " + doc, source);
    final CountDownLatch startLatch1 = new CountDownLatch(1);
    final CountDownLatch startLatch2 = new CountDownLatch(1);

    //Prerender
    ParserManager.parse(Collections.singleton(source), new UserTask() {
        @Override
        public void run(ResultIterator resultIterator) throws Exception {
            
        }
    });

    new Thread() {
        public void run () {
            NbDocument.runAtomic(doc, new Runnable() {
                public void run () {
                    try {
                        startLatch1.await();
                        startLatch2.countDown();
                        SourceAccessor.getINSTANCE().getEnvControl(source).sourceChanged(false);
                    } catch (InterruptedException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            });
        }
    }.start();
    synchronized(TaskProcessor.INTERNAL_LOCK) {
        startLatch1.countDown();
        startLatch2.await();
        NbDocument.runAtomic(doc, new Runnable() {
            public void run() {
            }
        });
    }
}
 
Example #22
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) {
    String t = null;
    if (ep.getCaret() != null) { // #255228
        if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
            t = ep.getSelectedText();
        }
        if (t != null) {
            return t;
        }
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);
    try {
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        if (col + 1 >= lineLen) {
            // do not evaluate when mouse hover behind the end of line (112662)
            return null;
        }
        t = doc.getText(lineStartOffset, lineLen);
        return getExpressionToEvaluate(t, col);
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example #23
Source File: GotoOppositeAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getApplicableFileObject(int[] caretPosHolder) {
    if (!EventQueue.isDispatchThread()) {
        // Unsafe to ask for an editor pane from a random thread.
        // E.g. org.netbeans.lib.uihandler.LogRecords.write asking for getName().
        Collection<? extends FileObject> dobs = Utilities.actionsGlobalContext().lookupAll(FileObject.class);
        return dobs.size() == 1 ? dobs.iterator().next() : null;
    }

    // TODO: Use the new editor library to compute this:
    // JTextComponent pane = EditorRegistry.lastFocusedComponent();

    TopComponent comp = TopComponent.getRegistry().getActivated();
    if(comp == null) {
        return null;
    }
    Node[] nodes = comp.getActivatedNodes();
    if (nodes != null && nodes.length == 1) {
        if (comp instanceof CloneableEditorSupport.Pane) { //OK. We have an editor
            EditorCookie ec = nodes[0].getLookup().lookup(EditorCookie.class);
            if (ec != null) {
                JEditorPane editorPane = NbDocument.findRecentEditorPane(ec);
                if (editorPane != null) {
                    if (editorPane.getCaret() != null) {
                            caretPosHolder[0] = editorPane.getCaret().getDot();
                    }
                    Document document = editorPane.getDocument();
                    return Source.create(document).getFileObject();
                }
            }
        } else {
            return UICommonUtils.getFileObjectFromNode(nodes[0]);
        }
    }
    
    return null;
}
 
Example #24
Source File: CompletionUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Adds fx: namespace declaration to the root of the document. Fails with
 * IllegalStateException, if a fx with a conflicting namespace URI is already
 * used in the root element.
 * 
 * @param doc document to modify
 * @param h token hierarchy - to find the root element
 */
public static Callable<String> makeFxNamespaceCreator(CompletionContext ctx) {
    final String existingPrefix = ctx.findFxmlNsPrefix();
    if (existingPrefix != null) {
        return new Callable<String>() {

            @Override
            public String call() throws Exception {
                return existingPrefix;
            }
            
        };
    }
    
    final String prefix = ctx.findPrefixString(JavaFXEditorUtils.FXML_FX_NAMESPACE_CURRENT, 
            JavaFXEditorUtils.FXML_FX_PREFIX);
    final Document doc = ctx.getDoc();
    Position pos;
    
    try {
        pos = NbDocument.createPosition(doc, ctx.getRootAttrInsertOffset(), Position.Bias.Forward);
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
        pos = null;
    }
    
    final Position finalPos = pos;
    return new Callable<String>() {
        public String call() throws Exception {
            if (finalPos == null) {
                return prefix;
            }
            doc.insertString(finalPos.getOffset(), "xmlns:" + prefix + "=\"" +
                    JavaFXEditorUtils.FXML_FX_NAMESPACE_CURRENT + "\" ", null);
            return prefix;
        }
    };
}
 
Example #25
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Position createPosition(FileObject file, int offset) {
    try {
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        StyledDocument doc = ec.openDocument();
        int line = NbDocument.findLineNumber(doc, offset);
        int column = NbDocument.findLineColumn(doc, offset);

        return new Position(line, column);
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #26
Source File: HighlightImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static HighlightImpl parse(StyledDocument doc, String line) throws ParseException, BadLocationException {
    MessageFormat f = new MessageFormat("[{0}], {1,number,integer}:{2,number,integer}-{3,number,integer}:{4,number,integer}");
    Object[] args = f.parse(line);
    
    String attributesString = (String) args[0];
    int    lineStart  = ((Long) args[1]).intValue();
    int    columnStart  = ((Long) args[2]).intValue();
    int    lineEnd  = ((Long) args[3]).intValue();
    int    columnEnd  = ((Long) args[4]).intValue();
    
    String[] attrElements = attributesString.split(",");
    List<ColoringAttributes> attributes = new ArrayList<ColoringAttributes>();
    
    for (String a : attrElements) {
        a = a.trim();
        
        attributes.add(ColoringAttributes.valueOf(a));
    }
    
    if (attributes.contains(null))
        throw new NullPointerException();
    
    int offsetStart = NbDocument.findLineOffset(doc, lineStart) + columnStart;
    int offsetEnd = NbDocument.findLineOffset(doc, lineEnd) + columnEnd;
    
    return new HighlightImpl(doc, offsetStart, offsetEnd, attributes);
}
 
Example #27
Source File: TestSingleMethodSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean canHandle(Node activatedNode) {
      FileObject fileO = org.netbeans.modules.gsf.testrunner.ui.api.UICommonUtils.getFileObjectFromNode(activatedNode);
      if (fileO != null) {
          final EditorCookie ec = activatedNode.getLookup().lookup(EditorCookie.class);
          if (ec != null) {
JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
    @Override
    public JEditorPane run() {
	return NbDocument.findRecentEditorPane(ec);
    }
});
if (pane != null) {
    String text = pane.getText();
                  if (text != null) {  //NOI18N
                      text = text.replaceAll("\n", "").replaceAll(" ", "");
	if ((text.contains("@RunWith") || text.contains("@org.junit.runner.RunWith")) //NOI18N
	    && text.contains("Parameterized.class)")) {  //NOI18N
	    return false;
	}
                  }
                  SingleMethod sm = getTestMethod(pane.getDocument(), pane.getCaret().getDot());
                  if(sm != null) {
                      return true;
                  }
              }
          }
      }
      return false;
  }
 
Example #28
Source File: ErrorHintProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run(FxmlParserResult result, SchedulerEvent event) {
    Collection<ErrorMark> marks = result.getProblems();
    
    document = result.getSnapshot().getSource().getDocument(false);
    if (document == null) {
        // no op
        return;
    }
    List<ErrorDescription> descs = new ArrayList<ErrorDescription>();
    for (ErrorMark m : marks) {
        try {
            descs.add(ErrorDescriptionFactory.createErrorDescription(
                    m.isError() ? Severity.ERROR : Severity.WARNING,
                    m.getMessage(),
                    document, 
                    NbDocument.createPosition(document, 
                        m.getOffset(), Position.Bias.Forward),
                    NbDocument.createPosition(document, 
                        m.getOffset() + m.getLen(), Position.Bias.Forward))
                );
        } catch (BadLocationException ex) {
            // ignore
        }
    }
    HintsController.setErrors(document, "fxml-parsing", descs);
}
 
Example #29
Source File: GetJavaWord.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static String getCurrentJavaWord() {
    Node[] n = TopComponent.getRegistry ().getActivatedNodes ();

    if (n.length == 1) {
        EditorCookie ec = n[0].getLookup().lookup(EditorCookie.class);
        if (ec != null) {
            JEditorPane pane = NbDocument.findRecentEditorPane(ec);
            return pane == null ? null : forPane(pane);
        }
    }

    return null;
}
 
Example #30
Source File: OpenFilesSearchScopeProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean isFromEditorWindow(DataObject dobj,
        final TopComponent tc) {
    final EditorCookie editor = dobj.getLookup().lookup(
            EditorCookie.class);
    if (editor != null) {
        return Mutex.EVENT.readAccess(new Action<Boolean>() {
            @Override
            public Boolean run() {
                return (tc instanceof CloneableTopComponent) // #246597
                        || NbDocument.findRecentEditorPane(editor) != null;
            }
        });
    }
    return false;
}