Java Code Examples for javax.swing.text.StyledDocument#getText()

The following examples show how to use javax.swing.text.StyledDocument#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: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** return the offset of the first non-whitespace character on the line,
           or -1 when the line does not exist
 */
private static int findLineOffset(StyledDocument doc, int lineNumber) {
    int offset;
    try {
        offset = NbDocument.findLineOffset (doc, lineNumber - 1);
        int offset2 = NbDocument.findLineOffset (doc, lineNumber);
        try {
            String lineStr = doc.getText(offset, offset2 - offset);
            for (int i = 0; i < lineStr.length(); i++) {
                if (!Character.isWhitespace(lineStr.charAt(i))) {
                    offset += i;
                    break;
                }
            }
        } catch (BadLocationException ex) {
            // ignore
        }
    } catch (IndexOutOfBoundsException ioobex) {
        return -1;
    }
    return offset;
}
 
Example 2
Source File: LinkUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    WebTextPane textPane = (WebTextPane) e.getComponent();
    StyledDocument doc = textPane.getStyledDocument();
    Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
    if (!elem.getAttributes().isDefined(URL_ATT_NAME))
        // not a link
        return;

    int len = elem.getEndOffset() - elem.getStartOffset();
    final String url;
    try {
        url = doc.getText(elem.getStartOffset(), len);
    } catch (BadLocationException ex) {
        LOGGER.log(Level.WARNING, "can't get URL", ex);
        return;
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            WebUtils.browseSiteSafely(fixProto(url));
        }
    };
    new Thread(run, "Link Browser").start();
}
 
Example 3
Source File: PositionBounds.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Finds the text contained in this range.
* @return the text
* @exception IOException if any I/O problem occurred during document loading (if that was necessary)
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public String getText() throws BadLocationException, IOException {
    StyledDocument doc = begin.getCloneableEditorSupport().openDocument();
    int p1 = begin.getOffset();
    int p2 = end.getOffset();

    return doc.getText(p1, p2 - p1);
}
 
