org.netbeans.editor.BaseDocument Java Examples
The following examples show how to use
org.netbeans.editor.BaseDocument.
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: XMLGeneratorTest.java From netbeans with Apache License 2.0 | 7 votes |
protected static BaseDocument getResourceAsDocument(String path) throws Exception { InputStream in = XMLGeneratorTest.class.getResourceAsStream(path); BaseDocument sd = new BaseDocument(true, "text/xml"); //NOI18N BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8")); StringBuffer sbuf = new StringBuffer(); try { String line = null; while ((line = br.readLine()) != null) { sbuf.append(line); sbuf.append(System.getProperty("line.separator")); } } finally { br.close(); } sd.insertString(0,sbuf.toString(),null); return sd; }
Example #2
Source File: TagBasedLexerFormatter.java From netbeans with Apache License 2.0 | 6 votes |
private boolean indexWithinCurrentLanguage(BaseDocument doc, int index) throws BadLocationException{ TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc); TokenSequence[] tokenSequences = (TokenSequence[]) tokenHierarchy.tokenSequenceList(supportedLanguagePath(), 0, Integer.MAX_VALUE).toArray(new TokenSequence[0]); for (TokenSequence tokenSequence: tokenSequences){ TextBounds languageBounds = findTokenSequenceBounds(doc, tokenSequence); if (languageBounds.getAbsoluteStart() <= index && languageBounds.getAbsoluteEnd() >= index){ tokenSequence.move(index); if (tokenSequence.moveNext()){ // the newly entered \n character may or may not // form a separate token - work it around if (isWSToken(tokenSequence.token())){ tokenSequence.movePrevious(); } return tokenSequence.embedded() == null && !isWSToken(tokenSequence.token()); } } } return false; }
Example #3
Source File: GsfHintsManager.java From netbeans with Apache License 2.0 | 6 votes |
public RuleContext createRuleContext (ParserResult parserResult, Language language, int caretOffset, int selectionStart, int selectionEnd) { RuleContext context = provider.createRuleContext(); context.manager = this; context.parserResult = parserResult; context.caretOffset = caretOffset; context.selectionStart = selectionStart; context.selectionEnd = selectionEnd; context.doc = (BaseDocument) parserResult.getSnapshot().getSource().getDocument(false); if (context.doc == null) { // Document closed return null; } // XXX: parsingapi // Collection<? extends ParserResult> embeddedResults = info.getEmbeddedResults(language.getMimeType()); // context.parserResults = embeddedResults != null ? embeddedResults : Collections.EMPTY_LIST; // if (context.parserResults.size() > 0) { // context.parserResult = embeddedResults.iterator().next(); // } return context; }
Example #4
Source File: ToggleCommentAction.java From netbeans with Apache License 2.0 | 6 votes |
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 #5
Source File: CompletionUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Can't provide completion for XML documents based on DTD * and for those who do not declare namespaces in root tag. */ public static boolean canProvideCompletion(BaseDocument doc) { FileObject file = getPrimaryFile(doc); if(file == null) return false; //for .xml documents if("xml".equals(file.getExt())) { //NOI18N //if docroot doesn't declare ns, no completion DocRoot root = CompletionUtil.getDocRoot(doc); if(root != null && !root.declaresNamespace()) { return false; } } return true; }
Example #6
Source File: GroovyFormatter.java From netbeans with Apache License 2.0 | 6 votes |
private int getTokenBalance(BaseDocument doc, int begin, int end, boolean includeKeywords) { int balance = 0; TokenSequence<GroovyTokenId> ts = LexUtilities.getGroovyTokenSequence(doc, begin); if (ts == null) { return 0; } ts.move(begin); if (!ts.moveNext()) { return 0; } do { Token<GroovyTokenId> token = ts.token(); TokenId id = token.id(); balance += getTokenBalanceDelta(id, token, doc, ts, includeKeywords); } while (ts.moveNext() && (ts.offset() < end)); return balance; }
Example #7
Source File: ConfigFileSpringBeanSource.java From netbeans with Apache License 2.0 | 6 votes |
/** * Parses the given document. * Currently the implementation expects it to be a {@link BaseDocument} or null. * * @param document the document to parse. */ public void parse(BaseDocument document) throws IOException { FileObject fo = NbEditorUtilities.getFileObject(document); if (fo == null) { LOGGER.log(Level.WARNING, "Could not get a FileObject for document {0}", document); return; } LOGGER.log(Level.FINE, "Parsing {0}", fo); File file = FileUtil.toFile(fo); if (file == null) { LOGGER.log(Level.WARNING, "{0} resolves to a null File, aborting", fo); return; } new DocumentParser(file, document).run(); LOGGER.log(Level.FINE, "Parsed {0}", fo); }
Example #8
Source File: CssTypedBreakInterceptor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void insert(MutableContext context) throws BadLocationException { int offset = context.getBreakInsertOffset(); BaseDocument doc = (BaseDocument) context.getDocument(); if (offset > 0 && offset < doc.getLength()) { //check corners String text = doc.getText(offset - 1, 2); //get char before and after if (TWO_CURLY_BRACES_IMAGE.equals(text)) { //NOI18N //context.setText("\n\n", 1, 1, 0, 2); //reformat workaround -- the preferred //won't work as the reformatter will not reformat the line with the closing tag int from = Utilities.getRowStart(doc, offset); int to = Utilities.getRowEnd(doc, offset); reformat = new Position[]{doc.createPosition(from), doc.createPosition(to)}; context.setText("\n\n", 1, 1); } } }
Example #9
Source File: XMLCompletionQueryTest.java From netbeans with Apache License 2.0 | 6 votes |
@Test public void testShouldCloseTag() throws IOException, BadLocationException, Exception { BaseDocument doc = getDocument("/org/netbeans/modules/xml/text/completion/res/docResourceUnclosed.html"); XMLSyntaxSupport xss = XMLSyntaxSupport.getSyntaxSupport((BaseDocument)doc); // ##IP1## and ##IP2## mark the positions in the document // which will be checked fif at that point the tag should be closed Finder ip1Finder = new FinderFactory.StringFwdFinder("##IP1##", true); Finder ip2Finder = new FinderFactory.StringFwdFinder("##IP2##", true); int insertPos1 = doc.find(ip1Finder, doc.getStartPosition().getOffset(), doc.getEndPosition().getOffset()); int insertPos2 = doc.find(ip2Finder, doc.getStartPosition().getOffset(), doc.getEndPosition().getOffset()); // The first position is a caret position behind a <a> Element, that // has a closing tag => shouldCloseTag needs to return NULL here to // indicate, that inserted content should be inserted without the // closing tag. SyntaxQueryHelper sqh = new SyntaxQueryHelper(xss, insertPos1); assertNull("XMLCompletionQuery#shouldCloseTag should return NULL if closing tag is present", XMLCompletionQuery.shouldCloseTag(sqh, doc, xss)); // The second position is a caret position behind a <a> Element without // a matching end tag. SyntaxQueryHelper sqh2 = new SyntaxQueryHelper(xss, insertPos2); assertEquals("XMLCompletionQuery#shouldCloseTag should return tagname if no closing tag is present", "a", XMLCompletionQuery.shouldCloseTag(sqh2, doc, xss)); }
Example #10
Source File: JSFConfigHyperlinkProvider.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void performClickAction(javax.swing.text.Document doc, int offset) { if (debug) debug (":: performClickAction"); if (hyperlinkMap.get(ev[0]) != null) { JsfConfigHyperlinkType type = (hyperlinkMap.get(ev[0])); switch (type) { case JAVA_CLASS: findJavaClass(ev[1], doc); break; case RESOURCE_PATH: findResourcePath(ev[1], (BaseDocument) doc); break; } } }
Example #11
Source File: ToggleBlockCommentAction.java From netbeans with Apache License 2.0 | 6 votes |
@Override void comment(BaseDocument baseDocument, Positions positions, AtomicBoolean processedHere) throws BadLocationException { TokenSequence<? extends TwigTopTokenId> ts = TwigLexerUtils.getTwigTokenSequence(baseDocument, positions.getStart()); Token<? extends TwigTopTokenId> token = null; if (ts != null) { ts.move(positions.getStart()); ts.moveNext(); token = ts.token(); if (token != null && positions.getStart() == ts.offset() && !isInComment(token.id())) { ts.movePrevious(); token = ts.token(); } } if (token != null && isInComment(token.id())) { uncommentToken(ts, baseDocument); } else { positions.comment(baseDocument); } processedHere.set(true); }
Example #12
Source File: AbstractTestCase.java From netbeans with Apache License 2.0 | 6 votes |
protected static BaseDocument getResourceAsDocument(String path) throws Exception { // AbstractTestCase was repackaged, tests typically contain path rooted at xml.text package. if (path.startsWith("syntax/")) { path = path.substring(7); } InputStream in = AbstractTestCase.class.getResourceAsStream(path); BaseDocument sd = new BaseDocument(true, "text/xml"); //NOI18N BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8")); StringBuffer sbuf = new StringBuffer(); try { String line = null; while ((line = br.readLine()) != null) { sbuf.append(line); sbuf.append(System.getProperty("line.separator")); } } finally { br.close(); } sd.insertString(0,sbuf.toString(),null); return sd; }
Example #13
Source File: GroovyFormatter.java From netbeans with Apache License 2.0 | 6 votes |
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 #14
Source File: ClassMemberPanelUI.java From netbeans with Apache License 2.0 | 6 votes |
private void doSelectNodes0(ParserResult info, BaseDocument bd, int offset) { ElementNode node; final ElementNode rootNode = getRootNode(); if (info != null && rootNode != null) { node = rootNode.getMimeRootNodeForOffset(info, offset); } else if (bd != null && rootNode != null) { node = rootNode.getMimeRootNodeForOffset(bd, offset); } else { return; } Node[] selectedNodes = manager.getSelectedNodes(); if (!(selectedNodes != null && selectedNodes.length == 1 && selectedNodes[0] == node)) { try { manager.setSelectedNodes(new Node[]{ node == null ? getRootNode() : node }); } catch (PropertyVetoException propertyVetoException) { Exceptions.printStackTrace(propertyVetoException); } } }
Example #15
Source File: KOJsEmbeddingProviderPluginTest.java From netbeans with Apache License 2.0 | 6 votes |
private void checkVirtualSource(String file) throws Exception { FileObject fo = getTestFile(file); BaseDocument doc = getDocument(fo); Source source = Source.create(doc); final AtomicReference<String> jsCodeRef = new AtomicReference<>(); ParserManager.parse(Collections.singleton(source), new UserTask() { @Override public void run(ResultIterator resultIterator) throws Exception { ResultIterator jsRi = WebUtils.getResultIterator(resultIterator, "text/javascript"); if (jsRi != null) { jsCodeRef.set(jsRi.getSnapshot().getText().toString()); } else { //no js embedded code } } }); String jsCode = jsCodeRef.get(); assertDescriptionMatches(fo, jsCode, false, ".virtual", true); }
Example #16
Source File: AbstractCompletionItem.java From netbeans with Apache License 2.0 | 6 votes |
protected void doSubstituteText(JTextComponent c, BaseDocument d, String text) throws BadLocationException { int offset = getSubstOffset(); String old = d.getText(offset, length); int nextOffset = ctx.getNextCaretPos(); Position p = null; if (nextOffset >= 0) { p = d.createPosition(nextOffset); } if (text.equals(old)) { if (p != null) { c.setCaretPosition(p.getOffset()); } else { c.setCaretPosition(offset + getCaretShift(d)); } } else { d.remove(offset, length); d.insertString(offset, text, null); if (p != null) { c.setCaretPosition(p.getOffset()); } else { c.setCaretPosition(offset + getCaretShift(d)); } } }
Example #17
Source File: DumpTokens.java From netbeans with Apache License 2.0 | 6 votes |
public static String printTokens(File file) throws IOException { Logger.getLogger(DumpTokens.class.getName()).info("Dumping tokens"); DataObject dataObj = DataObject.find(FileUtil.toFileObject(file)); EditorCookie ed = dataObj.getCookie(EditorCookie.class); StyledDocument sDoc = ed.openDocument(); BaseDocument doc = (BaseDocument) sDoc; TokenHierarchy th = null; TokenSequence ts = null; int roundCount = 0; while ((th == null) || (ts == null)) { th = TokenHierarchy.get(doc); if (th != null) { ts = th.tokenSequence(); } roundCount++; if (roundCount > 50) { throw new AssertionError("Impossible to get token hierarchy " + roundCount + "times"); } new EventTool().waitNoEvent(1000); } return ts.toString().replaceAll("(st=.*)*IHC=[0-9]*", "");// remove System.identityHashCode }
Example #18
Source File: JavaTypeCompletionItem.java From nb-springboot with Apache License 2.0 | 6 votes |
@Override public void processKeyEvent(KeyEvent evt) { if (evt.getID() == KeyEvent.KEY_TYPED && evt.getKeyChar() == '.' && elementKind == ElementKind.PACKAGE) { logger.log(Level.FINER, "Accepting package ''{0}'' and continuing completion", name); Completion.get().hideDocumentation(); Completion.get().hideCompletion(); JTextComponent tc = (JTextComponent) evt.getSource(); BaseDocument doc = (BaseDocument) tc.getDocument(); doc.runAtomic(new Runnable() { @Override public void run() { try { doc.remove(dotOffset, caretOffset - dotOffset); doc.insertString(dotOffset, name.concat("."), null); } catch (BadLocationException ble) { //ignore } } }); Completion.get().showCompletion(); evt.consume(); } // detect if Ctrl + Enter is pressed overwrite = evt.getKeyCode() == KeyEvent.VK_ENTER && (evt.getModifiers() & KeyEvent.CTRL_MASK) != 0; }
Example #19
Source File: CslEditorKit.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected void afterBreak(JTextComponent target, BaseDocument doc, Caret caret, Object cookie) { if (completionSettingEnabled()) { if (cookie != null) { if (cookie instanceof Integer) { // integer int dotPos = ((Integer)cookie).intValue(); if (dotPos != -1) { caret.setDot(dotPos); } else { int nowDotPos = caret.getDot(); caret.setDot(nowDotPos + 1); } } } } }
Example #20
Source File: XMLSyntaxSupport.java From netbeans with Apache License 2.0 | 5 votes |
/** * Creates a new instance for the given document. The instance will not be * registered anywhere; the caller is responsible for bookkeeping. The method * can return null if the document implementation is not appropriate (does * not offer appropriate API/services). NB editor documents are guaranteed * to work with this support. * * @param d document * @return XML support instance, or {@code null} for incompatible documents. */ @CheckForNull public static XMLSyntaxSupport createSyntaxSupport(Document d) { if (d == null) { throw new NullPointerException("Document may not be null"); } if (!(d instanceof BaseDocument)) { return null; } BaseDocument doc = (BaseDocument)d; return new XMLSyntaxSupport(doc); }
Example #21
Source File: ToggleBlockCommentAction.java From netbeans with Apache License 2.0 | 5 votes |
private void performCustomAction(BaseDocument baseDocument, Positions positions, AtomicBoolean processedHere) { ToggleCommentType toggleCommentType = TwigOptions.getInstance().getToggleCommentType(); try { toggleCommentType.comment(baseDocument, positions, processedHere); } catch (BadLocationException ex) { LOGGER.log(Level.WARNING, null, ex); } }
Example #22
Source File: JSFPaletteUtilities.java From netbeans with Apache License 2.0 | 5 votes |
public static void insert(String s, final JTextComponent target) throws BadLocationException { Document doc = target.getDocument(); if (doc != null && doc instanceof BaseDocument) { final String str = (s == null) ? "" : s; final BaseDocument baseDoc = (BaseDocument) doc; final Reformat formatter = Reformat.get(baseDoc); Runnable edit = new Runnable() { public void run() { try { int start = insert(str, target, baseDoc); // format the inserted text if (start >= 0) { int end = start + str.length(); formatter.reformat(start, end); } } catch (BadLocationException e) { Exceptions.printStackTrace(e); } } }; formatter.lock(); try { baseDoc.runAtomic(edit); }finally { formatter.unlock(); } } }
Example #23
Source File: SingleJspServletGenTest.java From netbeans with Apache License 2.0 | 5 votes |
private SimplifiedJspServlet getProcessor( String fileName ){ FileObject fo = getTestFile(TEST_FOLDER_SINGLE_JPS +"/" +fileName ); assertNotNull(fo); BaseDocument doc = getDocument(fo); SimplifiedJspServlet processor = new SimplifiedJspServlet( createSnaphot(doc) , doc ); return processor; }
Example #24
Source File: StrutsPopupAction.java From netbeans with Apache License 2.0 | 5 votes |
public void actionPerformed(ActionEvent evt, JTextComponent target) { Document doc = target.getDocument(); DataObject data = NbEditorUtilities.getDataObject(doc); AddActionPanel dialogPanel = new AddActionPanel((StrutsConfigDataObject)data); AddDialog dialog = new AddDialog(dialogPanel, NbBundle.getMessage(StrutsPopupAction.class,"TTL_AddAction"), //NOI18N new HelpCtx(AddActionPanel.class)); dialog.disableAdd(); // disable Add button java.awt.Dialog d = org.openide.DialogDisplayer.getDefault().createDialog(dialog); d.setVisible(true); if (dialog.getValue().equals(dialog.ADD_OPTION)) { //TODO:implement action try { StrutsConfig config = ((StrutsConfigDataObject)data).getStrutsConfig(); if (config==null) return; //TODO:inform that XML file is corrupted ActionMappings mappings = config.getActionMappings(); if (mappings==null) { mappings = new ActionMappings(); config.setActionMappings(mappings); } Action action = new Action(); action.setAttributeValue("type",dialogPanel.getActionClass()); //NOI18N action.setAttributeValue("path",dialogPanel.getActionPath()); //NOI18N if (dialogPanel.isActionFormUsed()){ action.setAttributeValue("name",dialogPanel.getFormName()); //NOI18N action.setAttributeValue("input",dialogPanel.getInput()); //NOI18N action.setAttributeValue("validate",dialogPanel.getValidate()); //NOI18N action.setAttributeValue("scope",dialogPanel.getScope()); //NOI18N action.setAttributeValue("attribute",dialogPanel.getAttribute()); //NOI18N } action.setAttributeValue("parameter",dialogPanel.getParameter()); //NOI18N mappings.addAction(action); target.setCaretPosition(StrutsEditorUtilities.writeBean((BaseDocument)doc, action, "action", "action-mappings")); //NOI18N } catch (java.io.IOException ex) {} } }
Example #25
Source File: FindTypeUtils.java From netbeans with Apache License 2.0 | 5 votes |
private static OffsetRange getAnnotationRange(AnnotationNode annotation, BaseDocument doc, int cursorOffset) { if (annotation.getLineNumber() != -1) { final int offset = ASTUtils.getOffset(doc, annotation.getLineNumber(), annotation.getColumnNumber()); final OffsetRange range = ASTUtils.getNextIdentifierByName(doc, annotation.getClassNode().getNameWithoutPackage(), offset); if (range.containsInclusive(cursorOffset)) { return range; } } return OffsetRange.NONE; }
Example #26
Source File: LineTranslations.java From netbeans with Apache License 2.0 | 5 votes |
public void attach() throws IOException { DataObject dobj; synchronized (this) { dobj = this.dataObject; } LineCookie lc = dobj.getLookup().lookup (LineCookie.class); if (lc == null) { return ; } lb.addPropertyChangeListener(this); try { final Line lineNew = lc.getLineSet().getCurrent(lb.getLineNumber() - 1); synchronized (this) { if (line != null) { line.removePropertyChangeListener(this); } this.line = lineNew; } lineNew.addPropertyChangeListener(this); StyledDocument document = NbDocument.getDocument(new Lookup.Provider() { @Override public Lookup getLookup() { return lineNew.getLookup(); } }); if (document instanceof BaseDocument) { BaseDocument bd = (BaseDocument) document; bd.addPostModificationDocumentListener(this); } } catch (IndexOutOfBoundsException ioobex) { // ignore document changes for BP with bad line number } }
Example #27
Source File: XMLSyntaxParserTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testParsePerformace() throws Exception { long start = System.currentTimeMillis(); BaseDocument basedoc = getDocument("nodes/fields.xsd"); XMLSyntaxParser parser = new XMLSyntaxParser(); Document doc = parser.parse(basedoc); long end = System.currentTimeMillis(); System.out.println("Time taken to parse healthcare schema: " + (end-start) + "ms."); assertNotNull("Document can not be null", doc); //FlushVisitor fv = new FlushVisitor(); //String docBuf = fv.flushModel(doc); //assertEquals("The document should be unaltered",basedoc.getText(0,basedoc.getLength()),docBuf); }
Example #28
Source File: ASTElement.java From netbeans with Apache License 2.0 | 5 votes |
@Override public OffsetRange getOffsetRange(ParserResult result) { BaseDocument doc = (BaseDocument) result.getSnapshot().getSource().getDocument(false); int lineNumber = node.getLineNumber(); int columnNumber = node.getColumnNumber(); int start = ASTUtils.getOffset(doc, lineNumber, columnNumber); return new OffsetRange(start, start); }
Example #29
Source File: CodeTemplateInsertHandler.java From netbeans with Apache License 2.0 | 5 votes |
public void insertTemplate() { TextRegionManager trm = TextRegionManager.reserve(component); if (trm == null) // Already occupied for another component over the same document return; Document doc = component.getDocument(); doc.putProperty(CT_HANDLER_DOC_PROPERTY, this); // Build insert string outside of the atomic lock completeInsertString = getInsertText(); if (formatter != null) formatter.lock(); if (indenter != null) indenter.lock(); try { if (doc instanceof BaseDocument) { ((BaseDocument) doc).runAtomicAsUser(this); } else { // Otherwise run without atomic locking this.run(); } } finally { if (formatter != null) { formatter.unlock(); formatter = null; } if (indenter != null) { indenter.unlock(); indenter = null; } completeInsertString = null; } }
Example #30
Source File: ToggleBlockCommentAction.java From netbeans with Apache License 2.0 | 5 votes |
private int findCommentStart(BaseDocument doc, CommentHandler handler, int offsetFrom, int offsetTo) throws BadLocationException { int from = Utilities.getFirstNonWhiteFwd(doc, offsetFrom, offsetTo); if (from == -1) { return offsetFrom; } String startDelim = handler.getCommentStartDelimiter(); if (CharSequenceUtilities.equals( DocumentUtilities.getText(doc).subSequence( from, Math.min(offsetTo, from + startDelim.length())), startDelim)) { return from; } return offsetFrom; }