List of usage examples for javax.swing.text StyledDocument getParagraphElement
public Element getParagraphElement(int pos);
From source file:com.keevosh.springframework.boot.netbeans.SpringBootConfigurationCompletionProvider.java
static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException { Element lineElement = doc.getParagraphElement(offset); int start = lineElement.getStartOffset(); while (start + 1 < lineElement.getEndOffset()) { try {/*from w w w .j a v a2s . co m*/ if (doc.getText(start, 1).charAt(0) != ' ') { break; } } catch (BadLocationException ex) { throw (BadLocationException) new BadLocationException( "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(), start).initCause(ex); } start++; } return start; }
From source file:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropsCompletionProvider.java
@Override public CompletionTask createTask(int queryType, JTextComponent jtc) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) { return null; }/*from w w w.j av a2s . c o m*/ Project prj = Utilities.actionsGlobalContext().lookup(Project.class); if (prj == null) { return null; } logger.log(FINE, "Completing within context of prj {0}", FileUtil.getFileDisplayName(prj.getProjectDirectory())); final SpringBootService sbs = prj.getLookup().lookup(SpringBootService.class); if (sbs == null) { return null; } logger.fine("Creating completion task"); return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { final StyledDocument styDoc = (StyledDocument) document; Element lineElement = styDoc.getParagraphElement(caretOffset); int lineStartOffset = lineElement.getStartOffset(); try { String lineToCaret = styDoc.getText(lineStartOffset, caretOffset - lineStartOffset); logger.log(FINER, "Completion on line to caret: {0}", lineToCaret); if (!lineToCaret.contains("#")) { String[] parts = lineToCaret.split("="); //property name extraction from part before = Matcher matcher = PATTERN_PROP_NAME.matcher(parts[0]); String propPrefix = null; int propPrefixOffset = 0; while (matcher.find()) { propPrefix = matcher.group(); propPrefixOffset = matcher.start(); } // check which kind of completion final int equalSignOffset = lineToCaret.indexOf('='); if (parts.length > 1) { //value completion String valPrefix = parts[1].trim(); completePropValue(sbs, completionResultSet, propPrefix, valPrefix, lineStartOffset + lineToCaret.indexOf(valPrefix, equalSignOffset), caretOffset); } else if (equalSignOffset >= 0) { //value completion with empty filter completePropValue(sbs, completionResultSet, propPrefix, null, lineStartOffset + equalSignOffset + 1, caretOffset); } else { // property completion completePropName(sbs, completionResultSet, propPrefix, lineStartOffset + propPrefixOffset, caretOffset); } } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } completionResultSet.finish(); } }, jtc); }
From source file:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropCompletionItem.java
@Override public void defaultAction(JTextComponent jtc) { try {//from w w w .ja va2 s .c o m StyledDocument doc = (StyledDocument) jtc.getDocument(); // calculate the amount of chars to remove (by default from property start up to caret position) int lenToRemove = caretOffset - propStartOffset; if (overwrite) { // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed // the document state here is different from when the completion was invoked thus we have to // find again the offset of the equal sign in the line Element lineElement = doc.getParagraphElement(caretOffset); String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset()); int equalSignIndex = line.indexOf('='); if (equalSignIndex >= 0) { // from property start to equal sign lenToRemove = lineElement.getStartOffset() + equalSignIndex - propStartOffset; } else { // from property start to end of line (except line terminator) lenToRemove = lineElement.getEndOffset() - 1 - propStartOffset; } } // remove characters from the property name start offset doc.remove(propStartOffset, lenToRemove); doc.insertString(propStartOffset, getText(), null); // close the code completion box Completion.get().hideAll(); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.debux.webmotion.netbeans.completion.WebMotionCompletion.java
@Override public CompletionTask createTask(int queryType, JTextComponent component) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) { return null; }//from w w w . j a va 2 s . co m return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { String filter = null; int startOffset = caretOffset - 1; int column = 0; try { // Get filter StyledDocument doc = (StyledDocument) document; int lineStartOffset = Utils.getRowFirstNonWhite(doc, caretOffset); char[] line = doc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray(); int whiteOffset = Utils.indexOfWhite(line); filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1); if (whiteOffset > 0) { startOffset = lineStartOffset + whiteOffset + 1; } else { startOffset = lineStartOffset; } // Get position Element lineElement = doc.getParagraphElement(caretOffset); String lineValue = doc.getText(lineElement.getStartOffset(), caretOffset - lineElement.getStartOffset()); Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(lineValue); while (matcher.find()) { column++; } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } // Get section Section section = LexerUtils.getSection(document, caretOffset); // Get the package in configuration String packageBase = Utils.getPackageValue("package.base", null); String packageTarget = null; String filterSuperClass = null; String separator = "/"; boolean onlyFolder = false; String onlyMimeType = null; String[] keywords = {}; if (section != null) { if (section == Section.CONFIG) { keywords = KEYWORDS_CONFIG; } else if (section == Section.ERRORS && column % 2 == 0) { keywords = KEYWORDS_ERROR; packageTarget = ""; filterSuperClass = "java.lang.Exception"; } else if (section == Section.ERRORS && column % 2 == 1) { keywords = KEYWORDS_ERROR_ACTION; if (filter.startsWith("view:")) { packageTarget = Utils.getPackageValue("package.views", null); } else if (filter.startsWith("action:") || !filter.contains(":")) { packageTarget = Utils.getPackageValue("package.errors", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionController"; } } else if (section == Section.EXTENSIONS && column % 2 == 0) { keywords = KEYWORDS_EXTENSION; } else if (section == Section.EXTENSIONS && column % 2 == 1) { packageTarget = ""; onlyMimeType = WebMotionLanguage.MIME_TYPE; } else if (section == Section.FILTERS && column % 3 == 0) { keywords = KEYWORDS_METHODS; } else if (section == Section.FILTERS && column % 3 == 1) { keywords = KEYWORDS_FILTER; } else if (section == Section.FILTERS && column % 3 == 2) { keywords = KEYWORDS_FILTER_ACTION; packageTarget = Utils.getPackageValue("package.filters", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionFilter"; } else if (section == Section.ACTIONS && column % 3 == 0) { keywords = KEYWORDS_METHODS; } else if (section == Section.ACTIONS && column % 3 == 1) { keywords = KEYWORDS_ACTION; } else if (section == Section.ACTIONS && column % 3 == 2) { keywords = KEYWORDS_ACTION_ACTION; if (filter.startsWith("view:")) { packageTarget = Utils.getPackageValue("package.views", null); } else if (filter.startsWith("action:") || !filter.contains(":")) { packageTarget = Utils.getPackageValue("package.actions", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionController"; } } else if (section == Section.PROPERTIES) { keywords = KEYWORDS_SECTIONS; } } else { keywords = KEYWORDS_SECTIONS; } // Keywords if (keywords == KEYWORDS_METHODS && filter.contains(",")) { keywords = KEYWORDS_METHOD; startOffset += StringUtils.substringBeforeLast(filter, ",").length(); filter = StringUtils.substringAfterLast(filter, ","); } else if (keywords == KEYWORDS_ERROR && filter.contains("code:")) { keywords = KEYWORDS_ERROR_CODE; startOffset += "code:".length(); filter = filter.substring("code:".length()); packageTarget = null; } else if (filter.startsWith("javac.debug=") || filter.startsWith("server.async=") || filter.startsWith("server.static.autodetect=")) { keywords = KEYWORDS_CONFIG_BOOLEAN; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.error.page=")) { keywords = KEYWORDS_CONFIG_ERROR; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.controller.scope=")) { keywords = KEYWORDS_CONFIG_SCOPE; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("package.base=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/"); packageTarget = ""; filterSuperClass = null; separator = "."; onlyFolder = true; } else if (filter.startsWith("package.views=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/"); packageTarget = ""; filterSuperClass = null; separator = "/"; onlyFolder = true; } else if (filter.startsWith("server.listener.class=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.WebMotionServerListener"; } else if (filter.startsWith("server.main.handler.class=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.WebMotionHandler"; } else if (filter.startsWith("default.render=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.render.Render"; } else if (filter.startsWith("package.actions=") || filter.startsWith("package.filters=") || filter.startsWith("package.errors=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = Utils.getPackageValue("package.base", null); filterSuperClass = null; separator = "."; onlyFolder = true; } else if (filter.startsWith("server.encoding=")) { keywords = KEYWORDS_CONFIG_ENCODING; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.secret=")) { keywords = new String[] { RandomStringUtils.random(31, true, true) }; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("javac.debug") || filter.startsWith("server.async") || filter.startsWith("server.static.autodetect") || filter.startsWith("server.error.page") || filter.startsWith("server.controller.scope") || filter.startsWith("package.base") || filter.startsWith("package.views") || filter.startsWith("server.listener.class") || filter.startsWith("server.main.handler.class") || filter.startsWith("package.actions") || filter.startsWith("package.filters") || filter.startsWith("package.errors") || filter.startsWith("server.encoding") || filter.startsWith("server.secret")) { keywords = KEYWORDS_CONFIG_EQUAL; startOffset += StringUtils.substringBefore(filter, "=").length(); filter = ""; } for (String keyword : keywords) { if (keyword.startsWith(filter)) { completionResultSet.addItem(new WebMotionCompletionItem(keyword, startOffset, caretOffset)); } } if (packageTarget != null) { // File if (filterSuperClass == null) { String path = packageTarget.replaceAll("\\.", "/"); String filterFile = filter; int startOffsetFile = startOffset; Set<String> names = new HashSet<String>(); if (filter.startsWith("view:")) { filterFile = filter.replaceFirst("view:", ""); startOffsetFile += "view:".length(); } if (filterFile.contains("/")) { String current = StringUtils.substringBeforeLast(filterFile, "/"); path += current; startOffsetFile += current.length() + 1; filterFile = StringUtils.substringAfterLast(filterFile, "/"); } else if (packageTarget.isEmpty() && separator.equals("/")) { String fileName = "WEB-INF"; names.add(fileName); if (fileName.startsWith(filterFile)) { if (!fileName.equals(filterFile)) { completionResultSet.addItem( new WebMotionCompletionItem(fileName, startOffsetFile, caretOffset)); } else { completionResultSet.addItem(new WebMotionCompletionItem(separator, startOffsetFile + fileName.length(), caretOffset)); } } } GlobalPathRegistry registry = GlobalPathRegistry.getDefault(); List<ClassPath> paths = new ArrayList<ClassPath>(); paths.addAll(registry.getPaths(ClassPath.BOOT)); paths.addAll(registry.getPaths(ClassPath.COMPILE)); paths.addAll(registry.getPaths(ClassPath.SOURCE)); for (ClassPath classPath : paths) { FileObject resource = classPath.findResource(path); if (resource != null) { FileObject[] children = resource.getChildren(); for (FileObject child : children) { String fileName = child.getNameExt(); if ((!onlyFolder || onlyFolder && child.isFolder()) && (onlyMimeType == null || child.isFolder() || onlyMimeType != null && child.getMIMEType().equals(onlyMimeType)) && fileName.startsWith(filterFile) && !fileName.startsWith(".")) { if (!names.contains(fileName)) { if (!fileName.equals(filterFile)) { completionResultSet.addItem(new WebMotionCompletionItem(fileName, startOffsetFile, caretOffset)); } else { completionResultSet.addItem(new WebMotionCompletionItem(separator, startOffsetFile + fileName.length(), caretOffset)); } names.add(fileName); } } } } } completionResultSet.finish(); } else { // Class if (filter.contains(":") && !filter.startsWith("code:")) { startOffset += StringUtils.substringBefore(filter, ":").length() + 1; filter = StringUtils.substringAfter(filter, ":"); } int startOffsetClass = startOffset; if (filter.contains(".")) { startOffsetClass += StringUtils.substringBeforeLast(filter, ".").length() + 1; } String fullName = packageTarget + filter; String rootPackage = ""; String filerPackage = fullName; if (fullName.contains(".")) { rootPackage = StringUtils.substringBeforeLast(fullName, "."); filerPackage = StringUtils.substringAfterLast(fullName, "."); } String folderPackage = rootPackage.replaceAll("\\.", "/"); FileObject fo = Utils.getFO(document); ClassPath bootCp = ClassPath.getClassPath(fo, ClassPath.BOOT); ClassPath compileCp = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClasspathInfo info = ClasspathInfo.create(bootCp, compileCp, sourcePath); JavaSource src = JavaSource.create(info); final String filterSuperJavaClass = filterSuperClass; final CompletionResultSet completionResultSetClass = completionResultSet; final int startOffsetJavaClass = startOffsetClass; final int caretOffsetClass = caretOffset; // Package names List<FileObject> folders = new ArrayList<FileObject>(); folders.addAll(bootCp.findAllResources(folderPackage)); folders.addAll(compileCp.findAllResources(folderPackage)); folders.addAll(sourcePath.findAllResources(folderPackage)); final String rootPackageFilter = rootPackage; final String filterPackageFilter = filerPackage; final Set<String> names = new HashSet<String>(); for (final FileObject folder : folders) { try { src.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController cu) throws Exception { Types types = cu.getTypes(); Elements elements = cu.getElements(); TypeElement superElement = elements.getTypeElement(filterSuperJavaClass); TypeMirror superType = null; if (superElement != null) { superType = superElement.asType(); } FileObject[] children = folder.getChildren(); for (FileObject child : children) { String name = child.getName(); if (!name.startsWith(".") && name.startsWith(filterPackageFilter)) { if (!names.contains(name)) { names.add(name); TypeElement element; if (rootPackageFilter.isEmpty()) { element = elements.getTypeElement(name); } else { element = elements .getTypeElement(rootPackageFilter + "." + name); } if (name.equals(filterPackageFilter)) { if (element == null || element.getKind() != ElementKind.CLASS || element.getKind() == ElementKind.CLASS && (filterSuperJavaClass.equals( "org.debux.webmotion.server.WebMotionFilter") || filterSuperJavaClass.equals( "org.debux.webmotion.server.WebMotionController"))) { WebMotionCompletionItem item = new WebMotionCompletionItem( ".", startOffsetJavaClass + name.length(), caretOffsetClass); completionResultSetClass.addItem(item); } } else if (child.isFolder()) { WebMotionCompletionItem item = new WebMotionCompletionItem( name, startOffsetJavaClass, caretOffsetClass); completionResultSetClass.addItem(item); } else if (element != null) { Set<Modifier> modifiers = element.getModifiers(); ElementKind kind = element.getKind(); TypeMirror resolveType = element.asType(); if (kind == ElementKind.CLASS && modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.ABSTRACT) && superType != null && types.isSubtype(resolveType, superType)) { WebMotionCompletionItem item = new WebMotionCompletionItem( name, cu, element, startOffsetJavaClass, caretOffsetClass); completionResultSetClass.addItem(item); } } } } } } }, false); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } // Method if (filter.contains(".") && (filterSuperJavaClass .equals("org.debux.webmotion.server.WebMotionFilter") || filterSuperJavaClass.equals("org.debux.webmotion.server.WebMotionController"))) { final String className = StringUtils.substringBeforeLast(filter, "."); final String fullClassName = packageTarget + className; final String filterMethod = StringUtils.substringAfterLast(filter, "."); final CompletionResultSet completionResultSetJavaSource = completionResultSet; final int startOffsetJavaSource = startOffset + className.length() + 1; final int caretOffesetJavaSource = caretOffset; try { src.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController cu) throws Exception { cu.toPhase(JavaSource.Phase.PARSED); Elements elements = cu.getElements(); TypeElement classElement = elements.getTypeElement(fullClassName); if (classElement != null) { List<? extends javax.lang.model.element.Element> members = elements .getAllMembers(classElement); for (javax.lang.model.element.Element member : members) { if (member.getKind() == ElementKind.METHOD) { Set<Modifier> modifiers = member.getModifiers(); String methodName = member.getSimpleName().toString(); String className = member.getEnclosingElement().getSimpleName() .toString(); if (!"Object".equals(className) && !"WebMotionController".equals(className) && !"WebMotionFilter".equals(className) && modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.STATIC) && methodName.startsWith(filterMethod)) { WebMotionCompletionItem item = new WebMotionCompletionItem( methodName, cu, member, startOffsetJavaSource, caretOffesetJavaSource); completionResultSetJavaSource.addItem(item); } } } } completionResultSetJavaSource.finish(); } }, false); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } else { completionResultSet.finish(); } } } else { completionResultSet.finish(); } } }, component); }
From source file:org.debux.webmotion.netbeans.Utils.java
public static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException { Element lineElement = doc.getParagraphElement(offset); int start = lineElement.getStartOffset(); while (start + 1 < lineElement.getEndOffset()) { try {//from w ww. j a va 2 s . c o m char charAt = doc.getText(start, 1).charAt(0); if (charAt != ' ') { break; } } catch (BadLocationException ex) { throw (BadLocationException) new BadLocationException( "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(), start).initCause(ex); } start++; } return start; }
From source file:plugin.notes.gui.NotesView.java
private void handleBackspace() { // TODO: This sucks, clean it up Element elem;/*w ww .java2s. co m*/ int pos = editor.getCaretPosition(); StyledDocument htmlDoc = editor.getStyledDocument(); try { if (pos > 0) { if ((editor.getSelectedText()) != null) { ExtendedHTMLEditorKit.delete(editor); return; } int sOffset = htmlDoc.getParagraphElement(pos).getStartOffset(); if (sOffset == editor.getSelectionStart()) { if (ExtendedHTMLEditorKit .checkParentsTag(htmlDoc.getParagraphElement(editor.getCaretPosition()), HTML.Tag.LI)) { elem = ExtendedHTMLEditorKit .getListItemParent(htmlDoc.getCharacterElement(editor.getCaretPosition())); boolean content = false; int so = elem.getStartOffset(); int eo = elem.getEndOffset(); if ((so + 1) < eo) { char[] temp = editor.getText(so, eo - so).toCharArray(); for (char aTemp : temp) { if (!Character.isWhitespace(aTemp)) { content = true; } } } if (!content) { elem.getParentElement(); ExtendedHTMLEditorKit.removeTag(editor, elem); editor.setCaretPosition(sOffset - 1); return; } editor.setCaretPosition(editor.getCaretPosition() - 1); editor.moveCaretPosition(editor.getCaretPosition() - 2); editor.replaceSelection(""); return; } } editor.replaceSelection(""); } } catch (BadLocationException ble) { Logging.errorPrint(ble.getMessage(), ble); } }