Example 4
Source File: CfgPropsDocAndTooltipQuery.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    final StyledDocument styDoc = (StyledDocument) document;
    Element lineElement = styDoc.getParagraphElement(caretOffset);
    int lineStartOffset = lineElement.getStartOffset();
    int lineEndOffset = lineElement.getEndOffset();
    try {
        String line = styDoc.getText(lineStartOffset, lineEndOffset - lineStartOffset);
        if (line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
        if (showTooltip) {
            logger.log(FINER, "Tooltip on: {0}", line);
        } else {
            logger.log(FINER, "Documentation on: {0}", line);
        }
        if (!line.contains("#")) {
            //property name extraction from line
            Matcher matcher = PATTERN_PROP_NAME.matcher(line);
            if (matcher.matches()) {
                String propPrefix = matcher.group(1);
                ConfigurationMetadataProperty propMeta = sbs.getPropertyMetadata(propPrefix);
                if (propMeta != null) {
                    if (showTooltip) {
                        final JToolTip toolTip = new JToolTip();
                        toolTip.setTipText(Utils.shortenJavaType(propMeta.getType()));
                        completionResultSet.setToolTip(toolTip);
                    } else {
                        completionResultSet.setDocumentation(new CfgPropCompletionDocumentation(propMeta));
                    }
                }
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
 
Example 5
Source File: BaseTypeTableCellRenderer.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public static String renderText(final TypeInstance instance) {
  final StyledDocument document = new DefaultStyledDocument();
  generateDocument(instance, false, document);
  try {
    return document.getText(0, document.getLength());
  } catch (final BadLocationException exception) {
    CUtilityFunctions.logException(exception);
  }
  return "";
}
 
Example 6
Source File: AbstractTestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Converts DataObject to String.
 */
public static String dataObjectToString(DataObject dataObject) throws IOException, BadLocationException {
    EditorCookie editorCookie = (EditorCookie) dataObject.getCookie(EditorCookie.class);
    
    if (editorCookie != null) {
        StyledDocument document = editorCookie.openDocument();
        if (document != null) {
            return  document.getText(0, document.getLength());
        }
    }
    return null;
}
 
Example 7
Source File: BaseTypeTableCellRenderer.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public static FormattedCharacterBuffer convertDocumentToFormattedCharacterBuffer(
    final StyledDocument document, Font font, int desiredWidth) {
  // The following code calculates the number of rows and the number of columns required for the
  // FormattedCharacterBuffer.
  int width = desiredWidth, height = 0;
  String text = "";
  try {
    text = document.getText(0, document.getLength());
  } catch (BadLocationException e) {
    // Cannot happen.
  }
  String[] chunks = text.split("\n");
  height = chunks.length;
  for (String line : chunks) {
    // The +1 is necessary because we wish to store the newline characters in the
    // FormattedCharacterBuffer.
    width = Math.max(width, line.length() + 1);
  }
  // Height & width is calculated, now create the buffer.
  FormattedCharacterBuffer result = new FormattedCharacterBuffer(height, width);
  int lineindex = 0, columnindex = 0;
  for (int index = 0; index < document.getLength(); ++index) {
    if (text.charAt(index) != '\n') {
      AttributeSet attributes = document.getCharacterElement(index).getAttributes();
      Color foreground =
          document.getForeground(attributes);
      Color background =
          document.getBackground(attributes);

      columnindex++;
      result.setAt(lineindex, columnindex, text.charAt(index), font, foreground, background);
    } else {
      columnindex = 0;
      lineindex++;
    }
  }
  return result;
}
 
Example 8
Source File: WebUrlHyperlinkSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void register(final JTextPane pane) {
    final StyledDocument doc = pane.getStyledDocument();
    String text = "";
    try {
        text = doc.getText(0, doc.getLength());
    } catch (BadLocationException ex) {
        Support.LOG.log(Level.SEVERE, null, ex);
    }
    final int[] boundaries = findBoundaries(text);
    if ((boundaries != null) && (boundaries.length != 0)) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Style defStyle = StyleContext.getDefaultStyleContext()
                                 .getStyle(StyleContext.DEFAULT_STYLE);
                final Style hlStyle = doc.addStyle("regularBlue-url", defStyle);      //NOI18N
                hlStyle.addAttribute(HyperlinkSupport.URL_ATTRIBUTE, new UrlAction());
                StyleConstants.setForeground(hlStyle, UIUtils.getLinkColor());
                StyleConstants.setUnderline(hlStyle, true);
                for (int i = 0; i < boundaries.length; i+=2) {
                    doc.setCharacterAttributes(boundaries[i], boundaries[i + 1] - boundaries[i], hlStyle, true);
                }
                pane.removeMouseListener(getUrlMouseListener());
                pane.addMouseListener(getUrlMouseListener());
            }
        });
    }
}
 
Example 9
Source File: TplEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getDocumentText() {
    String text = "";
    try {
        StyledDocument doc = getDocument();
        if (doc != null) {
            text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
        }
    } catch (BadLocationException e) {
        Logger.getLogger("global").log(Level.WARNING, null, e);
    }
    return text;
}
 
