Java Code Examples for org.netbeans.editor.BaseDocument#getText()
The following examples show how to use
org.netbeans.editor.BaseDocument#getText() .
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: PHPCodeCompletion.java From netbeans with Apache License 2.0 | 6 votes |
private void autoCompleteKeywordsInPHPDoc(final PHPCompletionResult completionResult, PHPCompletionItem.CompletionRequest request) { if (CancelSupport.getDefault().isCancelled()) { return; } BaseDocument doc = (BaseDocument) request.info.getSnapshot().getSource().getDocument(false); if (doc == null) { return; } try { int start = request.anchor - 1; if (start >= 0) { String prefix = doc.getText(start, 1); if (CodeUtils.NULLABLE_TYPE_PREFIX.equals(prefix)) { autoCompleteKeywords(completionResult, request, Type.getTypesForEditor()); } else { autoCompleteKeywords(completionResult, request, Type.getTypesForPhpDoc()); } } } catch (BadLocationException ex) { LOGGER.log(Level.WARNING, "Incorrect offset for the nullable type prefix: {0}", ex.offsetRequested()); // NOI18N } }
Example 2
Source File: IniActionsTestBase.java From netbeans with Apache License 2.0 | 6 votes |
protected void testInFile(String file, String actionName) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); String source = readFile(fo); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1); JEditorPane ta = getPane(sourceWithoutMarker); Caret caret = ta.getCaret(); caret.setDot(sourcePos); BaseDocument doc = (BaseDocument) ta.getDocument(); runKitAction(ta, actionName, null); doc.getText(0, doc.getLength()); doc.insertString(caret.getDot(), "^", null); String target = doc.getText(0, doc.getLength()); assertDescriptionMatches(file, target, false, goldenFileExtension()); }
Example 3
Source File: PositionBoundsResolver.java From netbeans with Apache License 2.0 | 6 votes |
/** *@return PositionBounds representing the position of the name of the entity that is being * refactored or PostionBounds representing the start of the file if the position * of the entity could not be resolved. */ public PositionBounds getPositionBounds(){ if (elementName != null){ try { BaseDocument doc = getDocument(); String text = doc.getText(0, doc.getLength()); int offset = text.indexOf(elementName); if (offset > -1){ PositionRef start = editorSupport.createPositionRef(offset, Bias.Forward); PositionRef end = editorSupport.createPositionRef(offset + elementName.length(), Bias.Backward); return new PositionBounds(start, end); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } return getDefaultPositionBounds(); }
Example 4
Source File: VarDocSuggestion.java From netbeans with Apache License 2.0 | 6 votes |
@Override public void implement() throws Exception { final BaseDocument doc = context.doc; final int caretOffset = getOffset(doc); final String commentText = getCommentText(); final int indexOf = commentText.indexOf(getTypeTemplate()); final EditList editList = getEditList(doc, caretOffset); final Position typeOffset = editList.createPosition(caretOffset + indexOf); editList.apply(); if (typeOffset != null && typeOffset.getOffset() != -1) { JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject()); if (target != null) { final int startOffset = typeOffset.getOffset(); final int endOffset = startOffset + getTypeTemplate().length(); if (indexOf != -1 && (endOffset <= doc.getLength())) { String s = doc.getText(startOffset, getTypeTemplate().length()); if (getTypeTemplate().equals(s)) { target.select(startOffset, endOffset); scheduleShowingCompletion(); } } } } }
Example 5
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 6
Source File: StrutsEditorUtilities.java From netbeans with Apache License 2.0 | 6 votes |
private static int findEndOfElement(BaseDocument doc, String element) throws BadLocationException{ String docText = doc.getText(0, doc.getLength()); int offset = doc.getText(0, doc.getLength()).indexOf("</" + element); //NOI18N ExtSyntaxSupport sup = (ExtSyntaxSupport)doc.getSyntaxSupport(); TokenItem token; while (offset > 0){ token = sup.getTokenChain(offset, offset+1); if (token != null && token.getTokenID().getNumericID() == XML_ELEMENT){ offset = token.getOffset(); token = token.getNext(); while (token != null && !(token.getTokenID().getNumericID() == XML_ELEMENT && token.getImage().equals(">"))) //NOI18N token = token.getNext(); if (token != null) offset = token.getOffset(); return offset; } offset = doc.getText(0, doc.getLength()).indexOf("</" + element); //NOI18N } return -1; }
Example 7
Source File: ArrowFunctionSuggestion.java From netbeans with Apache License 2.0 | 5 votes |
public String getReturnType(BaseDocument document) throws BadLocationException { Expression returnType = lambdaFunction.getReturnType(); if (returnType != null) { return ": " + document.getText(returnType.getStartOffset(), returnType.getEndOffset() - returnType.getStartOffset()); // NOI18N } return ""; // NOI18N }
Example 8
Source File: JadeIndenterTest.java From netbeans with Apache License 2.0 | 5 votes |
private void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); String source = readFile(fo); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1); Formatter formatter = getFormatter(indentPrefs); JEditorPane ta = getPane(sourceWithoutMarker); Caret caret = ta.getCaret(); caret.setDot(sourcePos); BaseDocument doc = (BaseDocument) ta.getDocument(); if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, indentPrefs); runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n"); doc.getText(0, doc.getLength()); doc.insertString(caret.getDot(), "^", null); String target = doc.getText(0, doc.getLength()); assertDescriptionMatches(file, target, false, ".indented"); }
Example 9
Source File: JsCommentGeneratorEmbeddedTest.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception { int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); source = source.substring(0, sourcePos) + source.substring(sourcePos + 1); Formatter formatter = getFormatter(null); int reformattedPos = reformatted.indexOf('^'); assertNotNull(reformattedPos); reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1); JEditorPane ta = getPane(source); Caret caret = ta.getCaret(); caret.setDot(sourcePos); BaseDocument doc = (BaseDocument) ta.getDocument(); if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, preferences); runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n"); // wait for generating comment Future<?> future = JsDocumentationCompleter.RP.submit(new Runnable() { @Override public void run() { } }); future.get(); String formatted = doc.getText(0, doc.getLength()); assertEquals(reformatted, formatted); if (reformattedPos != -1) { assertEquals(reformattedPos, caret.getDot()); } }
Example 10
Source File: XMLGeneratorTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testSameNameAsRootElement() throws Exception { StringBuffer sb = new StringBuffer(); URL url = XMLGeneratorTest.class.getResource("../resources/SameNamesSchema.xsd"); File file = new File(url.toURI()); SchemaModel model = TestCatalogModel.getDefault().getSchemaModel(url.toURI()); XMLContentAttributes attr = new XMLContentAttributes("ns0"); XMLGeneratorVisitor visitor = new XMLGeneratorVisitor(file.getPath(), attr, sb ); visitor.generateXML("newElement", model); BaseDocument doc = getDocument("../resources/SameNamesSchema.xml"); String str = doc.getText(0, doc.getLength()); assertEquals(sb.toString().trim(), str.trim()); }
Example 11
Source File: CslTestBase.java From netbeans with Apache License 2.0 | 4 votes |
protected void insertChar(String original, char insertText, String expected, String selection, boolean codeTemplateMode) throws Exception { String source = original; String reformatted = expected; Formatter formatter = getFormatter(null); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); source = source.substring(0, sourcePos) + source.substring(sourcePos+1); int reformattedPos = reformatted.indexOf('^'); assertNotNull(reformattedPos); reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos+1); JEditorPane ta = getPane(source); Caret caret = ta.getCaret(); caret.setDot(sourcePos); if (selection != null) { int start = original.indexOf(selection); assertTrue(start != -1); assertTrue("Ambiguous selection - multiple occurrences of selection string", original.indexOf(selection, start+1) == -1); ta.setSelectionStart(start); ta.setSelectionEnd(start+selection.length()); assertEquals(selection, ta.getSelectedText()); } BaseDocument doc = (BaseDocument) ta.getDocument(); if (codeTemplateMode) { // Copied from editor/codetemplates/src/org/netbeans/lib/editor/codetemplates/CodeTemplateInsertHandler.java String EDITING_TEMPLATE_DOC_PROPERTY = "processing-code-template"; // NOI18N doc.putProperty(EDITING_TEMPLATE_DOC_PROPERTY, Boolean.TRUE); } if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, null); runKitAction(ta, DefaultEditorKit.defaultKeyTypedAction, ""+insertText); String formatted = doc.getText(0, doc.getLength()); assertEquals(reformatted, formatted); if (reformattedPos != -1) { assertEquals(reformattedPos, caret.getDot()); } }
Example 12
Source File: PhpTypedTextInterceptorTest.java From netbeans with Apache License 2.0 | 4 votes |
protected void insertChar(String original, char insertText, String expected, String selection, boolean codeTemplateMode, Map<String, Object> formatPrefs) throws Exception { String source = wrapAsPhp(original); String reformatted = wrapAsPhp(expected); Formatter formatter = getFormatter(null); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); source = source.substring(0, sourcePos) + source.substring(sourcePos+1); int reformattedPos = reformatted.indexOf('^'); assertNotNull(reformattedPos); reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos+1); JEditorPane ta = getPane(source); Caret caret = ta.getCaret(); caret.setDot(sourcePos); if (selection != null) { int start = original.indexOf(selection); assertTrue(start != -1); assertTrue("Ambiguous selection - multiple occurrences of selection string", original.indexOf(selection, start+1) == -1); ta.setSelectionStart(start); ta.setSelectionEnd(start+selection.length()); assertEquals(selection, ta.getSelectedText()); } BaseDocument doc = (BaseDocument) ta.getDocument(); if (codeTemplateMode) { // Copied from editor/codetemplates/src/org/netbeans/lib/editor/codetemplates/CodeTemplateInsertHandler.java String EDITING_TEMPLATE_DOC_PROPERTY = "processing-code-template"; // NOI18N doc.putProperty(EDITING_TEMPLATE_DOC_PROPERTY, Boolean.TRUE); } if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, null); if (formatter != null && formatPrefs != null) { setOptionsForDocument(doc, formatPrefs); } runKitAction(ta, DefaultEditorKit.defaultKeyTypedAction, ""+insertText); String formatted = doc.getText(0, doc.getLength()); assertEquals(reformatted, formatted); if (reformattedPos != -1) { assertEquals(reformattedPos, caret.getDot()); } }
Example 13
Source File: PHPNewLineIndenterTest.java From netbeans with Apache License 2.0 | 4 votes |
protected void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); String source = readFile(fo); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1); Formatter formatter = getFormatter(indentPrefs); JEditorPane ta = getPane(sourceWithoutMarker); Caret caret = ta.getCaret(); caret.setDot(sourcePos); BaseDocument doc = (BaseDocument) ta.getDocument(); if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, indentPrefs); Map<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults()); options.put(FmtOptions.INITIAL_INDENT, initialIndent); if (indentPrefs != null) { options.put(FmtOptions.INDENT_SIZE, indentPrefs.getIndentation()); } Preferences prefs = CodeStylePreferences.get(doc).getPreferences(); for (String option : options.keySet()) { Object value = options.get(option); if (value instanceof Integer) { prefs.putInt(option, ((Integer) value).intValue()); } else if (value instanceof String) { prefs.put(option, (String) value); } else if (value instanceof Boolean) { prefs.put(option, ((Boolean) value).toString()); } else if (value instanceof CodeStyle.BracePlacement) { prefs.put(option, ((CodeStyle.BracePlacement) value).name()); } else if (value instanceof CodeStyle.WrapStyle) { prefs.put(option, ((CodeStyle.WrapStyle) value).name()); } } runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n"); doc.getText(0, doc.getLength()); doc.insertString(caret.getDot(), "^", null); String target = doc.getText(0, doc.getLength()); assertDescriptionMatches(file, target, false, ".indented"); }
Example 14
Source File: CompletionTest.java From netbeans with Apache License 2.0 | 4 votes |
protected void exec(JEditorPane editor, TestStep step) throws Exception { try { BaseDocument doc = (BaseDocument) editor.getDocument(); ref(step.toString()); Caret caret = editor.getCaret(); caret.setDot(step.getOffset() + 1); EditorOperator eo = new EditorOperator(testFileObj.getNameExt()); eo.insert(step.getPrefix()); if (!isJavaScript()) { caret.setDot(step.getCursorPos()); } waitTypingFinished(doc); CompletionJListOperator comp = null; boolean print = false; int counter = 0; while (!print) { ++counter; if (counter > 5) { print = true; } try { comp = CompletionJListOperator.showCompletion(); } catch (JemmyException e) { log("EE: The CC window did not appear"); e.printStackTrace(getLog()); } if (comp != null) { print = dumpCompletion(comp, step, editor, print) || print; waitTypingFinished(doc); CompletionJListOperator.hideAll(); if (!print) {// wait for refresh Thread.sleep(1000); if (!isJavaScript()) { caret.setDot(step.getCursorPos()); } } } else { long time = System.currentTimeMillis(); String screenFile = time + "-screen.png"; log("CompletionJList is null"); log("step: " + step); log("captureScreen:" + screenFile); try { PNGEncoder.captureScreen(getWorkDir().getAbsolutePath() + File.separator + screenFile); } catch (Exception e1) { e1.printStackTrace(getLog()); } } } waitTypingFinished(doc); int rowStart = Utilities.getRowStart(doc, step.getOffset() + 1); int rowEnd = Utilities.getRowEnd(doc, step.getOffset() + 1); String fullResult = doc.getText(new int[]{rowStart, rowEnd}); String result = fullResult.trim(); int removed_whitespaces = fullResult.length() - result.length(); if (!result.equals(step.getResult().trim())) { ref("EE: unexpected CC result:\n< " + result + "\n> " + step.getResult()); } ref("End cursor position = " + (caret.getDot() - removed_whitespaces)); } finally { // undo all changes final UndoAction ua = SystemAction.get(UndoAction.class); assertNotNull("Cannot obtain UndoAction", ua); while (ua.isEnabled()) { runInAWT(new Runnable() { public void run() { ua.performAction(); } }); } } }
Example 15
Source File: PHPFormatterTestBase.java From netbeans with Apache License 2.0 | 4 votes |
protected void reformatFileContents(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); BaseDocument doc = getDocument(fo); assertNotNull(doc); String fullTxt = doc.getText(0, doc.getLength()); int formatStart = 0; int formatEnd = doc.getLength(); int startMarkPos = fullTxt.indexOf(FORMAT_START_MARK); if (startMarkPos >= 0) { formatStart = startMarkPos + FORMAT_START_MARK.length(); formatEnd = fullTxt.indexOf(FORMAT_END_MARK); if (formatEnd == -1) { throw new IllegalStateException(); } } Formatter formatter = getFormatter(indentPrefs); setupDocumentIndentation(doc, indentPrefs); Map<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults()); options.put(FmtOptions.INITIAL_INDENT, initialIndent); if (indentPrefs != null) { options.put(FmtOptions.INDENT_SIZE, indentPrefs.getIndentation()); } options.put(FmtOptions.CONTINUATION_INDENT_SIZE, 4); Preferences prefs = CodeStylePreferences.get(doc).getPreferences(); for (String option : options.keySet()) { Object value = options.get(option); if (value instanceof Integer) { prefs.putInt(option, ((Integer) value).intValue()); } else if (value instanceof String) { prefs.put(option, (String) value); } else if (value instanceof Boolean) { prefs.put(option, ((Boolean) value).toString()); } else if (value instanceof CodeStyle.BracePlacement) { prefs.put(option, ((CodeStyle.BracePlacement) value).name()); } else if (value instanceof CodeStyle.WrapStyle) { prefs.put(option, ((CodeStyle.WrapStyle) value).name()); } } format(doc, formatter, formatStart, formatEnd, false); String after = doc.getText(0, doc.getLength()); assertDescriptionMatches(file, after, false, ".formatted"); }
Example 16
Source File: PHPFormatterQATest.java From netbeans with Apache License 2.0 | 4 votes |
@Override protected void reformatFileContents(String file, Map<String, Object> options) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); String text = read(fo); int formatStart = 0; int formatEnd = text.length(); int startMarkPos = text.indexOf(FORMAT_START_MARK); if (startMarkPos >= 0){ formatStart = startMarkPos; text = text.substring(0, formatStart) + text.substring(formatStart + FORMAT_START_MARK.length()); formatEnd = text.indexOf(FORMAT_END_MARK); text = text.substring(0, formatEnd) + text.substring(formatEnd + FORMAT_END_MARK.length()); formatEnd --; if (formatEnd == -1){ throw new IllegalStateException(); } } BaseDocument doc = getDocument(text); assertNotNull(doc); IndentPrefs preferences = new IndentPrefs(4, 4); Formatter formatter = getFormatter(preferences); //assertNotNull("getFormatter must be implemented", formatter); setupDocumentIndentation(doc, preferences); Preferences prefs = CodeStylePreferences.get(doc).getPreferences(); for (String option : options.keySet()) { Object value = options.get(option); if (value instanceof Integer) { prefs.putInt(option, ((Integer)value).intValue()); } else if (value instanceof String) { prefs.put(option, (String)value); } else if (value instanceof Boolean) { prefs.put(option, ((Boolean)value).toString()); } else if (value instanceof CodeStyle.BracePlacement) { prefs.put(option, ((CodeStyle.BracePlacement)value).name()); } else if (value instanceof CodeStyle.WrapStyle) { prefs.put(option, ((CodeStyle.WrapStyle)value).name()); } } format(doc, formatter, formatStart, formatEnd, false); String after = doc.getText(0, doc.getLength()); assertDescriptionMatches(file, after, false, ".formatted"); }
Example 17
Source File: YamlKeystrokeHandler.java From netbeans with Apache License 2.0 | 4 votes |
@Override public int beforeBreak(Document document, int offset, JTextComponent target) throws BadLocationException { Caret caret = target.getCaret(); BaseDocument doc = (BaseDocument) document; // Very simple algorithm for now.. // Basically, use the same indent as the current line, unless the caret is immediately preceeded by a ":" (possibly with whitespace // in between) int lineBegin = Utilities.getRowStart(doc, offset); int lineEnd = Utilities.getRowEnd(doc, offset); if (lineBegin == offset && lineEnd == offset) { // Pressed return on a blank newline - do nothing return -1; } int indent = getLineIndent(doc, offset); String linePrefix = doc.getText(lineBegin, offset - lineBegin); String lineSuffix = doc.getText(offset, lineEnd + 1 - offset); if (linePrefix.trim().endsWith(":") && lineSuffix.trim().length() == 0) { // Yes, new key: increase indent indent += IndentUtils.getIndentSize(doc); } else { // No, just use same indent as parent } // Also remove the whitespace from the caret up to the first nonspace character on the current line int remove = 0; String line = doc.getText(lineBegin, lineEnd + 1 - lineBegin); for (int n = line.length(), i = offset - lineBegin; i < n; i++) { char c = line.charAt(i); if (c == ' ' || c == '\t') { remove++; } else { break; } } if (remove > 0) { doc.remove(offset, remove); } String str = IndentUtils.getIndentString(indent); int newPos = offset + str.length(); doc.insertString(offset, str, null); caret.setDot(offset); return newPos + 1; }
Example 18
Source File: PHPNewLineIndenterQATest.java From netbeans with Apache License 2.0 | 4 votes |
protected void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); String source = readFile(fo); int sourcePos = source.indexOf('^'); assertNotNull(sourcePos); String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1); Formatter formatter = getFormatter(indentPrefs); JEditorPane ta = getPane(sourceWithoutMarker); Caret caret = ta.getCaret(); caret.setDot(sourcePos); BaseDocument doc = (BaseDocument) ta.getDocument(); if (formatter != null) { configureIndenters(doc, formatter, true); } setupDocumentIndentation(doc, indentPrefs); Map<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults()); options.put(FmtOptions.INITIAL_INDENT, initialIndent); if (indentPrefs != null) { options.put(FmtOptions.INDENT_SIZE, indentPrefs.getIndentation()); } Preferences prefs = CodeStylePreferences.get(doc).getPreferences(); for (String option : options.keySet()) { Object value = options.get(option); if (value instanceof Integer) { prefs.putInt(option, ((Integer) value).intValue()); } else if (value instanceof String) { prefs.put(option, (String) value); } else if (value instanceof Boolean) { prefs.put(option, ((Boolean) value).toString()); } else if (value instanceof CodeStyle.BracePlacement) { prefs.put(option, ((CodeStyle.BracePlacement) value).name()); } else if (value instanceof CodeStyle.WrapStyle) { prefs.put(option, ((CodeStyle.WrapStyle) value).name()); } } runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n"); doc.getText(0, doc.getLength()); doc.insertString(caret.getDot(), "^", null); String target = doc.getText(0, doc.getLength()); if (indentPrefs != null) { assertDescriptionMatches(file, target, false, "." + indentPrefs.getIndentation() + "_" + indentPrefs.getHangingIndentation() + "_" + initialIndent + ".indented"); } else { assertDescriptionMatches(file, target, false, ".indented"); } }
Example 19
Source File: WhereUsedElement.java From netbeans with Apache License 2.0 | 4 votes |
public static WhereUsedElement create(FileObject fileObject, String name, OffsetRange range, ElementKind kind) { Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList()); int start = range.getStart(); int end = range.getEnd(); int sta = start; int en = start; // ! Same line as start String content = null; BaseDocument bdoc = GsfUtilities.getDocument(fileObject, true); StringBuilder displayText = new StringBuilder(); try { bdoc.readLock(); // I should be able to just call tree.getInfo().getText() to get cached // copy - but since I'm playing fast and loose with compilationinfos // for for example find subclasses (using a singly dummy FileInfo) I need // to read it here instead content = bdoc.getText(0, bdoc.getLength()); sta = Utilities.getRowFirstNonWhite(bdoc, start); if (sta == -1) { sta = Utilities.getRowStart(bdoc, start); } en = Utilities.getRowLastNonWhite(bdoc, start); if (en == -1) { en = Utilities.getRowEnd(bdoc, start); } else { // Last nonwhite - left side of the last char, not inclusive en++; } // Sometimes the node we get from the AST is for the whole block // (e.g. such as the whole class), not the argument node. This happens // for example in Find Subclasses out of the index. In this case if (end > en) { end = start + name.length(); if (end > bdoc.getLength()) { end = bdoc.getLength(); } } } catch (Exception ex) { content = "n/a"; //NOI18N Exceptions.printStackTrace(ex); } finally { bdoc.readUnlock(); } if (end < sta) { // XXX Shouldn't happen, but I still have AST offset errors sta = end; } if (start < sta) { // XXX Shouldn't happen, but I still have AST offset errors start = sta; } if (en < end) { // XXX Shouldn't happen, but I still have AST offset errors en = end; } displayText.append(encodeCharRefs(content.subSequence(sta, start).toString())); displayText.append("<b>"); // NOI18N displayText.append(content.subSequence(start, end)); displayText.append("</b>"); // NOI18N displayText.append(encodeCharRefs(content.subSequence(end, en).toString())); CloneableEditorSupport ces = GsfUtilities.findCloneableEditorSupport(fileObject); PositionRef ref1 = ces.createPositionRef(start, Bias.Forward); PositionRef ref2 = ces.createPositionRef(end, Bias.Forward); PositionBounds bounds = new PositionBounds(ref1, ref2); return new WhereUsedElement(bounds, displayText.toString().trim(), fileObject, name, new OffsetRange(start, end), icon); }
Example 20
Source File: JPACompletionItem.java From netbeans with Apache License 2.0 | 4 votes |
public boolean substituteText(JTextComponent c, int offset, int len, boolean shifted) { BaseDocument doc = (BaseDocument) c.getDocument(); String text = getSubstitutionText(); if (text != null) { if (toAdd != null && !toAdd.equals("\n")) // NOI18N { text += toAdd; } // Update the text doc.atomicLock(); try { String textToReplace = doc.getText(offset, len); if (text.equals(textToReplace)) { return false; } if(!shifted) {//we are not in part of literal completion //dirty hack for @Table(name=CUS| if (!text.startsWith("\"")) { text = quoteText(text); } //check if there is already an end quote char ch = doc.getText(offset + len, 1).charAt(0); if (ch == '"') { //remove also this end quote since the inserted value is always quoted len++; } } doc.remove(offset, len); doc.insertString(offset, text, null); } catch (BadLocationException e) { // Can't update } finally { doc.atomicUnlock(); } return true; } else { return false; } }