Example usage for javax.swing.text Element getStartOffset

List of usage examples for javax.swing.text Element getStartOffset

Introduction

In this page you can find the example usage for javax.swing.text Element getStartOffset.

Prototype

public int getStartOffset();

Source Link

Document

Fetches the offset from the beginning of the document that this element begins at.

Usage

From source file:org.alder.fotobuchconvert.scribus.RtfToScribusConverter.java

void output(XmlBuilder xml, DefaultStyledDocument doc, ScribusWriter scribus) {
    log.debug("Starting conversion of RTF data");
    if (log.isTraceEnabled())
        doc.dump(System.err);/*from   w w  w . j  a va 2 s . c  om*/

    try {
        Element section = doc.getDefaultRootElement();
        log.trace(section);
        assert section.getName().equals("section");

        final int nj = section.getElementCount();
        for (int j = 0; j < nj; j++) {
            Element paragraph = section.getElement(j);
            log.trace(paragraph);
            assert section.getName().equals("paragraph");

            // boolean firstInPara = true;
            AttributeSet attr = paragraph.getAttributes();
            Integer alignment = (Integer) attr.getAttribute(StyleConstants.Alignment);

            boolean elementsInThisLine = false;
            final int ni = paragraph.getElementCount();
            for (int i = 0; i < ni; i++) {
                Element content = paragraph.getElement(i);
                assert section.getName().equals("content");

                int start = content.getStartOffset();
                int end = content.getEndOffset();

                attr = content.getAttributes();
                Boolean italic = (Boolean) attr.getAttribute(StyleConstants.Italic);
                Boolean bold = (Boolean) attr.getAttribute(StyleConstants.Bold);
                Boolean underline = (Boolean) attr.getAttribute(StyleConstants.Underline);
                String family = (String) attr.getAttribute(StyleConstants.Family);
                Integer fontSize = (Integer) attr.getAttribute(StyleConstants.Size);
                Color color = (Color) attr.getAttribute(StyleConstants.ColorConstants.Foreground);

                String text = doc.getText(start, end - start);

                // if (firstInPara && text.trim().isEmpty() && family ==
                // null
                // && fontSize == null)
                // continue;
                // else
                // firstInPara = false;
                if (i == ni - 1 && text.trim().isEmpty() && text.length() < 3)
                    continue;
                elementsInThisLine = true;

                while (text.endsWith("\n") || text.endsWith("\r"))
                    text = text.substring(0, text.length() - 1);

                log.debug(italic + " " + bold + " " + underline + " " + family + " " + fontSize + " " + color
                        + "\t\"" + text + "\"");

                XmlBuilder el = xml.add(C.EL_ITEXT).set(C.CH, text);

                if (bold == Boolean.TRUE && italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold Italic");
                else if (bold == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold");
                else if (italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Italic");
                else
                    el.set(C.FONT, family + " Regular");

                if (fontSize != null)
                    el.set(C.FONTSIZE, fontSize);

                if (color != null && color.equals(Color.BLACK) && scribus != null) {
                    String colname = scribus.colorManager.getColorName(color);
                    el.set(C.FCOLOR, colname);
                }
            }

            if (!elementsInThisLine && j == nj - 1)
                break; // don't convert last line if empty

            XmlBuilder el = xml.add(C.EL_PARA);
            if (alignment != null)
                switch (alignment) {
                case StyleConstants.ALIGN_LEFT:
                    el.set(C.ALIGN, 0);
                    break;
                case StyleConstants.ALIGN_CENTER:
                    el.set(C.ALIGN, 1);
                    break;
                case StyleConstants.ALIGN_RIGHT:
                    el.set(C.ALIGN, 2);
                    break;
                case StyleConstants.ALIGN_JUSTIFIED:
                    el.set(C.ALIGN, 3);
                    break;
                }
        }
    } catch (BadLocationException e) {
        throw new RuntimeException("This error should not occour", e);
    }

}

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  ww  . j a  v a  2 s. c o  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  www  .j a v a2 s. c om
            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:org.deegree.tools.metadata.InspireValidator.java

/**
 * parse INSPIRE metadata validator response and print out result onto the console
 * /*www .  ja  va2s .co  m*/
 * @param response
 * @throws IOException
 * @throws IllegalStateException
 */
private void parseServiceResponse(HttpResponse response) throws Exception {
    String s = FileUtils.readTextFile(((BasicHttpResponse) response).getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != 200) {
        outputWriter.println(s);
        outputWriter.println();
        return;
    }
    s = "<html><head></head><body>" + s + "</body></html>";
    BufferedReader br = new BufferedReader(new StringReader(s));

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag) && ((name == HTML.Tag.IMPLIED))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            outputWriter.println(text.toString());
        }
    }
    outputWriter.println("---------------------------------------------------------------------");
    outputWriter.println();
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

public String getTextAtRow(int rowNumber) {

    Element line = getElementMap().getElement(rowNumber);

    int startOffset = line.getStartOffset();
    int endOffset = line.getEndOffset();
    try {/* ww w  . j ava  2  s . co  m*/

        return getText(startOffset, (endOffset - startOffset));

    } catch (BadLocationException e) {

        e.printStackTrace();
        return null;
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

/**
 * Called when the caret position is updated.
 *
 * @param e the caret event/*  www. ja  v a 2  s .  c o  m*/
 */
public void caretUpdate(CaretEvent ce) {

    super.caretUpdate(ce);
    currentPosition = getCaretPosition();

    Element map = getElementMap();
    int row = map.getElementIndex(currentPosition);

    if (currentRow != row) {
        currentRow = row;
        //lineBorder.setRowCount(map.getElementCount());
    }

    Element lineElem = map.getElement(row);
    int col = currentPosition - lineElem.getStartOffset();
    editorPanel.getStatusBar().setCaretPosition(row + 1, col + 1);

    repaint();
}

From source file:org.fife.rsta.ac.js.JavaScriptParser.java

/**
 * {@inheritDoc}/*from   ww w  .j  ava  2s  .c om*/
 */
public ParseResult parse(RSyntaxDocument doc, String style) {

    astRoot = null;
    result.clearNotices();
    // Always spell check all lines, for now.
    Element root = doc.getDefaultRootElement();
    int lineCount = root.getElementCount();
    result.setParsedLines(0, lineCount - 1);

    DocumentReader r = new DocumentReader(doc);
    ErrorCollector errorHandler = new ErrorCollector();
    long start = System.currentTimeMillis();
    try {
        String script = IOUtils.toString(r);
        CompilerEnvirons env = createCompilerEnvironment(errorHandler, langSupport);
        Parser parser = new Parser(env);
        astRoot = parser.parse(new StringReader(MIRTH_SCRIPT_PREFIX + script + MIRTH_SCRIPT_SUFFIX), null, 0);
        env = createCompilerEnvironment(new ErrorCollector(), langSupport);
        astRoot = new Parser(env).parse(script, null, 0);
        long time = System.currentTimeMillis() - start;
        result.setParseTime(time);
    } catch (IOException ioe) { // Never happens
        result.setError(ioe);
        ioe.printStackTrace();
    } catch (RhinoException re) {
        // Shouldn't happen since we're passing an ErrorCollector in
        int line = re.lineNumber();
        // if (line>0) {
        Element elem = root.getElement(line);
        int offs = elem.getStartOffset();
        int len = elem.getEndOffset() - offs - 1;
        String msg = re.details();
        result.addNotice(new DefaultParserNotice(this, msg, line, offs, len));
        // }
    } catch (Exception e) {
        result.setError(e); // catch all
    }

    r.close();

    // Get any parser errors.
    switch (langSupport.getErrorParser()) {
    default:
    case RHINO:
        gatherParserErrorsRhino(errorHandler, root);
        break;
    case JSHINT:
        gatherParserErrorsJsHint(doc);
        break;
    }

    // addNotices(doc);
    support.firePropertyChange(PROPERTY_AST, null, astRoot);

    return result;

}

From source file:plugin.notes.gui.NotesView.java

private void handleBackspace() {
    // TODO: This sucks, clean it up
    Element elem;
    int pos = editor.getCaretPosition();
    StyledDocument htmlDoc = editor.getStyledDocument();

    try {/*from w w w.  ja  va  2s  .c om*/
        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);
    }
}

From source file:plugin.notes.gui.NotesView.java

private void handleEnter() {
    // TODO: this sucks.  clean it up
    Element elem;
    int pos = editor.getCaretPosition();
    ExtendedHTMLDocument htmlDoc = (ExtendedHTMLDocument) editor.getStyledDocument();

    try {//from w  w  w  .ja v a 2  s .  c o  m
        if (ExtendedHTMLEditorKit.checkParentsTag(htmlDoc.getParagraphElement(editor.getCaretPosition()),
                HTML.Tag.UL)
                || ExtendedHTMLEditorKit.checkParentsTag(htmlDoc.getParagraphElement(editor.getCaretPosition()),
                        HTML.Tag.OL)) {
            elem = ExtendedHTMLEditorKit
                    .getListItemParent(htmlDoc.getCharacterElement(editor.getCaretPosition()));

            int so = elem.getStartOffset();
            int eo = elem.getEndOffset();
            char[] temp = editor.getText(so, eo - so).toCharArray();
            boolean content = false;

            for (char aTemp : temp) {
                if (!Character.isWhitespace(aTemp)) {
                    content = true;
                }
            }

            int repos = -1;
            if (content) {
                int end = -1;
                int j = temp.length;

                do {
                    j--;

                    if (Character.isLetterOrDigit(temp[j])) {
                        end = j;
                    }
                } while ((end == -1) && (j >= 0));

                j = end;

                do {
                    j++;

                    if (!Character.isSpaceChar(temp[j])) {
                        repos = j - end - 1;
                    }
                } while ((repos == -1) && (j < temp.length));

                if (repos == -1) {
                    repos = 0;
                }
            }

            if ((elem.getStartOffset() == elem.getEndOffset()) || !content) {
                manageListElement(htmlDoc);
            } else {
                if ((editor.getCaretPosition() + 1) == elem.getEndOffset()) {
                    ExtendedHTMLEditorKit.insertListElement(editor, "");
                    editor.setCaretPosition(pos - repos);
                } else {
                    int caret = editor.getCaretPosition();
                    String tempString = editor.getText(caret, eo - caret);
                    editor.select(caret, eo - 1);
                    editor.replaceSelection("");
                    ExtendedHTMLEditorKit.insertListElement(editor, tempString);

                    Element newLi = ExtendedHTMLEditorKit
                            .getListItemParent(htmlDoc.getCharacterElement(editor.getCaretPosition()));
                    editor.setCaretPosition(newLi.getEndOffset());
                }
            }
        }
    } catch (BadLocationException ble) {
        Logging.errorPrint(ble.getMessage(), ble);
    }
}

From source file:ro.nextreports.designer.querybuilder.SQLViewPanel.java

private void highlightErrorLine(Exception e) {
    removeHighlightErrorLine();/* w  ww .  j a  va  2s.c  o  m*/
    // determine error line number, if any
    String er = e.getMessage();
    // error may contain line number info like " line 12" or " line 12, column 3 " ...
    String regex = ".*\\sline\\s(\\d+)([^\\d].*)*";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(er);
    // first found is line number
    if (m.find()) {
        String lineNo = m.group(1);
        LOG.info("Error on line number : " + lineNo);
        Document ed = sqlEditor.getEditorPanel().getEditorPane().getDocument();
        Element elem = ed.getDefaultRootElement().getElement(Integer.parseInt(lineNo) - 1);
        sqlEditor.getEditorPanel().getEditorPane().setCaretPosition(elem.getStartOffset());
        try {
            errorTag = sqlEditor.getEditorPanel().getEditorPane().getHighlighter()
                    .addHighlight(elem.getStartOffset(), elem.getEndOffset(), errorPainter);
        } catch (BadLocationException e1) {
            LOG.error("Could not highlight sql error line number", e1);
        }
    }
}