Example 10
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) {
    String t = null;
    if (ep.getCaret() != null) { // #255228
        if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
            t = ep.getSelectedText();
        }
        if (t != null) {
            return t;
        }
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);
    try {
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        if (col + 1 >= lineLen) {
            // do not evaluate when mouse hover behind the end of line (112662)
            return null;
        }
        t = doc.getText(lineStartOffset, lineLen);
        return getExpressionToEvaluate(t, col);
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 11
Source File: ReloadTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRefreshProblem46885 () throws Exception {
    StyledDocument doc = support.openDocument ();
    
    doc.insertString (0, "A text", null);
    support.saveDocument ();
    
    content = "New";
    propL.firePropertyChange (CloneableEditorSupport.Env.PROP_TIME, null, null);
    
    waitAWT ();
    Task reloadTask = support.reloadDocument();
    reloadTask.waitFinished();
    
    String s = doc.getText (0, doc.getLength ());
    assertEquals ("Text has been updated", content, s);
    

    long oldtime = System.currentTimeMillis ();
    Thread.sleep(300);
    err.info("Document modified");
    doc.insertString (0, "A text", null);
    err.info("Document about to save");
    support.saveDocument ();
    err.info("Document saved");
    s = doc.getText (0, doc.getLength ());

    err.info("Current content: " + s);
    content = "NOT TO be loaded";
    propL.firePropertyChange (CloneableEditorSupport.Env.PROP_TIME, null, new Date (oldtime));
    
    waitAWT ();
    
    String s1 = doc.getText (0, doc.getLength ());
    err.info("New content: " + s1);
    assertEquals ("Text has not been updated", s, s1);
}
 
Example 12
Source File: GroovyFilter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent ae) {
    JTextComponent tComp = (JTextComponent) ae.getSource();
    if (tComp.getDocument() instanceof StyledDocument) {
        doc = (StyledDocument) tComp.getDocument();
        try {
            doc.getText(0, doc.getLength(), segment);
        }
        catch (Exception e) {
            // should NEVER reach here
            e.printStackTrace();
        }
        int offset = tComp.getCaretPosition();
        int index = findTabLocation(offset);
        buffer.delete(0, buffer.length());
        buffer.append('\n');
        if (index > -1) {
            for (int i = 0; i < index + 4; i++) {
                buffer.append(' ');
            }
        }
        try {
            doc.insertString(offset, buffer.toString(),
                    doc.getDefaultRootElement().getAttributes());
        }
        catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    }
}
 
Example 13
Source File: HtmlEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getDocumentText() {
    String text = "";
    try {
        StyledDocument doc = getDocument();
        if (doc != null) {
            text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
        }
    } catch (BadLocationException e) {
        Logger.getLogger("global").log(Level.WARNING, null, e);
    }
    return text;
}
 
Example 14
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String getAsString(String file) {
    String result;
    try {
        FileObject testFile = Repository.getDefault().findResource(file);
        DataObject DO = DataObject.find(testFile);
        
        EditorCookie ec=(EditorCookie)(DO.getCookie(EditorCookie.class));
        StyledDocument doc=ec.openDocument();
        result=doc.getText(0, doc.getLength());
        //            result=Common.unify(result);
    } catch (Exception e){
        throw new AssertionFailedErrorException(e);
    }
    return result;
}
 
Example 15
Source File: SearchAction.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private void scrollToSearchResult(ArrayList<String> toHighlight, JTextPane textPane) {
  if (toHighlight.size() == 0) {
    return;
  }
  try {
    StyledDocument logDetailsDocument = textPane.getStyledDocument();
    String text = logDetailsDocument.getText(0, logDetailsDocument.getLength());
    String string = toHighlight.get(0);
    textPane.setCaretPosition(Math.max(text.indexOf(string), 0));
  } catch (BadLocationException e) {
    LOGGER.warn("Cant scroll to content, wrong location: " + e.getMessage());
  }
}
 
Example 16
Source File: ImportDebugger.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static String getText (Line l) throws Exception {
    EditorCookie ec = (EditorCookie) l.getDataObject ().
        getCookie (EditorCookie.class);
    StyledDocument doc = ec.openDocument ();
    if (doc == null) return "";
    int off = NbDocument.findLineOffset (doc, l.getLineNumber ());
    int len = NbDocument.findLineOffset (doc, l.getLineNumber () + 1) - 
        off - 1;
    return doc.getText (off, len);
}
 
