@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
// ---------------------------------------------------- // return last location found public int searchBackward(String lastFindStr) { try { // backward if (isFindAgain) { // otherwise you find same string int foo = lastFindIndex; // begining of word if (foo >= 0) { editor1.setCaretPosition(foo); } // System.out.println("Debug:TextViewer:searchBackward: lastFindIndex: "+foo); } int carPos = editor1.getCaretPosition(); // search backward // todo: should we use the getText(pos,len,segment); String chunk1 = editor1.getDocument().getText(0, carPos); int lastFindIndexTemp = chunk1.lastIndexOf(lastFindStr); if (lastFindIndexTemp == -1) { boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try forward?"); // handle forward if (okPressed) { forwardFindDirection = true; lastFindIndex = searchForward(lastFindStr); } } else { lastFindIndex = lastFindIndexTemp; editor1.setCaretPosition(lastFindIndex); // ready to type in body editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body } } catch (BadLocationException badexception) { String errstr = "TextViewer:searchBackward: " + badexception.getMessage(); warningPopup.display(errstr); return (-1); } return (lastFindIndex); }
/** 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; } }
/** Initialize document with information from the settings. */ private void initDocument(final GuardedDocument<Section> doc) { try { if (this.m_settings != null) { String script = this.m_settings.getScript(); if (script != null && !script.isEmpty()) { doc.setBreakGuarded(true); doc.replace(0, doc.getLength(), this.m_settings.getScript(), null); doc.setBreakGuarded(false); Map<Section, int[]> scriptParts = this.m_settings.getScriptParts(); for (Map.Entry<Section, int[]> scriptPart : scriptParts.entrySet()) { doc.getGuardedSection(scriptPart.getKey()) .setStart(doc.createPosition(scriptPart.getValue()[0])); doc.getGuardedSection(scriptPart.getKey()) .setEnd(doc.createPosition(scriptPart.getValue()[1])); } } } else this.initGuardedSection(doc); // doc.replaceBetween(Section.Imports, Section.JobStart, this.m_settings.getScriptImports()); // doc.replaceBetween(GUARDED_FIELDS, Section.TaskStart, this.m_settings.getScriptFields()); // doc.replaceBetween(Section.TaskStart, GUARDED_TASK_END, this.m_settings.getScriptBody()); // } } catch (BadLocationException e) { throw new IllegalStateException(e.getMessage(), e); } }
/** Clear the log panel. */ public void clearLogPanel() { try { logPane.getDocument().remove(1, logPane.getDocument().getLength() - 1); } catch (BadLocationException e) { LoggerFactory.getLogger(ProcessUIPanel.class).error(e.getMessage()); } }
private static int getNSVisualPosition(EditorPane txt, int pos, int direction) { Element root = txt.getDocument().getDefaultRootElement(); int numLines = root.getElementIndex(txt.getDocument().getLength() - 1) + 1; int line = root.getElementIndex(pos) + 1; int tarLine = direction == SwingConstants.NORTH ? line - 1 : line + 1; try { if (tarLine <= 0) { return 0; } if (tarLine > numLines) { return txt.getDocument().getLength(); } Rectangle curRect = txt.modelToView(pos); Rectangle tarEndRect; if (tarLine < numLines) { tarEndRect = txt.modelToView(txt.getLineStartOffset(tarLine) - 1); } else { tarEndRect = txt.modelToView(txt.getDocument().getLength() - 1); } Debug.log(9, "curRect: " + curRect + ", tarEnd: " + tarEndRect); if (curRect.x > tarEndRect.x) { pos = txt.viewToModel(new Point(tarEndRect.x, tarEndRect.y)); } else { pos = txt.viewToModel(new Point(curRect.x, tarEndRect.y)); } } catch (BadLocationException e) { Debug.error(me + "Problem getting next visual position\n%s", e.getMessage()); } return pos; }
public void caretUpdate(CaretEvent e) { try { setLineCount(textArea.getLineOfOffset(e.getDot()) + 1); } catch (BadLocationException blx) { logger.warn("BadLocationException: " + blx.getMessage()); } }
public void deleteAllMsgs() { try { doc.remove(0, doc.getLength()); MsgBox.setCaretPosition(doc.getLength()); } catch (BadLocationException e) { displayError(e.getMessage()); } }
/** * Highlight a string in a JTextComponent * * @param component Instance of JTextComponent * @param start Start position to be highlighted * @param end End position to be highlighted */ public void highlightFromTo(JTextComponent component, int start, int end) { try { Highlighter hilite = component.getHighlighter(); hilite.addHighlight(start, end, this); } catch (BadLocationException e) { System.out.println(e.getMessage()); System.err.println(e.getMessage()); } }
public void postMaintenanceEventMsg(String msg) { try { doc.insertString(doc.getLength(), msg + "\n", MsgBox.getStyle("Maintenance")); } catch (BadLocationException e) { displayError(e.getMessage()); } MsgBox.setCaretPosition(doc.getLength()); }
/** Perform reformatting of the whole document's text. */ protected void reformat() { FortranReformatter f = new FortranReformatter(getDocument(), FortranCodeStyle.get(getDocument())); try { f.reformat(); } catch (BadLocationException e) { e.printStackTrace(getLog()); fail(e.getMessage()); } }
/** * Save the text contained by the Document in the dataMap set as property. * * @param document */ public void saveDocumentText(Document document) { try { String name = document.getText(0, document.getLength()); Map<URI, Object> dataMap = (Map<URI, Object>) document.getProperty(DATA_MAP_PROPERTY); URI uri = (URI) document.getProperty(URI_PROPERTY); dataMap.put(uri, name); } catch (BadLocationException e) { LoggerFactory.getLogger(GeometryUI.class).error(e.getMessage()); } }
/** Initialize Section.Imports and GUARDED_FIELDS with information from the settings. */ private void initGuardedSection(final GuardedDocument<Section> doc) { try { GuardedSection imports = doc.getGuardedSection(Section.Imports); imports.setText(this.createImportsSection()); GuardedSection fields = doc.getGuardedSection(Section.Fields); fields.setText(this.createFieldsSection()); GuardedSection main = doc.getGuardedSection(Section.MainStart); main.setText(this.createMainSection()); } catch (BadLocationException e) { throw new IllegalStateException(e.getMessage(), e); } }
@Override public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum((int) f.length()); status.add(progress); status.revalidate(); // try to start reading Reader in = new FileReader(f); char[] buff = new char[4096]; int nch; while ((nch = in.read(buff, 0, buff.length)) != -1) { doc.insertString(doc.getLength(), new String(buff, 0, nch), null); progress.setValue(progress.getValue() + nch); } } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater( new Runnable() { public void run() { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + msg, "Error opening file", JOptionPane.ERROR_MESSAGE); } }); } catch (BadLocationException e) { System.err.println(e.getMessage()); } doc.addUndoableEditListener(undoHandler); // we are done... get rid of progressbar status.removeAll(); status.revalidate(); resetUndoManager(); if (elementTreePanel != null) { SwingUtilities.invokeLater( new Runnable() { public void run() { elementTreePanel.setEditor(getEditor()); } }); } }
@Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum(doc.getLength()); status.add(progress); status.revalidate(); // start writing Writer out = new FileWriter(f); Segment text = new Segment(); text.setPartialReturn(true); int charsLeft = doc.getLength(); int offset = 0; while (charsLeft > 0) { doc.getText(offset, Math.min(4096, charsLeft), text); out.write(text.array, text.offset, text.count); charsLeft -= text.count; offset += text.count; progress.setValue(offset); try { Thread.sleep(10); } catch (InterruptedException e) { Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e); } } out.flush(); out.close(); } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater( new Runnable() { public void run() { JOptionPane.showMessageDialog( getFrame(), "Could not save file: " + msg, "Error saving file", JOptionPane.ERROR_MESSAGE); } }); } catch (BadLocationException e) { System.err.println(e.getMessage()); } // we are done... get rid of progressbar status.removeAll(); status.revalidate(); }
@Override public void actionPerformed(ActionEvent e) { int pos = textPane.getCaretPosition(); Document doc = textPane.getDocument(); if (pos < 0) { pos = doc.getLength(); } try { doc.insertString(pos, textToInsert, null); } catch (BadLocationException ex) { log.error("Failed to insert text " + ex.getMessage() + " ... ignore, no rethrow!"); } }
public void actionPerformed(JTextComponent text) { indentationLogic = ((EditorPane) text).getIndentationLogic(); StyledDocument doc = (StyledDocument) text.getDocument(); Element map = doc.getDefaultRootElement(); Caret c = text.getCaret(); int dot = c.getDot(); int mark = c.getMark(); int line1 = map.getElementIndex(dot); if (dot != mark) { int line2 = map.getElementIndex(mark); int begin = Math.min(line1, line2); int end = Math.max(line1, line2); Element elem; try { for (line1 = begin; line1 < end; line1++) { elem = map.getElement(line1); handleDecreaseIndent(line1, elem, doc); } elem = map.getElement(end); int start = elem.getStartOffset(); if (Math.max(c.getDot(), c.getMark()) != start) { handleDecreaseIndent(end, elem, doc); } } catch (BadLocationException ble) { Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage()); UIManager.getLookAndFeel().provideErrorFeedback(text); } } else { Element elem = map.getElement(line1); try { handleDecreaseIndent(line1, elem, doc); } catch (BadLocationException ble) { Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage()); UIManager.getLookAndFeel().provideErrorFeedback(text); } } }
/** * Highlight a string in a JifTextComponent * * @param component Instance of JifTextComponent * @param pattern String to be highlighted */ public void highlight(JTextComponent component, String pattern) { try { Highlighter hilite = component.getHighlighter(); String text = jif.getText(); int pos = 0; while ((pos = text.indexOf(pattern, pos)) >= 0) { hilite.addHighlight(pos, pos + pattern.length(), this); pos += pattern.length(); } } catch (BadLocationException e) { System.out.println(e.getMessage()); System.err.println(e.getMessage()); } }
@Override protected void exportDone(JComponent source, Transferable data, int action) { if (action == TransferHandler.MOVE) { JTextPane aTextPane = (JTextPane) source; int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); Document doc = aTextPane.getDocument(); try { doc.remove(sel_start, sel_end - sel_start); } catch (BadLocationException e) { Debug.error(me + "exportDone: Problem while trying to remove text\n%s", e.getMessage()); } } }
private int parseRange(int start, int end) { if (!showThumbs) { // do not show any thumbnails return end; } try { end = parseLine(start, end, patCaptureBtn); end = parseLine(start, end, patPatternStr); end = parseLine(start, end, patRegionStr); end = parseLine(start, end, patPngStr); } catch (BadLocationException e) { Debug.error(me + "parseRange: Problem while trying to parse line\n%s", e.getMessage()); } return end; }
/** * DOCUMENT ME! * * @param lineNumber DOCUMENT ME! * @return DOCUMENT ME! */ private Element init(int lineNumber) { Document doc = buffer.getDocument(); Element line = doc.getDefaultRootElement().getElement(lineNumber); try { int options = Pattern.DOTALL; String find = PreferenceManager.getString("snr.find", ""); if ((find != null) && !find.equals("")) { if (PreferenceManager.getBoolean("snr.case", false)) { find = find.toLowerCase(); options |= Pattern.CASE_INSENSITIVE; } if (PreferenceManager.getBoolean("snr.whole", false)) { find = "\\b" + find + "\\b"; } int offset = line.getStartOffset(); int length = line.getEndOffset() - offset; if (PreferenceManager.getInt("snr.direction", FORWARD) == FORWARD) { if ((buffer.getSelectionEnd() > line.getStartOffset()) && (buffer.getSelectionEnd() <= line.getEndOffset())) { offset = buffer.getSelectionEnd(); length = line.getEndOffset() - offset; } } else { if ((buffer.getSelectionStart() > line.getStartOffset()) && (buffer.getSelectionStart() <= line.getEndOffset())) { length = buffer.getSelectionStart() - offset; } } String text = doc.getText(offset, length); Pattern pattern = Pattern.compile(find, options); this.matcher = pattern.matcher(text); } } catch (BadLocationException e) { log.error(e.getMessage(), e); } return line; }
// <editor-fold defaultstate="collapsed" desc="content insert append"> public void insertString(String str) { int sel_start = getSelectionStart(); int sel_end = getSelectionEnd(); if (sel_end != sel_start) { try { getDocument().remove(sel_start, sel_end - sel_start); } catch (BadLocationException e) { Debug.error(me + "insertString: Problem while trying to insert\n%s", e.getMessage()); } } int pos = getCaretPosition(); insertString(pos, str); int new_pos = getCaretPosition(); int end = parseRange(pos, new_pos); setCaretPosition(end); }
/** Insert the Saas client call */ @Override protected void insertSaasServiceAccessCode(boolean isInBlock) throws IOException { clearVariablePatterns(); addVariablePattern(J2eeUtil.JSP_NAMES_PAGE, 1); try { String code = ""; code += J2eeUtil.getJspImports( getTargetDocument(), getStartPosition(), getBean().getSaasServicePackageName()); code += J2eeUtil.wrapWithTag(getCustomMethodBody(), getTargetDocument(), getStartPosition()) + "\n"; insert(code, true); } catch (BadLocationException ex) { throw new IOException(ex.getMessage()); } }
/** DOCUMENT ME! */ public void replace() { String replace = PreferenceManager.getString("snr.replace", ""); if ((replace != null) && !replace.equals("")) { int start = buffer.getSelectionStart(); int end = buffer.getSelectionEnd(); if (start != end) { Document doc = buffer.getDocument(); try { doc.remove(start, end - start); doc.insertString(start, replace, null); } catch (BadLocationException e) { log.error(e.getMessage(), e); } } } }
public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum((int) f2.length()); status.add(progress); status.revalidate(); // try to start reading Reader in = new FileReader(f2); char[] buff = new char[4096]; int nch; while ((nch = in.read(buff, 0, buff.length)) != -1) { doc2.insertString(doc2.getLength(), new String(buff, 0, nch), null); progress.setValue(progress.getValue() + nch); } // we are done... get rid of progressbar // doc2.addUndoableEditListener(undoHandler); status.removeAll(); status.revalidate(); // resetUndoManager(); } catch (IOException e) { System.err.println("TextViewer:FileLoader " + e.toString()); } catch (BadLocationException e) { System.err.println("TextViewer:FileLoader " + e.getMessage()); } /* aa if (elementTreePanel != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { elementTreePanel.setEditor(getEditor()); } }); } */ }
// ---------------------- // return last location found public int searchForward(String lastFindStr) { try { // forward // System.out.println("Debug:TextViewer:in searchForward"); int carPos = editor1.getCaretPosition(); // System.out.println("Debug:TextViewer: carPos "+carPos); // int strLength=editor1.getDocument().getEndPosition().getOffset(); int strLength = editor1.getDocument().getLength(); // if ((strLength-carPos)<0) { // System.out.println("Debug:TextViewer: carPos "+carPos); // System.out.println("Debug:TextViewer: strLength "+strLength); // } // search Forward // todo: should we use the getText(pos,len,segment); String chunk1 = editor1.getDocument().getText(carPos, (strLength - carPos)); // offset,length int lastFindIndexTemp = chunk1.indexOf(lastFindStr); if (lastFindIndexTemp == -1) { boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try backward?"); // handle backward if (okPressed) { forwardFindDirection = false; lastFindIndex = searchBackward(lastFindStr); // System.out.println("Debug:TextViewer: lastFindIndex "+lastFindIndex); } } else { lastFindIndex = carPos + lastFindIndexTemp; // System.out.println("Debug:TextViewer: lastFindIndex "+lastFindIndex); editor1.setCaretPosition(lastFindIndex); // ready to type in body editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body } } catch (BadLocationException badexception) { String errstr = "TextViewer:searchForward: " + badexception.getMessage(); warningPopup.display(errstr); return (-1); } return (lastFindIndex); }
@Subscribe public void displayChatMessage(ChatEvent ev) { ReceivedChatMessage fm = createReceivedMessage(ev); formattedMessages.addLast(fm); if (client.getState() == JFrame.ICONIFIED) { messageReceivedWhileIconified = true; } else { setForceFocus(); } DefaultStyledDocument doc = new DefaultStyledDocument(); int offset = 0; try { for (ReceivedChatMessage msg : formattedMessages) { SimpleAttributeSet attrs = new SimpleAttributeSet(); ColorConstants.setForeground(attrs, msg.color); String nick = msg.nickname; String text = msg.ev.getText(); doc.insertString(offset, nick + ": ", attrs); offset += nick.length() + 2; Color textColor = client.getTheme().getTextColor(); if (textColor == null) { attrs = null; } else { attrs = new SimpleAttributeSet(); ColorConstants.setForeground(attrs, client.getTheme().getTextColor()); } doc.insertString(offset, text + "\n", attrs); offset += text.length() + 1; } } catch (BadLocationException e) { logger.error(e.getMessage(), e); //should never happen } messagesPane.setDocument(doc); repaint(); }
@Override public void executeAction(ActionEvent e) { EditorPanel pane = ViewManage.getInstance().getSqlEditor().getEditorPane(); int startLine = pane.getSelectionStartLine(); int endLine = pane.getSelectionEndLine(); int lineCount = pane.getLineCount(); int endOffset = 0; int startOffset = pane.getLineStartOffset(startLine); if (lineCount - 1 == endLine) { endOffset = pane.getLineEndOffset(endLine) - 1; } else { endOffset = pane.getLineEndOffset(endLine); } try { int length = endOffset - startOffset; pane.getDocument().remove(startOffset, length); } catch (BadLocationException e1) { LogProxy.errorLog(e1.getMessage(), e1); } }
public void actionPerformed(JTextComponent text) { indentationLogic = ((EditorPane) text).getIndentationLogic(); boolean indentError = false; Document doc = text.getDocument(); Element map = doc.getDefaultRootElement(); String tabWhitespace = PreferencesUser.getInstance().getTabWhitespace(); Caret c = text.getCaret(); int dot = c.getDot(); int mark = c.getMark(); int dotLine = map.getElementIndex(dot); int markLine = map.getElementIndex(mark); if (dotLine != markLine) { int first = Math.min(dotLine, markLine); int last = Math.max(dotLine, markLine); Element elem; int start; try { for (int i = first; i < last; i++) { elem = map.getElement(i); start = elem.getStartOffset(); doc.insertString(start, tabWhitespace, null); } elem = map.getElement(last); start = elem.getStartOffset(); if (Math.max(c.getDot(), c.getMark()) != start) { doc.insertString(start, tabWhitespace, null); } } catch (BadLocationException ble) { Debug.error(me + "Problem while indenting line\n%s", ble.getMessage()); UIManager.getLookAndFeel().provideErrorFeedback(text); } } else { text.replaceSelection(tabWhitespace); } }
/** * Evidenzia le parole di un testo * * @param jtc JTextComponent da modificare * @param al ArrayList contententi le stringa da evidenziare * @return jtc JTextComponent modificato */ private JTextComponent setHighlightText(JTextComponent jtc, ArrayList<String> al) { try { Highlighter hilite = jtc.getHighlighter(); Document doc = jtc.getDocument(); String text = doc.getText(0, doc.getLength()); int pos = 0; for (int i = 0; i < al.size(); i++) { while ((pos = text.indexOf(al.get(i), pos)) >= 0) { if (text.charAt(pos + al.get(i).length()) == ' ' && text.charAt(pos - 1) == ' ') hilite.addHighlight(pos, pos + al.get(i).length(), highlightPainter[0]); pos += al.get(i).length(); } } } catch (BadLocationException e) { System.out.println("Exception tabTextFile: " + e.getMessage()); return null; } return jtc; }