private boolean insideToken(final JTextComponent jtc, final JavaTokenId first, final JavaTokenId... rest) { final Document doc = jtc.getDocument(); final boolean[] result = new boolean[1]; doc.render(new Runnable() { @Override public void run() { int offset = jtc.getSelectionStart(); TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(TokenHierarchy.get(doc), offset); if (ts == null || !ts.moveNext() && !ts.movePrevious() || offset == ts.offset()) { result[0] = false; } else { EnumSet tokenIds = EnumSet.of(first, rest); result[0] = tokenIds.contains(ts.token().id()); } } }); return result[0]; }
public @Override FileCoverageDetails getDetails(final FileObject fo, final Document doc) { String path = srcPath().getResourceName(fo); if (path == null) { return null; } MavenDetails det = null; synchronized (this) { MavenSummary summ = summaryCache != null ? summaryCache.get(path) : null; if (summ != null) { det = summ.getDetails(); //we have to set the linecount here, as the entire line span is not apparent from the parsed xml, giving strange results then. det.lineCount = doc.getDefaultRootElement().getElementCount(); } } return det; }
public @Override boolean targetOffsetReached(int offset, char ch, int x, int charWidth, DrawContext ctx) { if (offset <= eolOffset) { if (x + charWidth < targetX) { this.offset = offset; return true; } else { // target position inside the char this.offset = offset; if (targetX > x + charWidth / 2) { Document doc = getDocument(); if (ch != '\n' && doc != null && offset < doc.getLength()) { //NOI18N this.offset++; } } return false; } } else { return false; } }
public void testSyncWithChangedProlog() throws Exception { List<Difference> diffs = Util.diff("resources/test1.xml", "resources/test1_changedProlog.xml"); assertEquals("should also include change in prolog", 1, diffs.size()); defaultSetup(); org.netbeans.modules.xml.xdm.nodes.Document oldDoc = (org.netbeans.modules.xml.xdm.nodes.Document) mModel.getDocument(); Util.setDocumentContentTo(mDoc, "resources/test1_changedProlog.xml"); mModel.sync(); org.netbeans.modules.xml.xdm.nodes.Document doc = (org.netbeans.modules.xml.xdm.nodes.Document) mModel.getDocument(); assertEquals("expect resulting document has no prolog", 6, doc.getTokens().size()); String tokens = doc.getTokens().toString(); assertFalse("prolog should changes: "+tokens, oldDoc.getTokens().toString().equals(tokens)); }
private static CharSequence getIndent(JTextComponent c) { StringBuilder sb = new StringBuilder(); try { Document doc = c.getDocument(); CodeStyle cs = CodeStyle.getDefault(doc); int indent = IndentUtils.lineIndent(c.getDocument(), IndentUtils.lineStartOffset(c.getDocument(), c.getCaretPosition())); int tabSize = cs.getTabSize(); int col = 0; if (!cs.expandTabToSpaces()) { while (col + tabSize <= indent) { sb.append('\t'); //NOI18N col += tabSize; } } while (col < indent) { sb.append(' '); //NOI18N col++; } } catch (BadLocationException ex) { } return sb; }
private synchronized void updateForNewDocument() { data.unregister(); Document newDocument = pane.getDocument(); if (weakDocL != null && this.doc != null) { this.doc.removeDocumentListener(weakDocL); this.doc = null; } if (newDocument instanceof BaseDocument) { this.doc = (BaseDocument) pane.getDocument(); weakDocL = WeakListeners.document(this, this.doc); this.doc.addDocumentListener(weakDocL); } data.register(this.doc); }
public static FindReplaceResult findBlocks(Document doc, int startOffset, int endOffset, Map<String, Object> props, int blocks[]) throws BadLocationException{ BlocksFinder finder; try { finder = (BlocksFinder) getFinder(doc, props, false, true); } catch (PatternSyntaxException pse) { FindReplaceResult findReplaceResult = new FindReplaceResult(new int[]{-1, -1}, ""); findReplaceResult.setErrorMsg(NbBundle.getMessage(DocumentFinder.class, "pattern-error-dialog-content") + " " + pse.getDescription()); return findReplaceResult; } if (finder == null){ return new FindReplaceResult(blocks, ""); } CharSequence cs = DocumentUtilities.getText(doc, startOffset, endOffset - startOffset); if (cs==null){ return null; } synchronized (finder) { finder.reset(); finder.setBlocks(blocks); finder.find(startOffset, cs); int ret [] = finder.getBlocks(); return new FindReplaceResult(ret, ""); } }
public static boolean isGuarded(Tree node, CompilationInfo javac, Document doc) { GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc); if (guards != null) { try { final int startOff = (int) javac.getTrees().getSourcePositions(). getStartPosition(javac.getCompilationUnit(), node); final Position startPos = doc.createPosition(startOff); for (GuardedSection guard : guards.getGuardedSections()) { if (guard.contains(startPos, false)) { return true; } } } catch (BadLocationException ex) { Logger.getLogger(Analyzer.class.getName()).log(Level.INFO, ex.getMessage(), ex); // consider it as guarded return true; } } return false; }
@Override public void implement() throws Exception { Source source = Source.create(sourceFile); final Document doc = source.getDocument(false); ParserManager.parse(Collections.singleton(source), new UserTask() { @Override public void run(ResultIterator resultIterator) throws Exception { //html must be top level Result result = resultIterator.getParserResult(); if(!(result instanceof HtmlParserResult)) { return ; } ModificationResult modification = new ModificationResult(); if(HtmlSourceUtils.importStyleSheet(modification, (HtmlParserResult)result, externalStylesheet)) { modification.commit(); // if(doc != null) { // //refresh the index for the modified file // HtmlSourceUtils.forceReindex(sourceFile); // } } } }); }
/** delayed change of query text */ @Override public void stateChanged (ChangeEvent e) { Document doc = (Document)e.getSource(); try { curTypedText = doc.getText(0, doc.getLength()).trim(); } catch (BadLocationException ex) { // should never happen, nothing we can do probably return; } tfQuery.setForeground(defSearchC); if (curTypedText.length() < 3) { tfQuery.setForeground(Color.RED); //nls.setWarningMessage(NbBundle.getMessage(AddDependencyPanel.class, "MSG_QueryTooShort")); } else { tfQuery.setForeground(defSearchC); //nls.clearMessages(); find(curTypedText); } }
private void checkExpansionKeystroke(KeyEvent evt) { Position pos = null; Document d = null; synchronized (abbrevChars) { if (abbrevEndPosition != null && component != null && doc != null && component.getCaretPosition() == abbrevEndPosition.getOffset() && !isAbbrevDisabled() && doc.getProperty(EDITING_TEMPLATE_DOC_PROPERTY) == null ) { pos = abbrevEndPosition; d = component.getDocument(); } } if (pos != null && d != null) { CodeTemplateManagerOperation operation = CodeTemplateManagerOperation.get(d, pos.getOffset()); if (operation != null) { KeyStroke expandKeyStroke = operation.getExpansionKey(); if (expandKeyStroke.equals(KeyStroke.getKeyStrokeForEvent(evt))) { if (expand(operation)) { evt.consume(); } } } } }
@Override public final void setText(final String text) { synchronized (getDelegateLock()) { // JTextArea.setText() posts two different events (remove & insert). // Since we make no differences between text events, // the document listener has to be disabled while // JTextArea.setText() is called. final Document document = getTextComponent().getDocument(); document.removeDocumentListener(this); getTextComponent().setText(text); revalidate(); if (firstChangeSkipped) { postEvent(new TextEvent(getTarget(), TextEvent.TEXT_VALUE_CHANGED)); } document.addDocumentListener(this); } repaintPeer(); }
private static CodeStyle getCodeStyle(CompilationInfo info) { if (info != null) { try { Document doc = info.getDocument(); if (doc != null) { CodeStyle cs = (CodeStyle)doc.getProperty(CodeStyle.class); return cs != null ? cs : CodeStyle.getDefault(doc); } } catch (IOException ioe) { // ignore } FileObject file = info.getFileObject(); if (file != null) { return CodeStyle.getDefault(file); } } return CodeStyle.getDefault((Document)null); }
XhtmlElHighlighting(Document document) { this.document = document; // load the background color for the embedding token AttributeSet elAttribs = null; String mimeType = (String) document.getProperty("mimeType"); //NOI18N FontColorSettings fcs = MimeLookup.getLookup(mimeType).lookup(FontColorSettings.class); if (fcs != null) { Color elBC = getColoring(fcs, XhtmlElTokenId.EL.primaryCategory()); if (elBC != null) { elAttribs = AttributesUtilities.createImmutable( StyleConstants.Background, elBC, ATTR_EXTENDS_EOL, Boolean.TRUE); } } expressionLanguageBackground = elAttribs; }
private TokenSequence<CssTokenId> getCssTokenSequence(Document doc, int offset) { TokenHierarchy th = TokenHierarchy.get(doc); TokenSequence ts = th.tokenSequence(); if (ts == null) { return null; } ts.move(offset); while (ts.moveNext() || ts.movePrevious()) { if (ts.language() == CssTokenId.language()) { return ts; } ts = ts.embedded(); if (ts == null) { break; } //position the embedded ts so we can search deeper ts.move(offset); } return null; }
/** Creates a new instance of SyntaxHighlighting */ public SyntaxHighlighting(Document document) { this.document = document; String mimeType = (String) document.getProperty("mimeType"); //NOI18N if (mimeType != null && mimeType.startsWith("test")) { //NOI18N this.mimeTypeForOptions = mimeType; } else { this.mimeTypeForOptions = null; } // Start listening on changes in global colorings since they may affect colorings for target language findFCSInfo("", null); hierarchy = TokenHierarchy.get(document); hierarchy.addTokenHierarchyListener(WeakListeners.create(TokenHierarchyListener.class, this, hierarchy)); }
static void refreshHack () { Iterator<Document> it = managers.keySet ().iterator (); while (it.hasNext ()) { AbstractDocument document = (AbstractDocument) it.next (); document.readLock (); try { MutableTextInput mti = (MutableTextInput) document.getProperty (MutableTextInput.class); mti.tokenHierarchyControl ().rebuild (); } finally { document.readUnlock (); } // final StyledDocument document = (StyledDocument) it.next (); // NbDocument.runAtomic (document, new Runnable () { // public void run() { // MutableTextInput mti = (MutableTextInput) document.getProperty (MutableTextInput.class); // mti.tokenHierarchyControl ().rebuild (); // } // }); } }
public static Collection<Mark> createMarks(final Document doc, final List<int[]> bag, final Color color, final String tooltip) { final List<Mark> result = new LinkedList<Mark>(); doc.render(new Runnable() { public void run() { int docLen = doc.getLength(); for (int[] span : bag) { try { int offset = span[0]; if (offset >= 0 && offset <= docLen) { result.add(new MarkImpl(doc, doc.createPosition(offset), color, tooltip)); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } } }); return result; }
/** * This is where, the schema gets instantiated from the template. */ public Set instantiate (TemplateWizard wizard) throws IOException { FileObject dir = Templates.getTargetFolder( wizard ); DataFolder df = DataFolder.findFolder( dir ); FileObject template = Templates.getTemplate( wizard ); DataObject dTemplate = DataObject.find( template ); DataObject dobj = dTemplate.createFromTemplate(df, Templates.getTargetName(wizard)); if (dobj == null) return Collections.emptySet(); encoding = EncodingUtil.getProjectEncoding(df.getPrimaryFile()); if(!EncodingUtil.isValidEncoding(encoding)) encoding = "UTF-8"; //NOI18N EditCookie edit = dobj.getCookie(EditCookie.class); if (edit != null) { EditorCookie editorCookie = dobj.getCookie(EditorCookie.class); Document doc = (Document)editorCookie.openDocument(); fixEncoding(doc, encoding); SaveCookie save = dobj.getCookie(SaveCookie.class); if (save!=null) save.save(); } return Collections.singleton(dobj.getPrimaryFile()); }
public void init(SaasMethod m, RestClientSaasBean saasBean, Document doc) throws IOException { super.init(m, doc); setBean(saasBean); targetSource = JavaSource.forFileObject(getTargetFile()); String packageName = JavaSourceHelper.getPackageName(targetSource); getBean().setPackageName(packageName); serviceFolder = null; saasServiceFile = SourceGroupSupport.findJavaSourceFile(getProject(), getBean().getSaasServiceName()); if (saasServiceFile != null) { saasServiceJS = JavaSource.forFileObject(saasServiceFile); } this.authGen = new SaasClientJavaAuthenticationGenerator(getBean(),getProject()); this.authGen.setLoginArguments(getLoginArguments()); this.authGen.setAuthenticatorMethodParameters(getAuthenticatorMethodParameters()); this.authGen.setSaasServiceFolder(getSaasServiceFolder()); this.authGen.setAuthenticationProfile(getBean().getProfile(m, getDropFileType())); this.authGen.setDropFileType(getDropFileType()); }
static List<AttributeSet> getColors(Language l, ASTPath path, Document doc) { List<AttributeSet> result = new ArrayList<AttributeSet> (); Context context = SyntaxContext.create(doc, path); List<Feature> fs = l.getFeatureList ().getFeatures(COLOR, path); Iterator<Feature> it = fs.iterator(); while (it.hasNext()) { Feature f = it.next(); if (!f.getBoolean("condition", context, true)) continue; result.add(createColoring(f, null)); } ASTNode node = (ASTNode) path.getRoot (); DatabaseContext root = DatabaseManager.getRoot (node); if (root == null) return result; ASTItem item = path.getLeaf (); DatabaseItem i = root.getDatabaseItem (item.getOffset ()); if (i == null || i.getEndOffset () != item.getEndOffset ()) return result; AttributeSet as = getAttributes (i); if (as != null) result.add (as); return result; }
public void run(CompilationInfo info) { cancel.set(false); FileObject file = info.getFileObject(); int[] selection = SelectionAwareJavaSourceTaskFactory.getLastSelection(file); if (selection == null) { //nothing to do.... HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), Collections.<ErrorDescription>emptyList()); } else { HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), computeError(info, selection[0], selection[1], null, new EnumMap<IntroduceKind, String>(IntroduceKind.class), cancel)); Document doc = info.getSnapshot().getSource().getDocument(false); if (doc != null) { PositionRefresherHelperImpl.setVersion(doc, selection[0], selection[1]); } } }
@Override public List<ErrorDescription> getErrorDescriptionsAt(CompilationInfo info, Context context, Document doc) throws Exception { int[] selection = SelectionAwareJavaSourceTaskFactory.getLastSelection(info.getFileObject()); if (selection == null) { return Collections.emptyList(); } return IntroduceHint.computeError(info, selection[0], selection[1], new EnumMap<IntroduceKind, Fix>(IntroduceKind.class), new EnumMap<IntroduceKind, String>(IntroduceKind.class), context.getCancel()); }
private ShellSession(String displayName, Document doc, ClasspathInfo cpInfo, JavaPlatform platform, FileObject workRoot, FileObject consoleFile) { this.consoleDocument = doc; this.projectInfo = cpInfo; this.displayName = displayName; this.platform = platform; this.consoleFile = consoleFile; this.workRoot = workRoot; this.editorSnippetsFileSystem = FileUtil.createMemoryFileSystem(); this.editorWorkRoot = editorSnippetsFileSystem.getRoot(); this.shellControlOutput = new PrintStream( new WriterOutputStream( // delegate to whatever Writer will be set new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { documentWriter.write(cbuf, off, len); } @Override public void flush() throws IOException { documentWriter.flush(); } @Override public void close() throws IOException { documentWriter.close(); } }) ); }
public void testRenameGlobalElementAfterCopy() throws Exception { // add this code to make sure getDocument returns the same document /* This simulates *- create a new schema; *- create a new element; *- switch to Source view; *- copy created element; *- go to Schema and back to Source view; */ SchemaModel model = Util.loadSchemaModel("resources/RenameTestRename_before.xsd"); SchemaImpl schema = (SchemaImpl) model.getSchema(); Document doc = AbstractDocumentModel.class.cast(model).getBaseDocument(); Iterator it = schema.getElements().iterator(); GlobalElementImpl ge1 = (GlobalElementImpl) it.next(); GlobalElementImpl ge2 = (GlobalElementImpl) it.next(); assertEquals("testRenameGlobalElementAfterCopy.secondRename.ge1", "OrgChart", ge1.getName()); assertEquals("testRenameGlobalElementAfterCopy.secondRename.ge2", "OrgChart", ge2.getName()); /* This simulates *- rename both elements; *- switch to Schema view. */ Util.setDocumentContentTo(doc, "resources/RenameTestRename_after.xsd"); model.sync(); Iterator it1 = schema.getElements().iterator(); ge1 = (GlobalElementImpl) it1.next(); ge2 = (GlobalElementImpl) it1.next(); assertEquals("testRenameGlobalElementAfterCopy.secondRename.ge1", "OrgChart1", ge1.getName()); assertEquals("testRenameGlobalElementAfterCopy.secondRename.ge2", "OrgChart2", ge2.getName()); }
public void run() { Document document = getDocument(); DocumentListener listener = document == null ? null : (DocumentListener) document.getProperty(PROPERTY_MODIFICATION_LISTENER); if (listener != null) { document.removeDocumentListener(listener); } try { reloadModel(); } finally { if (listener != null) { document.addDocumentListener(listener); } } }
@Hint(id = "error-in-javadoc", category = "JavaDoc", description = "#DESC_ERROR_IN_JAVADOC_HINT", displayName = "#DN_ERROR_IN_JAVADOC_HINT", hintKind = Hint.Kind.INSPECTION, severity = Severity.WARNING, customizerProvider = JavadocHint.CustomizerProviderImplError.class) @TriggerTreeKind({Kind.METHOD, Kind.ANNOTATION_TYPE, Kind.CLASS, Kind.ENUM, Kind.INTERFACE, Kind.VARIABLE}) public static List<ErrorDescription> errorHint(final HintContext ctx) { Preferences pref = ctx.getPreferences(); boolean correctJavadocForNonPublic = pref.getBoolean(AVAILABILITY_KEY + false, false); CompilationInfo javac = ctx.getInfo(); Boolean publiclyAccessible = AccessibilityQuery.isPubliclyAccessible(javac.getFileObject().getParent()); boolean isPubliclyA11e = publiclyAccessible == null ? true : publiclyAccessible; if (!isPubliclyA11e && !correctJavadocForNonPublic) { return null; } if (javac.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N // broken java platform return Collections.<ErrorDescription>emptyList(); } TreePath path = ctx.getPath(); { Document doc = null; try { doc = javac.getDocument(); } catch (IOException e) { Exceptions.printStackTrace(e); } if (doc != null && isGuarded(path.getLeaf(), javac, doc)) { return null; } } Access access = Access.resolve(pref.get(SCOPE_KEY, SCOPE_DEFAULT)); Analyzer a = new Analyzer(javac, path, access, ctx); return a.analyze(); }
public void testLengthyEdit() throws Exception { loggingOn(); RandomTestContainer container = createContainer(); JEditorPane pane = container.getInstance(JEditorPane.class); Document doc = pane.getDocument(); doc.putProperty("mimeType", "text/plain"); ViewHierarchyRandomTesting.initRandomText(container); final RandomTestContainer.Context context = container.context(); for (int i = 0; i < 100; i++) { DocumentTesting.insert(context, 0, "abcdefghijklmnopqrst\n"); } DocumentTesting.setSameThreadInvoke(context, true); // Otherwise runAtomic() would lock forever waiting for EDT final BaseDocument bdoc = (BaseDocument) doc; SwingUtilities.invokeAndWait(new Runnable() { private boolean inRunAtomic; @Override public void run() { if (!inRunAtomic) { inRunAtomic = true; bdoc.runAtomic(this); return; } try { for (int i = 0; i < 100; i++) { // DocumentTesting.insert(context, i * 22 + 3, "a\n"); DocumentTesting.remove(context, i * 20 + 2, 1); } } catch (Exception e) { throw new IllegalStateException(e); } } }); DocumentTesting.setSameThreadInvoke(context, false); EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, false); // DocumentTesting.insert(context, 50, "x\nab\n"); // EditorPaneTesting.setCaretOffset(context, 20); }
@Override public void defaultAction(JTextComponent component) { //StyledDocument doc = (StyledDocument) component.getDocument(); Document doc = component.getDocument(); try { String text = doc.getText(0, caretOffset); int dot = text.lastIndexOf('.'); if (dot < 0) dot = 0; else dot++; doc.remove(dot, caretOffset - dot); caretOffset = dot; String insertStr; int insertOffset = caretOffset; if (typeElement != null) { insertStr = ElementUtilities.getBinaryName(typeElement); doc.remove(0, doc.getLength()); insertOffset = 0; } else { insertStr = ((prefix != null) ? prefix : "") + elementName; } doc.insertString(insertOffset, insertStr, null); if (elementKind == ElementKind.PACKAGE) { doc.insertString(insertOffset + insertStr.length(), ".", null); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } if (elementKind != ElementKind.PACKAGE) { //This statement will close the code completion box: Completion.get().hideAll(); } }
@Override protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) { List<JPACompletionItem> completionItems = new ArrayList<JPACompletionItem>(); int anchorOffset = getCompletionItems(doc, caretOffset, completionItems); resultSet.addAllItems(completionItems); if (anchorOffset != -1) { resultSet.setAnchorOffset(anchorOffset); } resultSet.finish(); }
@Override protected boolean isUpToDate(Context context, Document doc, DocumentVersionImpl oldVersion) { List<ErrorDescription> errors = oldVersion.errorsContent; for (ErrorDescription ed : errors) { if (ed.getRange().getBegin().getOffset() <= context.getPosition() && context.getPosition() <= ed.getRange().getEnd().getOffset()) { if (!ed.getFixes().isComputed()) return false; } } return true; }
private void sourceComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sourceComboActionPerformed if((sourceMap.get(sourceCombo.getSelectedItem())).getStringMap().isEmpty()) { // There are no hardcoded strings found for this selected source. JLabel label = new JLabel(NbBundle.getBundle(HardStringWizardPanel.class).getString("TXT_NoHardstringsSource")); label.setHorizontalAlignment(JLabel.CENTER); scrollPane.setViewportView(label); } else { scrollPane.setViewportView(hardStringTable); tableModel.fireTableDataChanged(); } SourceData data = sourceMap.get(sourceCombo.getSelectedItem()); Document doc = data.getSupport().getDocument(); preview.setDocument(doc); }
private PositionsBag createRandomBag(Document doc, String bagId) { PositionsBag bag = new PositionsBag(doc, false); Random rand = new Random(System.currentTimeMillis()); int attrIdx = 0; int startOffset = 0; int endOffset = 100; int maxGapSize = Math.max((int) (endOffset - startOffset) / 10, 1); int maxHighlightSize = Math.max((int) (endOffset - startOffset) / 2, 1); for (int pointer = startOffset + rand.nextInt(maxGapSize); pointer <= endOffset; ) { int highlightSize = rand.nextInt(maxHighlightSize); SimpleAttributeSet attributes = new SimpleAttributeSet(); attributes.addAttribute("AttrName-" + bagId + "-" + attrIdx, "AttrValue"); attrIdx++; if (pointer + highlightSize < endOffset) { bag.addHighlight( new SimplePosition(pointer), new SimplePosition(pointer + highlightSize), attributes); } else { bag.addHighlight( new SimplePosition(pointer), new SimplePosition(endOffset), attributes); } // move the pointer pointer += highlightSize + rand.nextInt(maxGapSize); } return bag; }
@Override public void performClickAction(Document doc, int offset, HyperlinkType type) { Line ln = getLine(doc, offset); if (ln != null) { ln.show(ShowOpenType.OPEN, ShowVisibilityType.FOCUS); } else { Toolkit.getDefaultToolkit().beep(); } }
@Override public void run(ResultIterator resultIterator) throws Exception { Parser.Result r = resultIterator.getParserResult(); if (!mimeType.equals(r.getSnapshot().getMimeType())) { return; } Document doc = r.getSnapshot().getSource().getDocument(false); if (doc == null) { return; } Updater theUpdater = new Updater(fileData, doc); runWith(theUpdater, r, doc); }
@Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.insert(offset, string); if (test(sb.toString())) { super.insertString(fb, offset, string, attr); } else { JOptionPane.showMessageDialog(null, "STOP ! You're only allowed to encode numbers !", "Warning", JOptionPane.ERROR_MESSAGE); } }
private void releaseDocAndHoldPosition(Document doc) throws Exception { doc.insertString(0, "Nazdar", null); Position pos = doc.createPosition(3); doc.insertString(2, "abc", null); assertEquals(6, pos.getOffset()); WeakReference<Document> docRef = new WeakReference<Document>(doc); doc = null; assertGC("Doc not released", docRef); assertEquals(6, pos.getOffset()); // Doc released but position can still be referenced }
/** * Reparents comments that follow `from' tree and would be separated from that tree by insertion to `offset' position. * The comments are removed from the original tree, and attached to the `to' inserted tree. * @param wc the working copy * @param from the current owner of the comments * @param to the generated code * @param offset the offset where the new code will be inserted * @param doc document instance or {@code null} * @return */ private void moveCommentsAfterOffset(WorkingCopy wc, Tree from, Tree to, int offset, Document doc) { List<Comment> toMove = new LinkedList<>(); int idx = 0; int firstToRemove = -1; for (Comment comment : wc.getTreeUtilities().getComments(from, false)) { if (comment.endPos() <= offset) { // not affected by insertion idx++; continue; } DocumentGuards guards = LineDocumentUtils.as(doc, DocumentGuards.class); if (guards != null) { int epAfterBlock = guards.adjustPosition(comment.endPos(), true); // comment that ends exactly at the GB boundary cannot be really // reassigned from the previous member. if (epAfterBlock >= comment.endPos()) { // set new offset, after the guarded block idx++; continue; } } toMove.add(comment); if (firstToRemove == -1) { firstToRemove = idx; } idx++; } if (toMove.isEmpty()) { return; } doMoveComments(wc, from, to, offset, toMove, firstToRemove, idx); }
@Override public void initFolds(FoldHierarchyTransaction transaction) { Document doc = operation.getHierarchy().getComponent().getDocument(); Object od = doc.getProperty(Document.StreamDescriptionProperty); if (od instanceof DataObject) { FileObject file = ((DataObject)od).getPrimaryFile(); parserTask = FoldTask.getTask(file); parserTask.updateFoldManager(this, file); } }
/** * Get the root of the paragraph elements for the given document. * * @param doc non-null document instance. * @return root element of the paragraph elements. */ public static Element getParagraphRootElement(Document doc) { if (doc instanceof StyledDocument) { return ((StyledDocument)doc).getParagraphElement(0).getParentElement(); } else { return doc.getDefaultRootElement().getElement(0).getParentElement(); } }