Example 17
Source File: JavaTypeCompletionItem.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted java type completion: {0} {1}", new Object[]{elementKind.toString(), name});
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        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('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (isKeyCompletion) {
            // insert and continue completion
            doc.insertString(dotOffset, name.concat("="), null);
        } else {
            // insert and close the code completion box
            doc.insertString(dotOffset, name, null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 18
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getIdentifier (
    StyledDocument doc, 
    JEditorPane ep, 
    int offset
) {
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    )   t = ep.getSelectedText ();
    if (t != null) return t;
    
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem = 
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) return null;
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        lineLen = t.length ();
        int identStart = col;
        while ( (identStart > 0) && 
                (t.charAt (identStart - 1) != '"')
        ) {
            identStart--;
        }
        int identEnd = Math.max (col, 1);
        while ( (identEnd < lineLen) && 
                (t.charAt (identEnd - 1) != '"')
        ) {
            identEnd++;
        }

        if (identStart == identEnd) return null;
        return t.substring (identStart, identEnd - 1);
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 19
Source File: AbstractTestUtil.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Enbles <code>enable = true</code>  or disables <code>enable = false</code> the module.
     */
    public static void switchModule(String codeName, boolean enable) throws Exception {
        String statusFile = "Modules/" + codeName.replace('.', '-') + ".xml";
        ModuleInfo mi = getModuleInfo(codeName);
/*
        FileObject fo = findFileObject(statusFile);
        Document document = XMLUtil.parse(new InputSource(fo.getInputStream()), false, false, null, EntityCatalog.getDefault());
        //Document document = XMLUtil.parse(new InputSource(data.getPrimaryFile().getInputStream()), false, false, null, EntityCatalog.getDefault());
        NodeList list = document.getElementsByTagName("param");
 
        for (int i = 0; i < list.getLength(); i++) {
            Element ele = (Element) list.item(i);
            if (ele.getAttribute("name").equals("enabled")) {
                ele.getFirstChild().setNodeValue(enable ? "true" : "false");
                break;
            }
        }
 
        FileLock lock = fo.lock();
        OutputStream os = fo.getOutputStream(lock);
        XMLUtil.write(document, os, "UTF-8");
        lock.releaseLock();
        os.close();
 */
        
        // module is switched
        if (mi.isEnabled() == enable) {
            return;
        }
        
        DataObject data = findDataObject(statusFile);
        EditorCookie ec = (EditorCookie) data.getCookie(EditorCookie.class);
        StyledDocument doc = ec.openDocument();
        
        // Change parametr enabled
        String stag = "<param name=\"enabled\">";
        String etag = "</param>";
        String enabled = enable ? "true" : "false";
        String result;
        
        String str = doc.getText(0,doc.getLength());
        int sindex = str.indexOf(stag);
        int eindex = str.indexOf(etag, sindex);
        if (sindex > -1 && eindex > sindex) {
            result = str.substring(0, sindex + stag.length()) + enabled + str.substring(eindex);
            //System.err.println(result);
        } else {
            //throw new IllegalStateException("Invalid format of: " + statusFile + ", missing parametr 'enabled'");
            // Probably autoload module
            return;
        }
        
        // prepare synchronization and register listener
        final Waiter waiter = new Waiter();
        final PropertyChangeListener pcl = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("enabled")) {
                    waiter.notifyFinished();
                }
            }
        };
        mi.addPropertyChangeListener(pcl);
        
        // save document
        doc.remove(0,doc.getLength());
        doc.insertString(0,result,null);
        ec.saveDocument();
        
        // wait for enabled propety change and remove listener
        waiter.waitFinished();
        mi.removePropertyChangeListener(pcl);
    }
 
Example 20
Source File: FileObjectCompletionItem.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted file object completion: {0}", FileUtil.getFileDisplayName(fileObj));
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        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('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (fileObj.isRoot()) {
            logger.log(Level.FINER, "Adding filesystem root and continuing completion");
            doc.insertString(dotOffset, getText(), null);
        } else if (fileObj.isFolder()) {
            logger.log(Level.FINER, "Adding folder and continuing completion");
            doc.insertString(dotOffset, getText().concat("/"), null);
        } else {
            logger.log(Level.FINER, "Adding file and finishing completion");
            doc.insertString(dotOffset, getText(), null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}