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)); }
/** * Creates a new Outline object. * * @param djvuBean the DjVuBean to navigate. * @throws ArrayIndexOutOfBoundsException if the document has less than 2 pages. */ public Outline(final DjVuBean djvuBean) { this.djvuBean = djvuBean; if (djvuBean.getDocument().size() < 2) { throw new ArrayIndexOutOfBoundsException("Can not navigate documents with only one page."); } final MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(final MouseEvent e) { try { clickLocation(e.getX(), e.getY()); } catch (final Throwable exp) { exp.printStackTrace(DjVuOptions.err); System.gc(); } } }; addMouseListener(mouseListener); final Document document = djvuBean.getDocument(); final Bookmark bookmark = (Bookmark) document.getBookmark(); bookmark.setDjVmDir(document.getDjVmDir()); setFirstBookmark(bookmark); final Properties properties = djvuBean.properties; properties.put("addOn.NavPane", "Outline," + properties.getProperty("addOn.NavPane", "None")); djvuBean.addPropertyChangeListener(this); }
public void initMarkers(Place shreds) { SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject); int curOffset = -1; for (PsiLanguageInjectionHost.Shred shred : shreds) { final RangeMarker rangeMarker = myNewDocument.createRangeMarker( shred.getRange().getStartOffset() + shred.getPrefix().length(), shred.getRange().getEndOffset() - shred.getSuffix().length()); final TextRange rangeInsideHost = shred.getRangeInsideHost(); PsiLanguageInjectionHost host = shred.getHost(); RangeMarker origMarker = myOrigDocument.createRangeMarker( rangeInsideHost.shiftRight(host.getTextRange().getStartOffset())); SmartPsiElementPointer<PsiLanguageInjectionHost> elementPointer = smartPointerManager.createSmartPsiElementPointer(host); Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> markers = Trinity.<RangeMarker, RangeMarker, SmartPsiElementPointer>create( origMarker, rangeMarker, elementPointer); myMarkers.add(markers); origMarker.setGreedyToRight(true); rangeMarker.setGreedyToRight(true); if (origMarker.getStartOffset() > curOffset) { origMarker.setGreedyToLeft(true); rangeMarker.setGreedyToLeft(true); } curOffset = origMarker.getEndOffset(); } initGuardedBlocks(shreds); }
private void initGuardedBlocks(Place shreds) { int origOffset = -1; int curOffset = 0; for (PsiLanguageInjectionHost.Shred shred : shreds) { Segment hostRangeMarker = shred.getHostRangeMarker(); int start = shred.getRange().getStartOffset() + shred.getPrefix().length(); int end = shred.getRange().getEndOffset() - shred.getSuffix().length(); if (curOffset < start) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, start); if (curOffset == 0 && shred == shreds.get(0)) guard.setGreedyToLeft(true); String padding = origOffset < 0 ? "" : myOrigDocument.getText().substring(origOffset, hostRangeMarker.getStartOffset()); guard.putUserData(REPLACEMENT_KEY, fixQuotes(padding)); } curOffset = end; origOffset = hostRangeMarker.getEndOffset(); } if (curOffset < myNewDocument.getTextLength()) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, myNewDocument.getTextLength()); guard.setGreedyToRight(true); guard.putUserData(REPLACEMENT_KEY, ""); } }
/** * Determines the preferred span for this view along an axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into >= 0. Typically the view is told to * render into the span that is returned, although there is no guarantee. The parent may * choose to resize or break the view. */ public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: Segment buff = SegmentCache.getSharedSegment(); Document doc = getDocument(); int width; try { FontMetrics fm = getFontMetrics(); doc.getText(0, doc.getLength(), buff); width = Utilities.getTabbedTextWidth(buff, fm, 0, this, 0); if (buff.count > 0) { Component c = getContainer(); firstLineOffset = sun.swing.SwingUtilities2.getLeftSideBearing( (c instanceof JComponent) ? (JComponent) c : null, fm, buff.array[buff.offset]); firstLineOffset = Math.max(0, -firstLineOffset); } else { firstLineOffset = 0; } } catch (BadLocationException bl) { width = 0; } SegmentCache.releaseSharedSegment(buff); return width + firstLineOffset; default: return super.getPreferredSpan(axis); } }
/** * WhiteboardObjectTextJabberImpl constructor. * * @param xml the XML string object to parse. */ public WhiteboardObjectTextJabberImpl(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); InputStream in = new ByteArrayInputStream(xml.getBytes()); Document doc = builder.parse(in); Element e = doc.getDocumentElement(); String elementName = e.getNodeName(); if (elementName.equals("text")) { // we have a text String id = e.getAttribute("id"); double x = Double.parseDouble(e.getAttribute("x")); double y = Double.parseDouble(e.getAttribute("y")); String fill = e.getAttribute("fill"); String fontFamily = e.getAttribute("font-family"); int fontSize = Integer.parseInt(e.getAttribute("font-size")); String text = e.getTextContent(); this.setID(id); this.setWhiteboardPoint(new WhiteboardPoint(x, y)); this.setFontName(fontFamily); this.setFontSize(fontSize); this.setText(text); this.setColor(Color.decode(fill).getRGB()); } } catch (ParserConfigurationException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (IOException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (Exception ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } }
@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); } }
public CaretModelImpl(EditorImpl editor) { myEditor = editor; myLogicalCaret = new LogicalPosition(0, 0); myVisibleCaret = new VisualPosition(0, 0); myCaretInfo = new VerticalInfo(0, 0); myOffset = 0; myVisualLineStart = 0; Document doc = editor.getDocument(); myVisualLineEnd = doc.getLineCount() > 1 ? doc.getLineStartOffset(1) : doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0); DocumentBulkUpdateListener bulkUpdateListener = new DocumentBulkUpdateListener() { @Override public void updateStarted(Document doc) { if (doc != myEditor.getDocument()) return; savedBeforeBulkCaretMarker = doc.createRangeMarker(myOffset, myOffset); } @Override public void updateFinished(Document doc) { if (doc != myEditor.getDocument() || myIsInUpdate) return; if (savedBeforeBulkCaretMarker != null && savedBeforeBulkCaretMarker.isValid()) { moveToOffset(savedBeforeBulkCaretMarker.getStartOffset()); } releaseBulkCaretMarker(); } }; ApplicationManager.getApplication() .getMessageBus() .connect(this) .subscribe(DocumentBulkUpdateListener.TOPIC, bulkUpdateListener); }
/** * Perform the action of the plugin. * * @param document the current document. */ public boolean perform(Document document) throws IOException { // Interact with the user to get the layer tag/ Tag layerTag = getLayerTagFromUser(document); if (layerTag == null) return false; // User cancled. Tag endTag = new Tag(layerTag.getName(), false); // Get the output stream to hold the new document text. PrintWriter out = new PrintWriter(document.getOutput()); // Create a lexical stream to tokenize the old document text. LexicalStream in = new LexicalStream(new SelectedHTMLReader(document.getInput(), out)); for (; ; ) { // Get the next token of the document. Token token = in.next(); if (token == null) break; // Null means we've finished the document. else if (token instanceof Comment) { Comment comment = (Comment) token; if (comment.isSelectionStart()) { out.print(layerTag); } else if (comment.isSelectionEnd()) { out.print(comment); out.print(endTag); continue; // So comment isn't printed twice. } } out.print(token); } out.close(); return true; }
private ProperTextRange offsetToYPosition(int start, int end) { if (myEditorScrollbarTop == -1 || myEditorTargetHeight == -1) { recalcEditorDimensions(); } Document document = myEditor.getDocument(); int startLineNumber = offsetToLine(start, document); int startY; int lineCount; if (myEditorSourceHeight < myEditorTargetHeight) { lineCount = 0; startY = myEditorScrollbarTop + startLineNumber * myEditor.getLineHeight(); } else { lineCount = myEditorSourceHeight / myEditor.getLineHeight(); startY = myEditorScrollbarTop + (int) ((float) startLineNumber / lineCount * myEditorTargetHeight); } int endY; if (document.getLineNumber(start) == document.getLineNumber(end)) { endY = startY; // both offsets are on the same line, no need to recalc Y position } else { int endLineNumber = offsetToLine(end, document); if (myEditorSourceHeight < myEditorTargetHeight) { endY = myEditorScrollbarTop + endLineNumber * myEditor.getLineHeight(); } else { endY = myEditorScrollbarTop + (int) ((float) endLineNumber / lineCount * myEditorTargetHeight); } if (endY < startY) endY = startY; } return new ProperTextRange(startY, endY); }
/** * Creates an Element(or Node in XML in Document d) for single component * * @param x the component for which Element will be created * @param d Where the element will be added * @return the Element(for XML) created from component x */ private Element createCmpEle(component x, Document d) { Element cmp_el = d.createElement("comp"); cmp_el.setAttribute("id", String.valueOf(x.getId())); Element type_el = d.createElement("comp_type_id"); Text type_txt = d.createTextNode(String.valueOf(x.getType().getId())); type_el.appendChild(type_txt); cmp_el.appendChild(type_el); Element pkg_el = d.createElement("pkg_name"); Text pkg_txt = d.createTextNode(x.getType().getType_pkg_name()); pkg_el.appendChild(pkg_txt); cmp_el.appendChild(pkg_el); Element pos_el = d.createElement("position"); Element x_el = d.createElement("x"); Text x_txt = d.createTextNode(String.valueOf(x.getPosition().x)); x_el.appendChild(x_txt); pos_el.appendChild(x_el); Element y_el = d.createElement("y"); Text y_txt = d.createTextNode(String.valueOf(x.getPosition().y)); y_el.appendChild(y_txt); pos_el.appendChild(y_el); cmp_el.appendChild(pos_el); return cmp_el; }
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; }
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(); } }
private void altCommitToOriginal(@NotNull DocumentEvent e) { final PsiFile origPsiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument); String newText = myNewDocument.getText(); // prepare guarded blocks LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>(); int count = 0; for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) { String replacement = o.getUserData(REPLACEMENT_KEY); String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement)); newText = newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset()); replacementMap.put(tempText, replacement); } // run preformat processors final int hostStartOffset = myAltFullRange.getStartOffset(); myEditor.getCaretModel().moveToOffset(hostStartOffset); for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) { newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null); } myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText); // replace temp strings for guarded blocks for (String tempText : replacementMap.keySet()) { int idx = CharArrayUtil.indexOf( myOrigDocument.getCharsSequence(), tempText, hostStartOffset, myAltFullRange.getEndOffset()); myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText)); } // JAVA: fix occasional char literal concatenation fixDocumentQuotes(myOrigDocument, hostStartOffset - 1); fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset()); // reformat PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument); Runnable task = () -> { try { CodeStyleManager.getInstance(myProject) .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); } catch (IncorrectOperationException e1) { // LOG.error(e); } }; DocumentUtil.executeInBulk(myOrigDocument, true, task); PsiElement newInjected = InjectedLanguageManager.getInstance(myProject) .findInjectedElementAt(origPsiFile, hostStartOffset); DocumentWindow documentWindow = newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected); if (documentWindow != null) { myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset())); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } }
private void addText(String str, String styleName, JTextPane pane) { Document doc = pane.getDocument(); int len = doc.getLength(); try { doc.insertString(len, str, pane.getStyle(styleName)); } catch (javax.swing.text.BadLocationException e) { } }
private void updateDocumentFromPropertyValue( final String value, final Document document, final PropertiesFile propertiesFile) { @NonNls String text = value; if (myBackSlashPressed.contains(propertiesFile)) { text += "\\"; } document.replaceString(0, document.getTextLength(), text); }
// </editor-fold> // <editor-fold defaultstate="collapsed" desc="fill pane content"> @Override public void read(Reader in, Object desc) throws IOException { super.read(in, desc); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); parse(root); setCaretPosition(0); }
private void insertString(int pos, String str) { Document doc = getDocument(); try { doc.insertString(pos, str, null); } catch (Exception e) { Debug.error(me + "insertString: Problem while trying to insert at pos\n%s", e.getMessage()); } }
private void paintCaret(Graphics2D g_) { EditorImpl.CaretRectangle[] locations = myEditor.getCaretLocations(true); if (locations == null) return; Graphics2D g = IdeBackgroundUtil.getOriginalGraphics(g_); int lineHeight = myView.getLineHeight(); EditorSettings settings = myEditor.getSettings(); Color caretColor = myEditor.getColorsScheme().getColor(EditorColors.CARET_COLOR); if (caretColor == null) caretColor = new JBColor(CARET_DARK, CARET_LIGHT); g.setColor(caretColor); for (EditorImpl.CaretRectangle location : locations) { int x = location.myPoint.x; int y = location.myPoint.y; Caret caret = location.myCaret; boolean isRtl = location.myIsRtl; if (myEditor.isInsertMode() != settings.isBlockCursor()) { int lineWidth = JBUI.scale(settings.getLineCursorWidth()); g.fillRect(x, y, lineWidth, lineHeight); if (myDocument.getTextLength() > 0 && caret != null && !myView.getLineLayout(caret.getLogicalPosition().line).isLtr()) { g.fillPolygon( new int[] { isRtl ? x + lineWidth : x, isRtl ? x + lineWidth - CARET_DIRECTION_MARK_SIZE : x + CARET_DIRECTION_MARK_SIZE, isRtl ? x + lineWidth : x }, new int[] {y, y, y + CARET_DIRECTION_MARK_SIZE}, 3); } } else { int width = location.myWidth; int startX = Math.max(0, isRtl ? x - width : x); g.fillRect(startX, y, width, lineHeight - 1); if (myDocument.getTextLength() > 0 && caret != null) { int targetVisualColumn = caret.getVisualPosition().column; for (VisualLineFragmentsIterator.Fragment fragment : VisualLineFragmentsIterator.create(myView, caret.getVisualLineStart(), false)) { int startVisualColumn = fragment.getStartVisualColumn(); int endVisualColumn = fragment.getEndVisualColumn(); if (startVisualColumn < targetVisualColumn && endVisualColumn > targetVisualColumn || startVisualColumn == targetVisualColumn && !isRtl || endVisualColumn == targetVisualColumn && isRtl) { g.setColor(ColorUtil.isDark(caretColor) ? CARET_LIGHT : CARET_DARK); fragment.draw( g, startX, y + myView.getAscent(), targetVisualColumn - startVisualColumn - (isRtl ? 1 : 0), targetVisualColumn - startVisualColumn + (isRtl ? 0 : 1)); break; } } } } } }
public void documentChanged(DocumentEvent e) { finishUpdate(); DocumentEventImpl event = (DocumentEventImpl) e; final Document document = myEditor.getDocument(); boolean performSoftWrapAdjustment = e.getNewLength() > 0 // We want to put caret just after the last added symbol // There is a possible case that the user removes text just before the soft wrap. We // want to keep caret // on a visual line with soft wrap start then. || myEditor.getSoftWrapModel().getSoftWrap(e.getOffset()) != null; if (event.isWholeTextReplaced()) { int newLength = document.getTextLength(); if (myOffset == newLength - e.getNewLength() + e.getOldLength() || newLength == 0) { moveToOffset(newLength, performSoftWrapAdjustment); } else { final int line; try { line = event.translateLineViaDiff(myLogicalCaret.line); moveToLogicalPosition( new LogicalPosition(line, myLogicalCaret.column), performSoftWrapAdjustment); } catch (FilesTooBigForDiffException e1) { LOG.info(e1); moveToOffset(0); } } } else { if (document instanceof DocumentEx && ((DocumentEx) document).isInBulkUpdate()) return; int startOffset = e.getOffset(); int oldEndOffset = startOffset + e.getOldLength(); int newOffset = myOffset; if (myOffset > oldEndOffset || myOffset == oldEndOffset && needToShiftWhiteSpaces(e)) { newOffset += e.getNewLength() - e.getOldLength(); } else if (myOffset >= startOffset && myOffset <= oldEndOffset) { newOffset = Math.min(newOffset, startOffset + e.getNewLength()); } newOffset = Math.min(newOffset, document.getTextLength()); // if (newOffset != myOffset) { moveToOffset(newOffset, performSoftWrapAdjustment); // } // else { // moveToVisualPosition(oldPosition); // } } myVisualLineStart = myEditor.logicalPositionToOffset( myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0))); myVisualLineEnd = myEditor.logicalPositionToOffset( myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0))); }
private void addListenerToAllHyperlinkItems(EventListener listener) { final Document doc = myEngine.getDocument(); if (doc != null) { final NodeList nodeList = doc.getElementsByTagName("a"); for (int i = 0; i < nodeList.getLength(); i++) { ((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_CLICK, listener, false); } } }
public void insertUpdate(DocumentEvent e) { Document doc = e.getDocument(); try { prop.set(doc.getText(0, doc.getLength())); } catch (BadLocationException b) { // Once again, no idea what this is supposed to be. // I don't think I like this interface much :-(. System.out.println(b); } }
private boolean isBlankLine(int line, CharSequence chars) { Document document = myDocument; if (document == null) { return true; } int startOffset = document.getLineStartOffset(line); int endOffset = document.getLineEndOffset(line); return CharArrayUtil.shiftForward(chars, startOffset, endOffset, " \t") >= myDocument.getLineEndOffset(line); }
public void actionPerformed(ActionEvent e) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } getEditor().setDocument(new PlainDocument()); getEditor().getDocument().addUndoableEditListener(undoHandler); resetUndoManager(); getFrame().setTitle(resources.getString("Title")); revalidate(); }
// TODO not used public void appendString(String str) { Document doc = getDocument(); try { int start = doc.getLength(); doc.insertString(doc.getLength(), str, null); int end = doc.getLength(); // end = parseLine(start, end, patHistoryBtnStr); } catch (Exception e) { Debug.error(me + "appendString: Problem while trying to append\n%s", e.getMessage()); } }
/** * Emulates pressing <code>Enter</code> at current caret position. * * @param editor target editor * @param project target project * @param shifts two-elements array which is expected to be filled with the following info: 1. The * first element holds added lines number; 2. The second element holds added symbols number; */ private static void emulateEnter( @NotNull final Editor editor, @NotNull Project project, int[] shifts) { final DataContext dataContext = prepareContext(editor.getComponent(), project); int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); SelectionModel selectionModel = editor.getSelectionModel(); int startSelectionOffset = 0; int endSelectionOffset = 0; boolean restoreSelection = selectionModel.hasSelection(); if (restoreSelection) { startSelectionOffset = selectionModel.getSelectionStart(); endSelectionOffset = selectionModel.getSelectionEnd(); selectionModel.removeSelection(); } int textLengthBeforeWrap = document.getTextLength(); int lineCountBeforeWrap = document.getLineCount(); DataManager.getInstance() .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true); CommandProcessor commandProcessor = CommandProcessor.getInstance(); try { Runnable command = new Runnable() { @Override public void run() { EditorActionManager.getInstance() .getActionHandler(IdeActions.ACTION_EDITOR_ENTER) .execute(editor, dataContext); } }; if (commandProcessor.getCurrentCommand() == null) { commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null); } else { command.run(); } } finally { DataManager.getInstance() .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null); } int symbolsDiff = document.getTextLength() - textLengthBeforeWrap; if (restoreSelection) { int newSelectionStart = startSelectionOffset; int newSelectionEnd = endSelectionOffset; if (startSelectionOffset >= caretOffset) { newSelectionStart += symbolsDiff; } if (endSelectionOffset >= caretOffset) { newSelectionEnd += symbolsDiff; } selectionModel.setSelection(newSelectionStart, newSelectionEnd); } shifts[0] = document.getLineCount() - lineCountBeforeWrap; shifts[1] = symbolsDiff; }
private void updateBoard(DocumentEvent e) throws BadLocationException { Document doc = e.getDocument(); int index = (int) doc.getProperty("index"); String valueString = doc.getText(0, doc.getLength()); if (doc.getLength() == 0) valueString = "0"; int value = Integer.parseInt(valueString); gameBoard.changeCellAt(index, value); // gameBoard.out(); if (gameBoard.checkGameOver()) { JOptionPane.showMessageDialog(frame, "NUMBRIX COMPLETED!!!"); } }
private void setStructureViewSelectionFromPropertiesFile(@NotNull Editor propertiesFileEditor) { int line = propertiesFileEditor.getCaretModel().getLogicalPosition().line; Document document = propertiesFileEditor.getDocument(); if (line >= document.getLineCount()) { return; } final String propertyName = getPropertyName(document, line); if (propertyName == null) { return; } setStructureViewSelection(propertyName); }
@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(); }
@Nullable private static String getPropertyName(@NotNull Document document, int line) { int startOffset = document.getLineStartOffset(line); int endOffset = StringUtil.indexOf( document.getCharsSequence(), '=', startOffset, document.getLineEndOffset(line)); if (endOffset <= startOffset) { return null; } String propertyName = document.getCharsSequence().subSequence(startOffset, endOffset).toString().trim(); return propertyName.isEmpty() ? null : propertyName; }