/** * Returns offset of the given word in src the component * * @param src source component * @param word desired word * @return position offset */ public static int searchInTxComp(JTextComponent src, String word) { int firstOffset = -1; if (word == null || word.isEmpty()) { return -1; } // Look for the word we are given - insensitive searchInTxComp String content = null; try { Document d = src.getDocument(); content = d.getText(0, d.getLength()).toLowerCase(); } catch (BadLocationException e) { // Cannot happen return -1; } word = word.toLowerCase(); int lastIndex = 0; int wordSize = word.length(); while ((lastIndex = content.indexOf(word, lastIndex)) != -1) { int endIndex = lastIndex + wordSize; if (firstOffset == -1) { firstOffset = lastIndex; } lastIndex = endIndex; } return firstOffset; }
public void actionPerformed(ActionEvent evt) { Document document = outputArea.getDocument(); try { document.remove(0, document.getLength()); } catch (BadLocationException ble) { } }
/** * Returns the start of the word at the given offset. * * @param textArea The text area. * @param offs The offset into the text area's content. * @return The start offset of the word. * @throws BadLocationException If <code>offs</code> is invalid. * @see #getWordEnd(RSyntaxTextArea, int) */ public static int getWordStart(RSyntaxTextArea textArea, int offs) throws BadLocationException { Document doc = textArea.getDocument(); Element line = getLineElem(doc, offs); if (line == null) { throw new BadLocationException("No word at " + offs, offs); } int lineStart = line.getStartOffset(); if (offs == lineStart) { // Start of the line. return offs; } int endOffs = Math.min(offs + 1, doc.getLength()); String s = doc.getText(lineStart, endOffs - lineStart); if (s != null && s.length() > 0) { int i = s.length() - 1; char ch = s.charAt(i); if (Character.isWhitespace(ch)) { while (i > 0 && Character.isWhitespace(s.charAt(i - 1))) { i--; } offs = lineStart + i; } else if (Character.isLetterOrDigit(ch)) { while (i > 0 && Character.isLetterOrDigit(s.charAt(i - 1))) { i--; } offs = lineStart + i; } } return offs; }
/** * Attempts to find the next subsequence of the input sequence that matches the pattern. * * <p>This method starts at the beginning of the input sequence or, if a previous invocation of * the method was successful and the matcher has not since been reset, at the first character not * matched by the previous match. * * @return the index of the first occurrence of the search string, starting at the specified * offset, or -1 if no occurrence was found. */ public int findNext() { // Don't match empty strings and don't match if we are at the end of the document. if (findString.length() == 0 || document.getLength() - findString.length() < startIndex) { return -1; } try { int nextMatch = 0; // index of next matching character // Iterate through all segments of the document starting from offset Segment text = new Segment(); text.setPartialReturn(true); int offset = startIndex; int nleft = document.getLength() - startIndex; while (nleft > 0) { document.getText(offset, nleft, text); // Iterate through the characters in the current segment char next = text.first(); for (text.first(); next != Segment.DONE; next = text.next()) { // Check if the current character matches with the next // search character. char current = text.current(); if (current == matchUpperCase[nextMatch] || current == matchLowerCase[nextMatch]) { nextMatch++; // Did we match all search characters? if (nextMatch == matchLowerCase.length) { int foundIndex = text.getIndex() - text.getBeginIndex() + offset - matchLowerCase.length + 1; if (matchType == MatchType.CONTAINS) { return foundIndex; // break; <- never reached } else if (matchType == MatchType.STARTS_WITH) { if (!isWordChar(foundIndex - 1)) { return foundIndex; } } else if (matchType == MatchType.FULL_WORD) { if (!isWordChar(foundIndex - 1) && !isWordChar(foundIndex + matchLowerCase.length)) { return foundIndex; } } nextMatch = 0; } } else { nextMatch = 0; } } // Move forward to the next segment nleft -= text.count; offset += text.count; } return -1; } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } }
@Override public void actionPerformed(PhpModule phpModule) { // Check CakePHP project if (!CakePhpUtils.isCakePHP(phpModule)) { return; } // get EditorCookie Lookup lookup = Utilities.actionsGlobalContext(); EditorCookie context = lookup.lookup(EditorCookie.class); if (context == null) { return; } Document doc = context.getDocument(); if (doc == null) { return; } reformat(doc); // Change line feed if (!BaseDocument.LS_LF.equals(doc.getProperty(BaseDocument.READ_LINE_SEPARATOR_PROP))) { doc.putProperty(BaseDocument.READ_LINE_SEPARATOR_PROP, BaseDocument.LS_LF); } }
@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
void appendOutput(final String line) { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater( new Runnable() { public void run() { appendOutput(line); } }); return; } if (!isShowing()) { // ignore request, dialog is closed return; } // Can now accept user input outputArea.setEditable(true); Document doc = outputArea.getDocument(); if (doc != null) { try { doc.insertString(doc.getLength(), line + "\n", null); // NOI18N } catch (BadLocationException e) { } } }
@Override public void run(Result result, SchedulerEvent event) { try { ALGParserResult sjResult = (ALGParserResult) result; List<ParseException> syntaxErrors = sjResult.getJavaParser().syntaxErrors; Document document = result.getSnapshot().getSource().getDocument(false); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (ParseException syntaxError : syntaxErrors) { Token token = syntaxError.currentToken; int start = NbDocument.findLineOffset((StyledDocument) document, token.beginLine - 1) + token.beginColumn - 1; int end = NbDocument.findLineOffset((StyledDocument) document, token.endLine - 1) + token.endColumn; ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage(), document, document.createPosition(start), document.createPosition(end)); errors.add(errorDescription); } HintsController.setErrors(document, "simple-java", errors); } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace(ex1); } }
/** * Parse the passed text string for style names and add the styled text to the text pane's * document. * * @param text Text to parse * @param pane Pane to modify. The pane also provides the style names */ public static final void parse(String text, JTextPane pane) { try { Matcher match = TEXT_PATTERN.matcher(text); Document doc = pane.getDocument(); int textStart = 0; // Start of current text area Style style = null; // Style for next set of text while (match.find()) { // Save the current text first String styledText = text.substring(textStart, match.start()); textStart = match.end() + 1; if (style != null && styledText != null) { doc.insertString(doc.getLength(), styledText, style); } // endif // Get the next style style = pane.getStyle(match.group(1)); if (style == null) throw new IllegalArgumentException("Unknown style: '" + match.group(1)); } // endwhile // Add the last of the text doc.insertString(doc.getLength(), text.substring(textStart), null); } catch (BadLocationException e) { e.printStackTrace(); throw new IllegalStateException( "This should not happen since I always use the document to " + "determine the location to write. It might be due to synchronization problems though"); } }
public void keyPressed(KeyEvent event) { try { switch (event.getKeyCode()) { case KeyEvent.VK_ENTER: try { processInput.write(getLastLine(textComponent.getDocument()).getBytes()); processInput.flush(); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); } break; case KeyEvent.VK_BACK_SPACE: Document doc = textComponent.getDocument(); if (!"\n".equals(getLastChar(doc))) { // NOI18N startOffset = doc.getLength() - 1; doc.remove(startOffset, 1); } break; } } catch (BadLocationException ex) { } // be sure caret position is adjusted in the case user move it from the end of doc textComponent.setCaretPosition(textComponent.getDocument().getLength()); startOffset = textComponent.getDocument().getLength(); }
/** * Накат истории вперед * * @param target Запись истории * @param textPane Текст для которого применяется историческое изменение */ public static void applyForward(UndoTextAction target, JTextComponent textPane) { if (target == null) throw new IllegalArgumentException("target==null"); if (textPane == null) throw new IllegalArgumentException("textPane==null"); try { javax.swing.text.Document doc = textPane.getDocument(); int offset = target.getOffset(); String changes = target.getChangedText(); if (UndoTextAction.Action.Added.equals(target.getAction())) { doc.insertString(offset, changes, null); int L = doc.getLength(); int P = offset + changes.length(); if (P > L) P = L; textPane.setCaretPosition(P); } else if (UndoTextAction.Action.Deleted.equals(target.getAction())) { doc.remove(offset, changes.length()); textPane.setCaretPosition(offset); } } catch (BadLocationException ex) { Logger.getLogger(UndoTextAction.class.getName()).log(Level.SEVERE, null, ex); } }
public void execute() { if (!isEditable() || !isEnabled()) { return; } try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { final int selectionEnd = getSelectionEnd(); document.insertString(selectionEnd, selectedText, null); select(selectionEnd, selectionEnd + selectedText.length()); } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1); if (!textToDuplicate.startsWith("\n")) { textToDuplicate = "\n" + textToDuplicate; } if (textToDuplicate.endsWith("\n")) { textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1); } document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null); setCaretPosition(position + textToDuplicate.length()); } } catch (BadLocationException e1) { e1.printStackTrace(); } }
/** * Replaces the currently selected content with new content represented by the given StyledText. * If there is no selection this amounts to an insert of the given text. If there is no * replacement text this amounts to a removal of the current selection. The replacement text will * have the attributes currently defined for input at the point of insertion. If the document is * not editable, beep and return * * @param content the content to replace the selection with * @see StyledText#insert */ public static void replaceSelection(Word word, StyledText content) { Document doc = word.workspace.getDocument(); String text; Caret caret = word.workspace.getCaret(); int insertPos = 0; int i; int contentSize; if (doc != null) { try { int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); // if there is any selection if (p0 != p1) { doc.remove(p0, p1 - p0); } // insert the content if (content != null) { content.insert(doc, p0); } } catch (BadLocationException ble) { javax.swing.UIManager.getLookAndFeel().provideErrorFeedback(word.workspace); return; } } }
/** The constructor. */ public StylePanelFig() { super("Fig Appearance"); initChoices(); Document bboxDoc = bboxField.getDocument(); bboxDoc.addDocumentListener(this); bboxField.addKeyListener(this); bboxField.addFocusListener(this); fillField.addItemListener(this); lineField.addItemListener(this); fillField.setRenderer(new ColorRenderer()); lineField.setRenderer(new ColorRenderer()); bboxLabel.setLabelFor(bboxField); add(bboxLabel); add(bboxField); fillLabel.setLabelFor(fillField); add(fillLabel); add(fillField); lineLabel.setLabelFor(lineField); add(lineLabel); add(lineField); }
public void print(final String line) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { ConsoleTab.this.print(line); } }); return; } Document document = this.console.getDocument(); JScrollBar scrollBar = getVerticalScrollBar(); boolean shouldScroll = false; if (getViewport().getView() == this.console) { shouldScroll = scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4 > scrollBar.getMaximum(); } try { document.insertString(document.getLength(), line, null); } catch (BadLocationException localBadLocationException) { } if (shouldScroll) scrollBar.setValue(2147483647); }
public void addToUses(String strType, boolean bTemplate, boolean bProgram) { if (isTypeUsed(strType)) { return; } Document doc = _gsEditor.getEditor().getDocument(); int iPos = findUsesInsertionPosition(bProgram); int iIndex = doc.getDefaultRootElement().getElementIndex(iPos); int iInsertionPt; String strUsesStmt = Keyword.KW_uses + " " + strType; if (bTemplate) { strUsesStmt = "<% " + strUsesStmt + " %>"; } strUsesStmt += "\n"; if (iPos == 0) { iInsertionPt = iPos; if (!bTemplate) { strUsesStmt = strUsesStmt + "\n"; } } else { iInsertionPt = doc.getDefaultRootElement().getElement(iIndex).getEndOffset(); } try { doc.insertString(iInsertionPt, strUsesStmt, null); } catch (BadLocationException e) { throw new RuntimeException(e); } }
/** * Attach a {@link Document} to enable line number tracking when editing. The position to track is * before the first non-whitespace character on the line. Edits happening before that position * will cause the line number to update accordingly. Multiple {@link #startTracking} calls will * replace the tracked document. Whoever wants a tracked line should track it and add itself as * listener if necessary. ({@link LineHighlight}, {@link LineBreakpoint}) * * @param doc the {@link Document} to use for line number tracking */ public synchronized void startTracking(Document doc) { // System.out.println("tracking: " + this); if (doc == null) { return; // null arg } if (doc == this.doc) { return; // already tracking that doc } try { Element line = doc.getDefaultRootElement().getElement(lineIdx); if (line == null) { return; // line doesn't exist } String lineText = doc.getText(line.getStartOffset(), line.getEndOffset() - line.getStartOffset()); // set tracking position at (=before) first non-white space character on line pos = doc.createPosition(line.getStartOffset() + nonWhiteSpaceOffset(lineText)); this.doc = doc; doc.addDocumentListener(this); } catch (BadLocationException ex) { Logger.getLogger(LineID.class.getName()).log(Level.SEVERE, null, ex); pos = null; this.doc = null; } }
/** @param singleFormatter */ protected void fillWithObjFormatter(final DataObjDataFieldFormatIFace singleFormatter) { ignoreFmtChange = true; try { formatEditor.setText(""); if (singleFormatter == null) { return; } Document doc = formatEditor.getDocument(); DataObjDataField[] fields = singleFormatter.getFields(); if (fields == null) { return; } for (DataObjDataField field : fields) { try { doc.insertString(doc.getLength(), field.getSep(), null); // System.err.println("["+field.getName()+"]["+field.getSep()+"]["+field.getFormat()+"]["+field.toString()+"]"); insertFieldIntoTextEditor(new DataObjDataFieldWrapper(field)); } catch (BadLocationException ble) { } } } finally { ignoreFmtChange = false; } }
public void highlight(JTextComponent textComp, String pattern) { if (pattern.isEmpty()) { textComp.getHighlighter().removeAllHighlights(); return; } try { Highlighter hilite = textComp.getHighlighter(); hilite.removeAllHighlights(); javax.swing.text.Document doc = textComp.getDocument(); String text = doc.getText(0, doc.getLength()); int pos = 0; if (!check.isSelected()) { pattern = pattern.toLowerCase(); text = text.toLowerCase(); } // Search for pattern while ((pos = text.indexOf(pattern, pos)) >= 0) { // Create highlighter using private painter and apply around // pattern hilite.addHighlight(pos, pos + pattern.length(), painter); pos += pattern.length(); } } catch (Exception e) { new the.bytecode.club.bytecodeviewer.api.ExceptionUI(e); } }
/** return indent for nearest non-ws line */ private static int getIndent(final Document document, int elementIndex) throws BadLocationException { Element rootElement = document.getDefaultRootElement(); boolean isTextWSOnly; int eso = rootElement.getStartOffset(); boolean extendIndent = false; do { if (elementIndex < 1) { break; } Element element = rootElement.getElement(elementIndex--); eso = element.getStartOffset(); String elementText = document.getText(eso, element.getEndOffset() - eso); isTextWSOnly = elementText.matches("\\s+"); // NOI18N if (!isTextWSOnly) { final String ett = elementText.trim(); extendIndent = ett.endsWith("{") || ett.endsWith("["); // NOI18N } } while (isTextWSOnly); int indent = IndentUtils.lineIndent(document, eso); if (extendIndent) { indent += IndentUtils.tabSize(document); } return indent; }
/** Replaces the current word token */ public void replaceWord(String newWord) { if (currentWordPos != -1) { try { /* ORIGINAL document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, null); */ // Howard's Version for Ekit Element element = ((javax.swing.text.html.HTMLDocument) document).getCharacterElement(currentWordPos); AttributeSet attribs = element.getAttributes(); document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, attribs); // End Howard's Version // Need to reset the segment document.getText(0, document.getLength(), text); } catch (BadLocationException ex) { throw new RuntimeException(ex.getMessage()); } // Position after the newly replaced word(s) // Position after the newly replaced word(s) first = true; currentWordPos = getNextWordStart(text, currentWordPos + newWord.length()); if (currentWordPos != -1) { currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd); sentanceIterator.setText(text); sentanceIterator.following(currentWordPos); } else moreTokens = false; } }
/** * Returns the end of the word at the given offset. * * @param textArea The text area. * @param offs The offset into the text area's content. * @return The end offset of the word. * @throws BadLocationException If <code>offs</code> is invalid. * @see #getWordStart(RSyntaxTextArea, int) */ public static int getWordEnd(RSyntaxTextArea textArea, int offs) throws BadLocationException { Document doc = textArea.getDocument(); int endOffs = textArea.getLineEndOffsetOfCurrentLine(); int lineEnd = Math.min(endOffs, doc.getLength()); if (offs == lineEnd) { // End of the line. return offs; } String s = doc.getText(offs, lineEnd - offs - 1); if (s != null && s.length() > 0) { // Should always be true int i = 0; int count = s.length(); char ch = s.charAt(i); if (Character.isWhitespace(ch)) { while (i < count && Character.isWhitespace(s.charAt(i++))) ; } else if (Character.isLetterOrDigit(ch)) { while (i < count && Character.isLetterOrDigit(s.charAt(i++))) ; } else { i = 2; } offs += i - 1; } return offs; }
private static OffsetsBag getBag(Document doc) { OffsetsBag bag = (OffsetsBag) doc.getProperty(RemoveSurroundingCodePanel.class); if (bag == null) { doc.putProperty(RemoveSurroundingCodePanel.class, bag = new OffsetsBag(doc)); } return bag; }
private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic) throws BadLocationException { Element map = document.getDefaultRootElement(); int endPos = map.getElement(lineNum).getEndOffset(); indentationLogic.reset(); indentationLogic.addText(document.getText(0, endPos)); }
private boolean replaceWithImage(int startOff, int endOff, Pattern ptn) throws BadLocationException { Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); JComponent comp = null; if (ptn == patPatternStr || ptn == patPngStr) { if (pref.getPrefMoreImageThumbs()) { comp = EditorPatternButton.createFromString(this, imgStr, null); } else { comp = EditorPatternLabel.labelFromString(this, imgStr); } } else if (ptn == patRegionStr) { if (pref.getPrefMoreImageThumbs()) { comp = EditorRegionButton.createFromString(this, imgStr); } else { comp = EditorRegionLabel.labelFromString(this, imgStr); } } else if (ptn == patCaptureBtn) { comp = EditorPatternLabel.labelFromString(this, ""); } if (comp != null) { this.select(startOff, endOff); this.insertComponent(comp); return true; } return false; }
private Collection<Token> performTest(String sourceCode, final int offset, boolean[] wasResolved) throws Exception { FileObject root = makeScratchDir(this); FileObject sourceDir = root.createFolder("src"); FileObject buildDir = root.createFolder("build"); FileObject cacheDir = root.createFolder("cache"); source = sourceDir.createFolder("test").createData("Test.java"); writeIntoFile(source, sourceCode); SourceUtilsTestUtil.prepareTest(sourceDir, buildDir, cacheDir, new FileObject[0]); DataObject od = DataObject.find(source); EditorCookie ec = od.getCookie(EditorCookie.class); Document doc = ec.openDocument(); doc.putProperty(Language.class, JavaTokenId.language()); doc.putProperty("mimeType", "text/x-java"); return InstantRenamePerformer.computeChangePoints( SourceUtilsTestUtil.getCompilationInfo(JavaSource.forFileObject(source), Phase.RESOLVED), offset, wasResolved); }
/** * Updates the AttributedCharacterIterator by invoking <code>formatToCharacterIterator</code> on * the <code>Format</code>. If this is successful, <code>updateMask(AttributedCharacterIterator) * </code> is then invoked to update the internal bitmask. */ void updateMask() { if (getFormat() != null) { Document doc = getFormattedTextField().getDocument(); validMask = false; if (doc != null) { try { string = doc.getText(0, doc.getLength()); } catch (BadLocationException ble) { string = null; } if (string != null) { try { Object value = stringToValue(string); AttributedCharacterIterator iterator = getFormat().formatToCharacterIterator(value); updateMask(iterator); } catch (ParseException pe) { } catch (IllegalArgumentException iae) { } catch (NullPointerException npe) { } } } } }
private void logResult(JEditorPane e, String s) { Document doc = e.getDocument(); try { doc.insertString(doc.getLength(), s, null); } catch (BadLocationException e1) { /* empty */ } }
/* * To prevent memory from being used up you can control the number of * lines to display in the console * * This number can be dynamically changed, but the console will only * be updated the next time the Document is updated. */ public void setMessageLines(final int lines) { if (limitLinesListener != null) { document.removeDocumentListener(limitLinesListener); } limitLinesListener = new LimitLinesDocumentListener(lines, isAppend); document.addDocumentListener(limitLinesListener); }
/** * @param document * @return True if given document is a dtbook. */ private static boolean isDtBook(final Document document) { try { return document.getText(0, document.getLength()).contains("<dtbook"); } catch (final BadLocationException e) { e.printStackTrace(); return false; } }