Java Code Examples for org.netbeans.editor.BaseDocument#getLength()
The following examples show how to use
org.netbeans.editor.BaseDocument#getLength() .
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: 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 2
Source File: JsTypedTextInterceptor.java From netbeans with Apache License 2.0 | 6 votes |
private boolean isQuoteCompletablePosition(BaseDocument doc, int dotPos) throws BadLocationException { if (dotPos == doc.getLength()) { // there's no other character to test return true; } else { // test that we are in front of ) , " or ' ... etc. int eol = Utilities.getRowEnd(doc, dotPos); if ((dotPos == eol) || (eol == -1)) { return false; } int firstNonWhiteFwd = Utilities.getFirstNonWhiteFwd(doc, dotPos, eol); if (firstNonWhiteFwd == -1) { return false; } char chr = doc.getChars(firstNonWhiteFwd, 1)[0]; return ((chr == ')') || (chr == ',') || (chr == '+') || (chr == '}') || (chr == ';') || (chr == ']')); } }
Example 3
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 4
Source File: GroovyTypedTextInterceptor.java From netbeans with Apache License 2.0 | 6 votes |
private boolean isQuoteCompletablePosition(BaseDocument doc, int dotPos) throws BadLocationException { if (dotPos == doc.getLength()) { // there's no other character to test return true; } else { // test that we are in front of ) , " or ' ... etc. int eol = Utilities.getRowEnd(doc, dotPos); if ((dotPos == eol) || (eol == -1)) { return false; } int firstNonWhiteFwd = Utilities.getFirstNonWhiteFwd(doc, dotPos, eol); if (firstNonWhiteFwd == -1) { return false; } char chr = doc.getChars(firstNonWhiteFwd, 1)[0]; return ((chr == ')') || (chr == ',') || (chr == '+') || (chr == '}') || (chr == ';') || (chr == ']')); } }
Example 5
Source File: AstPath.java From netbeans with Apache License 2.0 | 6 votes |
public AstPath(ASTNode root, int caretOffset, BaseDocument document) { try { // make sure offset is not higher than document length, see #138353 int length = document.getLength(); int offset = length == 0 ? 0 : caretOffset + 1; if (length > 0 && offset >= length) { offset = length - 1; } Scanner scanner = new Scanner(document.getText(0, offset)); int line = 0; String lineText = ""; while (scanner.hasNextLine()) { lineText = scanner.nextLine(); line++; } int column = lineText.length(); this.lineNumber = line; this.columnNumber = column; findPathTo(root, line, column); } catch (BadLocationException ble) { Exceptions.printStackTrace(ble); } }
Example 6
Source File: YamlScanner.java From netbeans with Apache License 2.0 | 6 votes |
private void addBlocks(YamlParserResult result, BaseDocument doc, CharSequence text, List<OffsetRange> codeblocks, StructureItem item) throws BadLocationException { int docLength = doc == null ? text.length() : doc.getLength(); int begin = Math.min((int) item.getPosition(), docLength); int end = Math.min((int) item.getEndPosition(), docLength); int firstRowEnd = doc == null ? GsfUtilities.getRowEnd(text, begin) : Utilities.getRowEnd(doc, begin); int lastRowEnd = doc == null ? GsfUtilities.getRowEnd(text, end) : Utilities.getRowEnd(doc, end); if (begin < end && firstRowEnd != lastRowEnd) { codeblocks.add(new OffsetRange(firstRowEnd, end)); } else { return; } for (StructureItem child : item.getNestedItems()) { int childBegin = (int) child.getPosition(); int childEnd = (int) child.getEndPosition(); if (childBegin >= begin && childEnd <= end) { addBlocks(result, doc, text, codeblocks, child); } } }
Example 7
Source File: JspPaletteUtilities.java From netbeans with Apache License 2.0 | 5 votes |
/**************************************************************************/ private static void insertTagLibRef(JTextComponent target, String prefix, String uri) { Document doc = target.getDocument(); if (doc != null && doc instanceof BaseDocument) { BaseDocument baseDoc = (BaseDocument)doc; baseDoc.atomicLock(); try { int pos = 0; // FIXME: compute better where to insert tag lib definition? String definition = "<%@taglib prefix=\""+prefix+"\" uri=\""+uri+"\"%>\n"; //NOI18N //test for .jspx. FIXME: find better way to detect xml syntax?. FileObject fobj = getFileObject(target); if (fobj != null && "jspx".equals(fobj.getExt())) { int baseDocLength = baseDoc.getLength(); String text = baseDoc.getText(0, baseDocLength); String jspRootBegin = "<jsp:root "; //NOI18N int jspRootIndex = text.indexOf(jspRootBegin); if (jspRootIndex != -1) { pos = jspRootIndex + jspRootBegin.length(); definition = "xmlns:" + prefix + "=\"" + uri + "\" "; //NOI18N } } doc.insertString(pos, definition, null); } catch (BadLocationException e) { Exceptions.printStackTrace(e); } finally { baseDoc.atomicUnlock(); } } }
Example 8
Source File: PHPFormatterQATest.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void reformatFileContents(String file, IndentPrefs preferences) 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(preferences); //assertNotNull("getFormatter must be implemented", formatter); setupDocumentIndentation(doc, preferences); format(doc, formatter, formatStart, formatEnd, false); String after = doc.getText(0, doc.getLength()); if (preferences.getIndentation() != 2 || preferences.getHangingIndentation() != 2) { assertDescriptionMatches(file, after, false, "_" + preferences.getIndentation() + "_" + preferences.getHangingIndentation() + ".formatted"); } else { assertDescriptionMatches(file, after, false, ".formatted"); } }
Example 9
Source File: PhpTypedTextInterceptor.java From netbeans with Apache License 2.0 | 5 votes |
/** * Checks whether dotPos is a position at which bracket and quote completion * is performed. Brackets and quotes are not completed everywhere but just * at suitable places . * * @param doc the document * @param dotPos position to be tested */ private boolean isCompletablePosition(BaseDocument doc, int dotPos) throws BadLocationException { if (dotPos == doc.getLength()) { // there's no other character to test return true; } else { // test that we are in front of ) , " or ' char chr = doc.getChars(dotPos, 1)[0]; return ((chr == ')') || (chr == ',') || (chr == '\"') || (chr == '\'') || (chr == ' ') || (chr == ']') || (chr == '}') || (chr == '\n') || (chr == '\t') || (chr == ';')); } }
Example 10
Source File: JspCompletionQueryTest.java From netbeans with Apache License 2.0 | 5 votes |
private void testCompletionResults(String testFile) throws IOException, BadLocationException { FileObject source = getTestFile(DATA_DIR_BASE + testFile); BaseDocument doc = getDocument(source); JspCompletionQuery query = JspCompletionQuery.instance(); JEditorPane component = new JEditorPane(); component.setDocument(doc); StringBuffer output = new StringBuffer(); for (int i = 0; i < doc.getLength(); i++) { JspCompletionQuery.CompletionResultSet result = new JspCompletionQuery.CompletionResultSet(); query.query(result, component, i); if (result != null) { List<CompletionItem> items = result.getItems(); output.append(i + ":"); output.append('['); Iterator<CompletionItem> itr = items.iterator(); while (itr.hasNext()) { CompletionItem ci = itr.next(); if (ci instanceof JspCompletionItem) { //test only html completion items JspCompletionItem htmlci = (JspCompletionItem) ci; output.append(htmlci.getItemText()); if (itr.hasNext()) { output.append(','); } } } output.append(']'); output.append('\n'); } } assertDescriptionMatches(source, output.toString(), false, ".pass", true); }
Example 11
Source File: LexUtilities.java From netbeans with Apache License 2.0 | 5 votes |
/** * Return true iff the line for the given offset is a comment line. * This will return false for lines that contain comments (even when the * offset is within the comment portion) but also contain code. */ public static boolean isCommentOnlyLine(BaseDocument doc, int offset) throws BadLocationException { int begin = Utilities.getRowFirstNonWhite(doc, offset); if (begin == -1) { return false; // whitespace only } if (begin == doc.getLength()) { return false; } return false; //doc.getText(begin, 2).equals("//") || doc.getText(begin, 1).equals("*"); }
Example 12
Source File: GroovyTypedTextInterceptor.java From netbeans with Apache License 2.0 | 5 votes |
/** * Checks whether dotPos is a position at which bracket and quote * completion is performed. Brackets and quotes are not completed * everywhere but just at suitable places . * @param doc the document * @param dotPos position to be tested */ private boolean isCompletablePosition(BaseDocument doc, int dotPos) throws BadLocationException { if (dotPos == doc.getLength()) { // there's no other character to test return true; } else { // test that we are in front of ) , " or ' char chr = doc.getChars(dotPos, 1)[0]; return ((chr == ')') || (chr == ',') || (chr == '\"') || (chr == '\'') || (chr == ' ') || (chr == ']') || (chr == '}') || (chr == '\n') || (chr == '\t') || (chr == ';')); } }
Example 13
Source File: JsTypedTextInterceptor.java From netbeans with Apache License 2.0 | 5 votes |
/** * Checks whether dotPos is a position at which bracket and quote * completion is performed. Brackets and quotes are not completed * everywhere but just at suitable places . * @param doc the document * @param dotPos position to be tested */ private boolean isCompletablePosition(BaseDocument doc, int dotPos) throws BadLocationException { if (dotPos == doc.getLength()) { // there's no other character to test return true; } else { // test that we are in front of ) , " or ' char chr = doc.getChars(dotPos, 1)[0]; return ((chr == ')') || (chr == ',') || (chr == '\"') || (chr == '\'') || (chr == '`') || (chr == ' ') || (chr == ']') || (chr == '}') || (chr == '\n') || (chr == '\t') || (chr == ';')); } }
Example 14
Source File: JavaMoveCodeElementAction.java From netbeans with Apache License 2.0 | 4 votes |
private int findDestinationOffset(CompilationInfo cInfo, BaseDocument doc, int offset, boolean insideBlock) { TreeUtilities tu = cInfo.getTreeUtilities(); SourcePositions sp = cInfo.getTrees().getSourcePositions(); while (true) { if (offset < 0 || offset > doc.getLength()) { return -1; } int destinationOffset = downward ? getLineEnd(doc, offset) : getLineStart(doc, offset); if (doc instanceof GuardedDocument && ((GuardedDocument)doc).isPosGuarded(destinationOffset)) { return -1; } if (destinationOffset < doc.getLength()) { TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), destinationOffset); if (ts != null && (ts.moveNext() || ts.movePrevious())) { if (ts.offset() < destinationOffset && ts.token().id() != JavaTokenId.WHITESPACE) { offset = downward ? ts.offset() + ts.token().length() : ts.offset(); continue; } } } TreePath destinationPath = tu.pathFor(destinationOffset); Tree leaf = destinationPath.getLeaf(); if (insideBlock) { switch (leaf.getKind()) { case COMPILATION_UNIT: return -1; case BLOCK: return destinationOffset; case IF: case FOR_LOOP: case ENHANCED_FOR_LOOP: case WHILE_LOOP: case DO_WHILE_LOOP: case SWITCH: case CASE: case SYNCHRONIZED: case TRY: case CATCH: offset = destinationOffset + (downward ? 1 : -1); break; default: offset = downward ? (int) sp.getEndPosition(destinationPath.getCompilationUnit(), leaf) : (int) sp.getStartPosition(destinationPath.getCompilationUnit(), leaf); } } else { switch (leaf.getKind()) { case COMPILATION_UNIT: return -1; case CLASS: case INTERFACE: case ANNOTATION_TYPE: case ENUM: return destinationOffset; default: offset = downward ? (int) sp.getEndPosition(destinationPath.getCompilationUnit(), leaf) : (int) sp.getStartPosition(destinationPath.getCompilationUnit(), leaf); } } } }
Example 15
Source File: LexUtilities.java From netbeans with Apache License 2.0 | 4 votes |
public static OffsetRange getCommentBlock(BaseDocument doc, int caretOffset) { // Check if the caret is within a comment, and if so insert a new // leaf "node" which contains the comment line and then comment block try { Token<GroovyTokenId> token = getToken(doc, caretOffset); if ((token != null) && (token.id() == GroovyTokenId.LINE_COMMENT)) { // First add a range for the current line int begin = Utilities.getRowStart(doc, caretOffset); int end = Utilities.getRowEnd(doc, caretOffset); if (LexUtilities.isCommentOnlyLine(doc, caretOffset)) { while (begin > 0) { int newBegin = Utilities.getRowStart(doc, begin - 1); if ((newBegin < 0) || !LexUtilities.isCommentOnlyLine(doc, newBegin)) { begin = Utilities.getRowFirstNonWhite(doc, begin); break; } begin = newBegin; } int length = doc.getLength(); while (true) { int newEnd = Utilities.getRowEnd(doc, end + 1); if ((newEnd >= length) || !LexUtilities.isCommentOnlyLine(doc, newEnd)) { end = Utilities.getRowLastNonWhite(doc, end) + 1; break; } end = newEnd; } if (begin < end) { return new OffsetRange(begin, end); } } else { // It's just a line comment next to some code TokenHierarchy<Document> th = TokenHierarchy.get((Document) doc); int offset = token.offset(th); return new OffsetRange(offset, offset + token.length()); } } } catch (BadLocationException ble) { Exceptions.printStackTrace(ble); } return OffsetRange.NONE; }
Example 16
Source File: PhpTypedTextInterceptor.java From netbeans with Apache License 2.0 | 4 votes |
/** * Check whether the typed bracket should stay in the document or be * removed. <br> This method is called by * <code>skipClosingBracket()</code>. * * @param doc document into which typing was done. * @param caretOffset */ private boolean isSkipClosingBracket(BaseDocument doc, int caretOffset, char bracket) throws BadLocationException { if (caretOffset == doc.getLength()) { return false; } TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, caretOffset); if (ts == null) { return false; } ts.move(caretOffset); if (!ts.moveNext()) { return false; } Token<? extends PHPTokenId> token = ts.token(); boolean skipClosingBracket = false; // Check whether character follows the bracket is the same bracket if ((token != null) && (LexUtilities.textEquals(token.text(), bracket))) { char leftBracket = bracket == ')' ? '(' : (bracket == ']' ? '[' : '{'); int bracketBalanceWithNewBracket = 0; ts.moveStart(); if (!ts.moveNext()) { return false; } token = ts.token(); while (token != null) { if ((LexUtilities.textEquals(token.text(), '(')) || (LexUtilities.textEquals(token.text(), '['))) { if (LexUtilities.textEquals(token.text(), leftBracket)) { bracketBalanceWithNewBracket++; } } else if ((LexUtilities.textEquals(token.text(), ')')) || (LexUtilities.textEquals(token.text(), ']'))) { if (LexUtilities.textEquals(token.text(), bracket)) { bracketBalanceWithNewBracket--; } } if (!ts.moveNext()) { break; } token = ts.token(); } if (bracketBalanceWithNewBracket == 0) { skipClosingBracket = false; } else { skipClosingBracket = true; } } return skipClosingBracket; }
Example 17
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 18
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 19
Source File: WhereUsedElement.java From netbeans with Apache License 2.0 | 4 votes |
public static WhereUsedElement create(FileObject fileObject, Entry entry, ElementKind kind, boolean related) { Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList()); String name = entry.getName(); OffsetRange range = entry.getDocumentRange(); 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); 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) { Exceptions.printStackTrace(ex); } finally { bdoc.readUnlock(); } StringBuilder sb = new StringBuilder(); 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; } sb.append(encodeCharRefs(content.subSequence(sta, start).toString())); sb.append("<b>"); // NOI18N sb.append(content.subSequence(start, end)); sb.append("</b>"); // NOI18N sb.append(encodeCharRefs(content.subSequence(end, en).toString())); if(!related) { sb.append(NbBundle.getMessage(WhereUsedElement.class, "MSG_Unrelated_Where_Used_Occurance")); //NOI18N } 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, sb.toString().trim(), fileObject, name, new OffsetRange(start, end), icon); }
Example 20
Source File: JsFormatter.java From netbeans with Apache License 2.0 | 4 votes |
private int isEndIndent(IndentContext context, int offset) throws BadLocationException { BaseDocument doc = context.getDocument(); int lineBegin = Utilities.getRowFirstNonWhite(doc, offset); if (lineBegin != -1) { Token<?extends JsTokenId> token = getFirstToken(context, offset); if (token == null) { return 0; } 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. if (id == JsTokenId.BRACKET_RIGHT_CURLY || id == JsTokenId.BRACKET_RIGHT_BRACKET /*|| id == JsTokenId.BRACKET_RIGHT_PAREN*/) { int indents = 1; // Check if there are multiple end markers here... if so increase indent level. // This should really do an iteration... for now just handling the most common // scenario in JavaScript where we have }) in object literals int lineEnd = Utilities.getRowEnd(doc, offset); int newOffset = offset; while (newOffset < lineEnd && token != null) { newOffset = newOffset + token.length(); if (newOffset < doc.getLength()) { token = LexUtilities.getToken(doc, newOffset, language); if (token != null) { id = token.id(); if (id == JsTokenId.WHITESPACE) { continue; } else { break; } } } } return indents; } } return 0; }