public void search() { hilit.removeAllHighlights(); String s = entry.getText(); if (s.length() <= 0) { message("Nothing to search"); return; } String content = textArea.getText(); int index = content.indexOf(s, 0); if (index >= 0) { try { int end = index + s.length(); hilit.addHighlight(index, end, painter); textArea.setCaretPosition(end); entry.setBackground(entryBg); message("'" + s + "' found. Press ESC to end search"); } catch (BadLocationException e) { e.printStackTrace(); } } else { entry.setBackground(ERROR_COLOR); message("'" + s + "' found. Press ESC to start a new search"); } }
private void addStyledText(String text, Style style) { try { doc.insertString(doc.getLength(), text, style); } catch (BadLocationException ble) { ble.printStackTrace(); } }
public void mousePressed(MouseEvent evt) { requestFocus(); // Focus events not fired sometimes? setCaretVisible(true); focusedComponent = JEditTextArea.this; if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 && popup != null) { popup.show(painter, evt.getX(), evt.getY()); return; } int line = yToLine(evt.getY()); int offset = xToOffset(line, evt.getX()); int dot = getLineStartOffset(line) + offset; switch (evt.getClickCount()) { case 1: doSingleClick(evt, line, offset, dot); break; case 2: // It uses the bracket matching stuff, so // it can throw a BLE try { doDoubleClick(evt, line, offset, dot); } catch (BadLocationException bl) { bl.printStackTrace(); } break; case 3: doTripleClick(evt, line, offset, dot); break; } }
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(); } }
public void toggleBreakpoint() { if (isEnabled()) { try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; if (position >= 0) { String textToCaret = getDocument().getText(0, position); int lineCount = 0; for (int i = 0; i < textToCaret.length(); i++) { if (textToCaret.charAt(i) == '\n') { lineCount++; } } if (breakpoints.isThereBreakpoint(lineCount)) { breakpoints.removeBreakpoint(lineCount); } else { breakpoints.addBreakpoint(new BreakpointInfo(lineCount)); } } } catch (BadLocationException e) { e.printStackTrace(); } Component parent = GuiUtils.getParentOfType(this, XmlEditorScrollPane.class); if (parent != null) { ((XmlEditorScrollPane) parent).onDocChanged(); } repaint(); } }
/** * Similar to <code>setSelectedText()</code>, but overstrikes the appropriate number of characters * if overwrite mode is enabled. * * @param str The string * @see #setSelectedText(String) * @see #isOverwriteEnabled() */ public void overwriteSetSelectedText(String str) { // Don't overstrike if there is a selection if (!overwrite || selectionStart != selectionEnd) { setSelectedText(str); return; } // Don't overstrike if we're on the end of // the line int caret = getCaretPosition(); int caretLineEnd = getLineEndOffset(getCaretLine()); if (caretLineEnd - caret <= str.length()) { setSelectedText(str); return; } document.beginCompoundEdit(); try { document.remove(caret, str.length()); document.insertString(caret, str, null); } catch (BadLocationException bl) { bl.printStackTrace(); } finally { document.endCompoundEdit(); } }
/** * This method causes a transfer to a component from a clipboard or a DND drop operation. The * Transferable represents the data to be imported into the component. * * @param comp The component to receive the transfer. This argument is provided to enable sharing * of TransferHandlers by multiple components. * @param t The data to import * @return <code>true</code> iff the data was inserted into the component. */ public boolean importData(JComponent comp, Transferable t) { JTextComponent c = (JTextComponent) comp; withinSameComponent = c == exportComp; // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside // the drag location and set shouldRemove to false so that exportDone // knows not to remove any data if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) { shouldRemove = false; return true; } boolean imported = false; DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c); if (importFlavor != null) { try { InputContext ic = c.getInputContext(); if (ic != null) ic.endComposition(); Reader r = importFlavor.getReaderForText(t); handleReaderImport(r, c); imported = true; } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (BadLocationException ble) { ble.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } return imported; }
public void actionPerformed(ActionEvent evt) { JEditTextArea textArea = getTextArea(evt); if(!textArea.isEditable()) { textArea.getToolkit().beep(); return; } if(textArea.getSelectionStart() != textArea.getSelectionEnd()) { textArea.setSelectedText(""); } else { int caret = textArea.getCaretPosition(); if(caret == textArea.getDocumentLength()) { textArea.getToolkit().beep(); return; } try { textArea.getDocument().remove(caret,1); } catch(BadLocationException bl) { bl.printStackTrace(); } } }
/** * Appends a string into the panel window. * * @param stringMessage The string to be appended. */ public void append(String stringMessage) { StyledDocument doc = textPane.getStyledDocument(); try { doc.insertString(doc.getLength(), "[Server: " + stringMessage + "]\n", chatFont); } catch (BadLocationException e) { e.printStackTrace(); } }
/** * Returns the specified substring of the document. * * @param start The start offset * @param len The length of the substring * @return The substring, or null if the offsets are invalid */ public final String getText(int start, int len) { try { return document.getText(start, len); } catch (BadLocationException bl) { bl.printStackTrace(); return null; } }
public String getDocumentText() { try { return getDocument().getText(0, getDocument().getLength()); } catch (BadLocationException e) { e.printStackTrace(); return null; } }
/** * Copies the specified substring of the document into a segment. If the offsets are invalid, the * segment will contain a null string. * * @param start The start offset * @param len The length of the substring * @param segment The segment */ public final void getText(int start, int len, Segment segment) { try { document.getText(start, len, segment); } catch (BadLocationException bl) { bl.printStackTrace(); segment.offset = segment.count = 0; } }
/** Returns the entire text of this text area. */ public String getText() { try { return document.getText(0, document.getLength()); } catch (BadLocationException bl) { bl.printStackTrace(); return null; } }
private void moveCursorToTest(Test test) { if (test instanceof TestCase) { String func = ((TestCase) test).getName(); try { SikuliIDE.getInstance().jumpTo(func); } catch (BadLocationException e) { e.printStackTrace(); } } }
/** * Makes a <code>Segment</code> point to the text in our document between the given positions. * Note that the positions MUST be valid positions in the document. * * @param p0 The first position in the document. * @param p1 The second position in the document. * @param document The document from which you want to get the text. * @param seg The segment in which to load the text. */ private void setSegment(int p0, int p1, Document document, Segment seg) { try { // System.err.println("... in setSharedSegment, p0/p1==" + p0 + "/" + p1); document.getText(p0, p1 - p0, seg); // System.err.println("... in setSharedSegment: s=='" + s + "'; line/numLines==" + line + "/" // + numLines); } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } }
/** Sets the entire text of this text area. */ public void setText(String text) { try { document.beginCompoundEdit(); document.remove(0, document.getLength()); document.insertString(0, text, null); } catch (BadLocationException bl) { bl.printStackTrace(); } finally { document.endCompoundEdit(); } }
/** * Copies the text passed in from the component to the model, replacing any content already there * entirely. */ public void updateModelFromComponent(String newText) { try { doc.remove(0, doc.getLength()); doc.insertString(0, newText, null); componentJustChanged = true; // Let the twin routine know not to run // as a result of this change (no need to // sync component/model twice). } catch (BadLocationException e) { // Shouldn't ever happen since we're replacing the whole lot e.printStackTrace(); } }
public void actionPerformed(ActionEvent e) { JTextComponent textComponent = getTextComponent(e); if (!textComponent.isEditable() || !textComponent.isEnabled()) { return; } try { outdentText(textComponent); } catch (BadLocationException e1) { e1.printStackTrace(); } }
public void execute() { if (!isEditable() || !isEnabled()) { return; } int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); try { if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { String trimmed = selectedText.trim(); if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) { StringBuffer buffer = new StringBuffer(selectedText); int pos = buffer.indexOf("<!--"); buffer.delete(pos, pos + 4); pos = buffer.lastIndexOf("-->"); buffer.delete(pos, pos + 3); replaceSelection(buffer.toString()); } else { String newSelection = "<!--" + selectedText + "-->"; replaceSelection(newSelection); } } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToComment = getText(fromIndex, toIndex - fromIndex + 1); if (textToComment.startsWith("\n")) { textToComment = textToComment.substring(1); fromIndex++; } if (textToComment.endsWith("\n")) { textToComment = textToComment.substring(0, textToComment.length() - 1); toIndex--; } String trimmed = textToComment.trim(); if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) { int pos = textToComment.lastIndexOf("-->"); document.remove(fromIndex + pos, 3); pos = textToComment.indexOf("<!--"); document.remove(fromIndex + pos, 4); } else { document.insertString(Math.min(toIndex + 1, docLen), "-->", null); document.insertString(fromIndex, "<!--", null); } } } catch (BadLocationException e1) { e1.printStackTrace(); } }
private static void insertQuestion(final JTextPane textPane, String str) { Document doc = textPane.getDocument(); try { doc.insertString(doc.getLength(), str, null); final int pos = doc.getLength(); System.out.println(pos); final JTextField field = new JTextField(4) { @Override public Dimension getMaximumSize() { return getPreferredSize(); } }; field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); field.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { try { Rectangle rect = textPane.modelToView(pos); rect.grow(0, 4); rect.setSize(field.getSize()); // System.out.println(rect); // System.out.println(field.getLocation()); textPane.scrollRectToVisible(rect); } catch (BadLocationException ex) { ex.printStackTrace(); } } @Override public void focusLost(FocusEvent e) { /* not needed */ } }); Dimension d = field.getPreferredSize(); int baseline = field.getBaseline(d.width, d.height); field.setAlignmentY(baseline / (float) d.height); SimpleAttributeSet a = new SimpleAttributeSet(); StyleConstants.setLineSpacing(a, 1.5f); textPane.setParagraphAttributes(a, true); textPane.insertComponent(field); doc.insertString(doc.getLength(), "\n", null); } catch (BadLocationException e) { e.printStackTrace(); } }
public void actionPerformed(ActionEvent e) { ETextArea target = (ETextArea) getFocusedComponent(); try { Document document = target.getDocument(); int position = target.getCaretPosition(); String whitespace = target.getIndentationOfLineAtOffset(position); String prefix = "{\n" + whitespace + Parameters.getParameter("indent.string"); String suffix = "\n" + whitespace + "}"; document.insertString(position, prefix + suffix, null); target.setCaretPosition(position + prefix.length()); } catch (BadLocationException ex) { ex.printStackTrace(); } }
/** * Returns a token list for the specified segment of text representing the specified line number. * This method is basically a wrapper for <code>tokenMaker.getTokenList</code> that takes into * account the last token on the previous line to assure token accuracy. * * @param line The line number of <code>text</code> in the document, >= 0. * @return A token list representing the specified line. */ public final Token getTokenListForLine(int line) { Element map = getDefaultRootElement(); Element elem = map.getElement(line); int startOffset = elem.getStartOffset(); // int endOffset = (line==map.getElementCount()-1 ? elem.getEndOffset() - 1: // elem.getEndOffset() - 1); int endOffset = elem.getEndOffset() - 1; // Why always "-1"? try { getText(startOffset, endOffset - startOffset, s); } catch (BadLocationException ble) { ble.printStackTrace(); return null; } int initialTokenType = line == 0 ? Token.NULL : getLastTokenTypeOnLine(line - 1); return tokenMaker.getTokenList(s, initialTokenType, startOffset); }
protected void updateBracketHighlight(int newCaretPosition) { if (newCaretPosition == 0) { bracketPosition = bracketLine = -1; return; } try { int offset = TextUtilities.findMatchingBracket(document, newCaretPosition - 1); if (offset != -1) { bracketLine = getLineOfOffset(offset); bracketPosition = offset - getLineStartOffset(bracketLine); return; } } catch (BadLocationException bl) { bl.printStackTrace(); } bracketLine = bracketPosition = -1; }
public void actionPerformed(ActionEvent evt) { JEditTextArea textArea = getTextArea(evt); int start = textArea.getSelectionStart(); if(start != textArea.getSelectionEnd()) { textArea.setSelectedText(""); } int line = textArea.getCaretLine(); int lineStart = textArea.getLineStartOffset(line); int caret = start - lineStart; String lineText = textArea.getLineText(textArea .getCaretLine()); if(caret == 0) { if(lineStart == 0) { textArea.getToolkit().beep(); return; } caret--; } else { String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); caret = TextUtilities.findWordStart(lineText,caret,noWordSep); } try { textArea.getDocument().remove( caret + lineStart, start - (caret + lineStart)); } catch(BadLocationException bl) { bl.printStackTrace(); } }
/** Reads the text from the model and replaces the text in the component. */ public void updateComponentFromModel() { // We set this flag when a keypress fires a model // change - this ensures that if the model was just // updated from the component, the resulting Document // change doesn't fire a component update (losing // the caret position and looking weird to the user). // Besides - if this flag is set, the two have just // been synced so there's no need to do it again. if (componentJustChanged) { componentJustChanged = false; return; } try { comp.setText(doc.getText(0, doc.getLength())); } catch (BadLocationException e) { // Shouldn't ever happen e.printStackTrace(); } }
/** * Scrolls the help browser to the element with id <code>id</code> * * @param id the id * @return true, if an element with this id was found and scrolling was successful; false, * otherwise */ protected boolean scrollToElementWithId(String id) { Document d = help.getDocument(); if (d instanceof HTMLDocument) { HTMLDocument doc = (HTMLDocument) d; Element element = doc.getElement(id); try { Rectangle r = help.modelToView(element.getStartOffset()); if (r != null) { Rectangle vis = help.getVisibleRect(); r.height = vis.height; help.scrollRectToVisible(r); return true; } } catch (BadLocationException e) { System.err.println( tr("Warning: bad location in HTML document. Exception was: {0}", e.toString())); e.printStackTrace(); } } return false; }
void fix(IDocument document) { getFixes(); if (!Common.isEmptyArray(mFixes)) { try { for (int i = 0; i < mFixes.length; i++) { INILine line = mFixes[i].getLine(); if (line == null) { mFixes[i].setPosition(new Position(0, 0)); } else { mFixes[i].setPosition(line.getParent().getChildPosition(line)); } } Arrays.sort(mFixes, cReversePositionComparator); for (int i = 0; i < mFixes.length; i++) { Position position = mFixes[i].getPosition(); document.replace(position.offset, position.length, mFixes[i].getText()); } } catch (BadLocationException e) { e.printStackTrace(); } } }
public void actionPerformed(ActionEvent e) { JTextComponent textComponent = getTextComponent(e); if (!textComponent.isEditable() || !textComponent.isEnabled()) { return; } try { final int position = getCaretPosition(); final Document document = getDocument(); int docLen = document.getLength(); if (docLen == 0) { return; } int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - fromIndex - 1).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex + 1; String text = getText(fromIndex, toIndex - fromIndex); if (text.startsWith("\n") || toIndex >= docLen) { document.remove(fromIndex, toIndex - fromIndex); } else { document.remove(fromIndex, toIndex - fromIndex + 1); } int newPosition = 0; if (fromIndex > 0) { newPosition = fromIndex + 1; } docLen = document.getLength(); if (newPosition > docLen) { newPosition = getText().lastIndexOf('\n') + 1; } setCaretPosition(newPosition); } catch (BadLocationException e1) { e1.printStackTrace(); } }
public String getCurrentWordBeforeCursor() { Document doc = getDocument(); if (doc == null) return null; int charsToLookBack = 10; int docLength = doc.getLength(); if (docLength < charsToLookBack) charsToLookBack = docLength - 1; String allTextBeforeCaretPosition = null; String oldContent = null; String charsSinceLastWhitespace = null; try { allTextBeforeCaretPosition = doc.getText(0, getCaretPosition()); LastWhitespaceInfo info = findLastWhitespaceLocation(allTextBeforeCaretPosition); if (info.lastWhitespaceLocation > 0 && doc.getLength() > (charsToLookBack - 1)) { // get caret position int caretPosition = getCaretPosition(); // look at last 10 characters int scanBackPosition = caretPosition - charsToLookBack; if (scanBackPosition <= 0) return null; String recentChars = doc.getText(scanBackPosition, charsToLookBack); // if any characters are blanks, get the characters since the last blank int lastWhitespacePosition = recentChars.lastIndexOf(info.lastWhitespaceString); if (lastWhitespacePosition <= 0) return null; charsSinceLastWhitespace = recentChars.substring(lastWhitespacePosition + 1, charsToLookBack); return charsSinceLastWhitespace; } else { return null; } } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
/** * Replaces the selection with the specified text. * * @param selectedText The replacement text for the selection */ public void setSelectedText(String selectedText) { if (!editable) { throw new InternalError("Text component" + " read only"); } document.beginCompoundEdit(); try { if (rectSelect) { Element map = document.getDefaultRootElement(); int start = selectionStart - map.getElement(selectionStartLine).getStartOffset(); int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset(); // Certain rectangles satisfy this condition... if (end < start) { int tmp = end; end = start; start = tmp; } int lastNewline = 0; int currNewline = 0; for (int i = selectionStartLine; i <= selectionEndLine; i++) { Element lineElement = map.getElement(i); int lineStart = lineElement.getStartOffset(); int lineEnd = lineElement.getEndOffset() - 1; int rectStart = Math.min(lineEnd, lineStart + start); document.remove(rectStart, Math.min(lineEnd - rectStart, end - start)); if (selectedText == null) continue; currNewline = selectedText.indexOf('\n', lastNewline); if (currNewline == -1) currNewline = selectedText.length(); document.insertString(rectStart, selectedText.substring(lastNewline, currNewline), null); lastNewline = Math.min(selectedText.length(), currNewline + 1); } if (selectedText != null && currNewline != selectedText.length()) { int offset = map.getElement(selectionEndLine).getEndOffset() - 1; document.insertString(offset, "\n", null); document.insertString(offset + 1, selectedText.substring(currNewline + 1), null); } } else { document.remove(selectionStart, selectionEnd - selectionStart); if (selectedText != null) { document.insertString(selectionStart, selectedText, null); } } } catch (BadLocationException bl) { bl.printStackTrace(); throw new InternalError("Cannot replace" + " selection"); } // No matter what happends... stops us from leaving document // in a bad state finally { document.endCompoundEdit(); } setCaretPosition(selectionEnd); }