Java Code Examples for javax.swing.text.Document#createPosition()

The following examples show how to use javax.swing.text.Document#createPosition() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   File: WeakPositions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets a <code>Position</code> in the document at the given offset. The 
 * position is automatically updated when the document's contents is modified.
 * The <code>Position</code> does not reference the document in anyway that
 * would prevent the document from being garbage collected.
 * 
 * @param doc The document to get a position in.
 * @param offset The initial offset of the position.
 * 
 * @return A <code>Position</code> inside the document.
 * @throws BadLocationException If the offset is not valid for the document.
 */
public static Position get(Document doc, int offset) throws BadLocationException {
    // Check that the offset is valid. This should excercise any rule imposed by
    // the document on its positions.
    doc.createPosition(offset);
    
    synchronized (OGLS) {
        OffsetGapList<WeakP> ogl = OGLS.get(doc);

        if (ogl == null) {
            ogl = new OffsetGapList<WeakPositions.WeakP>();
            OGLS.put(doc, ogl);
            doc.addDocumentListener(WeakListeners.document(documentsTracker, doc));
        }
        
        int index = ogl.findElementIndex(offset);
        WeakP pos = index >= 0 ? ogl.get(index) : null;

        if (pos == null) {
            pos = new WeakP(offset);
            ogl.add(pos);
        }
        
        return pos;
    }
}
 
Example 2
Source Project: consulo   File: HtmlPanel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getSelectedText() {
  Document doc = getDocument();
  int start = getSelectionStart();
  int end = getSelectionEnd();

  try {
    Position p0 = doc.createPosition(start);
    Position p1 = doc.createPosition(end);
    StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset());
    getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset());

    return StringHtmlUtil.removeHtmlTags(sw.toString());
  }
  catch (BadLocationException | IOException ignored) {
  }
  return super.getSelectedText();
}
 
Example 3
Source Project: netbeans   File: DefaultIndentEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int indentLine(Document doc, int offset) {
    Indent indent = Indent.get(doc);
    indent.lock();
    try {
        if (doc instanceof BaseDocument) {
            ((BaseDocument) doc).atomicLock();
        }
        try {
            Position pos = doc.createPosition(offset);
            indent.reindent(offset);
            return pos.getOffset();
        } catch (BadLocationException ble) {
            return offset;
        } finally {
            if (doc instanceof BaseDocument) {
                ((BaseDocument) doc).atomicUnlock();
            }
        }
    } finally {
        indent.unlock();
    }
}
 
Example 4
Source Project: netbeans   File: PlainDocumentTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCuriosities() throws Exception {
    // Test position at offset 0 does not move after insert
    Document doc = new PlainDocument();
    doc.insertString(0, "test", null);
    Position pos = doc.createPosition(0);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "a", null);
    assertEquals(0, pos.getOffset());
    
    // Test there is an extra newline above doc.getLength()
    assertEquals("\n", doc.getText(doc.getLength(), 1));
    assertEquals("atest\n", doc.getText(0, doc.getLength() + 1));
    
    // Test the last line element contains the extra newline
    Element lineElem = doc.getDefaultRootElement().getElement(0);
    assertEquals(0, lineElem.getStartOffset());
    assertEquals(doc.getLength() + 1, lineElem.getEndOffset());

    // Test that once position gets to zero it won't go anywhere else (unless undo performed)
    pos = doc.createPosition(1);
    doc.remove(0, 1);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "b", null);
    assertEquals(0, pos.getOffset());
}
 
Example 5
Source Project: littleluck   File: SnippetHighlighter.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * Adds a highlight to the view.  Returns a tag that can be used 
    * to refer to the highlight.
    *
    * @param p0   the start offset of the range to highlight >= 0
    * @param p1   the end offset of the range to highlight >= p0
    * @param p    the painter to use to actually render the highlight
    * @return     an object that can be used as a tag
    *   to refer to the highlight
    * @exception BadLocationException if the specified location is invalid
    */
   public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p) throws BadLocationException {
Document doc = component.getDocument();
HighlightInfo i = (getDrawsLayeredHighlights() &&
		   (p instanceof LayeredHighlighter.LayerPainter)) ?
                  new LayeredHighlightInfo() : new HighlightInfo();
i.painter = p;
i.p0 = doc.createPosition(p0);
i.p1 = doc.createPosition(p1);
       // For snippets, we want to make sure selection is layered ON TOP
       // since we add transparency to the selection color;  so rather
       // than append the highlight, we insert it in the front.
highlights.insertElementAt(i, 0);
       safeDamageRange(p0, p1);
       return i;
   }
 
Example 6
Source Project: netbeans   File: UtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
private void doTestDefaultIndent(String code, String insertCode, String expectedResult) throws Exception {
    clearWorkDir();
    FileObject wd = FileUtil.toFileObject(getWorkDir());
    FileObject sourceFile1 = wd.createData("Test1.txt");
    EditorCookie ec = sourceFile1.getLookup().lookup(EditorCookie.class);
    Document doc = ec.openDocument();
    int insertPos = code.indexOf("|");
    code = code.replace("|", "");
    doc.insertString(0, code, null);
    javax.swing.text.Position caret = doc.createPosition(insertPos);
    doc.insertString(insertPos, insertCode, null);
    List<TextEdit> edits = Utils.computeDefaultOnTypeIndent(doc, insertPos, Utils.createPosition(doc, insertPos), insertCode);
    Utils.applyEditsNoLock(doc, edits);
    int expectedPos = expectedResult.indexOf("|");
    expectedResult = expectedResult.replace("|", "");
    assertEquals(expectedResult, doc.getText(0, doc.getLength()));
    assertEquals(expectedPos, caret.getOffset());
    LifecycleManager.getDefault().saveAll();
}
 
Example 7
public void reindent() throws BadLocationException {
    Document doc = context.document();
    int startOffset = context.startOffset();
    int endOffset = context.endOffset();
    
    pushFormattingContextDocument(doc);
    try {
        // Original formatter does not have reindentation of multiple lines
        // so reformat start line and continue for each line.
        Element lineRootElem = lineRootElement(doc);
        Position endPos = doc.createPosition(endOffset);
        do {
            startOffset = formatter.indentLine(doc, startOffset);
            int startLineIndex = lineRootElem.getElementIndex(startOffset) + 1;
            if (startLineIndex >= lineRootElem.getElementCount())
                break;
            Element lineElem = lineRootElem.getElement(startLineIndex);
            startOffset = lineElem.getStartOffset(); // Move to next line
        } while (startOffset < endPos.getOffset());
    } finally {
        popFormattingContextDocument(doc);
    }
}
 
Example 8
public void actionPerformed(ActionEvent e) {
	JTextComponent tc = (JTextComponent) getInvoker();

	String sel = tc.getSelectedText();

	if (e.getSource() == cutItem) {
		tc.cut();
	} else if (e.getSource() == copyItem) {
		tc.copy();
	} else if (e.getSource() == pasteItem) {
		tc.paste();
	} else if (e.getSource() == selectAllItem) {
		tc.selectAll();
	} else if (e.getSource() == deleteItem) {
		Document doc = tc.getDocument();
		int start = tc.getSelectionStart();
		int end = tc.getSelectionEnd();

		try {
			Position p0 = doc.createPosition(start);
			Position p1 = doc.createPosition(end);

			if ((p0 != null) && (p1 != null)
					&& (p0.getOffset() != p1.getOffset())) {
				doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
			}
		} catch (BadLocationException be) {
		}
	}
}
 
Example 9
Source Project: netbeans   File: Fold.java    License: Apache License 2.0 5 votes vote down vote up
void setStartOffset(Document doc, int startOffset)
throws BadLocationException {
    if (isRootFold()) {
        throw new IllegalStateException("Cannot set endOffset of root fold"); // NOI18N
    } else {
        this.startPos = doc.createPosition(startOffset);
    }
}
 
Example 10
Source Project: netbeans   File: FoldView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JComponent getToolTip(double x, double y, Shape allocation) {
    Container container = getContainer();
    if (container instanceof JEditorPane) {
        JEditorPane editorPane = (JEditorPane) getContainer();
        JEditorPane tooltipPane = new JEditorPane();
        EditorKit kit = editorPane.getEditorKit();
        Document doc = getDocument();
        if (kit != null && doc != null) {
            Element lineRootElement = doc.getDefaultRootElement();
            tooltipPane.putClientProperty(FoldViewFactory.DISPLAY_ALL_FOLDS_EXPANDED_PROPERTY, true);
            try {
                // Start-offset of the fold => line start => position
                int lineIndex = lineRootElement.getElementIndex(fold.getStartOffset());
                Position pos = doc.createPosition(
                        lineRootElement.getElement(lineIndex).getStartOffset());
                // DocumentView.START_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-start-position", pos); // NOI18N
                // End-offset of the fold => line end => position
                lineIndex = lineRootElement.getElementIndex(fold.getEndOffset());
                pos = doc.createPosition(lineRootElement.getElement(lineIndex).getEndOffset());
                // DocumentView.END_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-end-position", pos); // NOI18N
                tooltipPane.putClientProperty("document-view-accurate-span", true); // NOI18N
                // Set the same kit and document
                tooltipPane.setEditorKit(kit);
                tooltipPane.setDocument(doc);
                tooltipPane.setEditable(false);
                return new FoldToolTip(editorPane, tooltipPane, getBorderColor());
            } catch (BadLocationException e) {
                // => return null
            }
        }
    }
    return null;
}
 
Example 11
public void actionPerformed(ActionEvent e) {
	JTextComponent tc = (JTextComponent) getInvoker();
	@SuppressWarnings("unused")
	String sel = tc.getSelectedText();

	if (e.getSource() == cutItem) {
		tc.cut();
	} else if (e.getSource() == copyItem) {
		tc.copy();
	} else if (e.getSource() == pasteItem) {
		tc.paste();
	} else if (e.getSource() == selectAllItem) {
		tc.selectAll();
	} else if (e.getSource() == deleteItem) {
		Document doc = tc.getDocument();
		int start = tc.getSelectionStart();
		int end = tc.getSelectionEnd();

		try {
			Position p0 = doc.createPosition(start);
			Position p1 = doc.createPosition(end);

			if ((p0 != null) && (p1 != null)
					&& (p0.getOffset() != p1.getOffset())) {
				doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
			}
		} catch (BadLocationException be) {
		}
	}
}
 
Example 12
Source Project: netbeans   File: BaseDocumentTest.java    License: Apache License 2.0 5 votes vote down vote up
private void releaseDocAndHoldPosition(Document doc) throws Exception {
    doc.insertString(0, "Nazdar", null);
    Position pos = doc.createPosition(3);
    doc.insertString(2, "abc", null);
    assertEquals(6, pos.getOffset());
    WeakReference<Document> docRef = new WeakReference<Document>(doc);
    doc = null;
    assertGC("Doc not released", docRef);
    assertEquals(6, pos.getOffset()); // Doc released but position can still be referenced
}
 
Example 13
Source Project: netbeans   File: OffsetRegion.java    License: Apache License 2.0 5 votes vote down vote up
private static Position createPos(Document doc, int offset) {
    try {
        return doc.createPosition(offset);
    } catch (BadLocationException ex) {
        throw new IllegalArgumentException("Invalid offset=" + offset + " in doc: " + doc, ex);
    }
}
 
Example 14
Source Project: netbeans   File: ViewHierarchyTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testCustomBounds() throws Exception {
    loggingOn();    
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    doc.insertString(0, "hello\nworld\ngood\nmorning", null);
    Position startPos = doc.createPosition(3);
    pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, startPos);
    pane.modelToView(0); // Force rebuild of VH
    doc.insertString(startPos.getOffset(), "a", null);
    doc.insertString(startPos.getOffset() - 1, "a", null);
    Element line0 = doc.getDefaultRootElement().getElement(0);
    Position endPos = doc.createPosition(line0.getEndOffset() + 3); // Middle of line 1
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos);
    pane.modelToView(0); // Force rebuild of VH

    TestHighlightsViewFactory testFactory = ViewUpdatesTesting.getTestFactory(pane);
    List<TestHighlight> hlts = ViewUpdatesTesting.getHighlightsCopy(testFactory);
    int hlStartOffset = startPos.getOffset() + 1;
    int hlEndOffset = endPos.getOffset() - 1; 
    TestHighlight hi = TestHighlight.create(doc, hlStartOffset, hlEndOffset, colorAttrs[0]);
    hlts.add(hi);
    testFactory.setHighlights(hlts);
    testFactory.fireChange(hlStartOffset, hlEndOffset);
    pane.modelToView(0); // Force rebuild of VH
    
    doc.insertString(doc.getLength(), "test\ntest2", null);
    Position endPos2 = doc.createPosition(doc.getLength() - 3);
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos2);
    pane.modelToView(0); // Force rebuild of VH
    doc.remove(endPos2.getOffset() - 2, 3);
    pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, null);
    pane.modelToView(0); // Force rebuild of VH
}
 
Example 15
Source Project: netbeans   File: ViewHierarchyTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEmptyCustomBounds() throws Exception {
    loggingOn();    
    JEditorPane pane = ViewUpdatesTesting.createPane();
    Document doc = pane.getDocument();
    pane.modelToView(0);
    doc.insertString(0, "hello\nworld\ngood\nmorning", null);
    Position startPos = doc.createPosition(3);
    pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, startPos);
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, startPos);
    pane.modelToView(0); // Force rebuild of VH

    Position endPos = doc.createPosition(2);
    pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos);
    pane.modelToView(0); // Force rebuild of VH
}
 
Example 16
public static Position createPosition(Document doc, int offset) {
    try {
        return doc.createPosition(offset);
    } catch (BadLocationException ex) {
        throw new IndexOutOfBoundsException(ex.getMessage());
    }
}
 
Example 17
Source Project: littleluck   File: SnippetHighlighter.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * Changes a highlight.
    *
    * @param tag the highlight tag
    * @param p0 the beginning of the range >= 0
    * @param p1 the end of the range >= p0
    * @exception BadLocationException if the specified location is invalid
    */
   public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException {
Document doc = component.getDocument();
if (tag instanceof LayeredHighlightInfo) {
    LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag;
    if (lhi.width > 0 && lhi.height > 0) {
	component.repaint(lhi.x, lhi.y, lhi.width, lhi.height);
    }
    // Mark the highlights region as invalid, it will reset itself
    // next time asked to paint.
    lhi.width = lhi.height = 0;
    lhi.p0 = doc.createPosition(p0);
    lhi.p1 = doc.createPosition(p1);
           safeDamageRange(Math.min(p0, p1), Math.max(p0, p1));
}
else {
    HighlightInfo info = (HighlightInfo) tag;
    int oldP0 = info.p0.getOffset();
    int oldP1 = info.p1.getOffset();
    if (p0 == oldP0) {
               safeDamageRange(Math.min(oldP1, p1),
			   Math.max(oldP1, p1));
    } else if (p1 == oldP1) {
               safeDamageRange(Math.min(p0, oldP0),
			   Math.max(p0, oldP0));
    } else {
               safeDamageRange(oldP0, oldP1);
               safeDamageRange(p0, p1);
    }
    info.p0 = doc.createPosition(p0);
    info.p1 = doc.createPosition(p1);
}
   }
 
Example 18
Source Project: beautyeye   File: SnippetHighlighter.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * Changes a highlight.
    *
    * @param tag the highlight tag
    * @param p0 the beginning of the range >= 0
    * @param p1 the end of the range >= p0
    * @exception BadLocationException if the specified location is invalid
    */
   public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException {
Document doc = component.getDocument();
if (tag instanceof LayeredHighlightInfo) {
    LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag;
    if (lhi.width > 0 && lhi.height > 0) {
	component.repaint(lhi.x, lhi.y, lhi.width, lhi.height);
    }
    // Mark the highlights region as invalid, it will reset itself
    // next time asked to paint.
    lhi.width = lhi.height = 0;
    lhi.p0 = doc.createPosition(p0);
    lhi.p1 = doc.createPosition(p1);
           safeDamageRange(Math.min(p0, p1), Math.max(p0, p1));
}
else {
    HighlightInfo info = (HighlightInfo) tag;
    int oldP0 = info.p0.getOffset();
    int oldP1 = info.p1.getOffset();
    if (p0 == oldP0) {
               safeDamageRange(Math.min(oldP1, p1),
			   Math.max(oldP1, p1));
    } else if (p1 == oldP1) {
               safeDamageRange(Math.min(p0, oldP0),
			   Math.max(p0, oldP0));
    } else {
               safeDamageRange(oldP0, oldP1);
               safeDamageRange(p0, p1);
    }
    info.p0 = doc.createPosition(p0);
    info.p1 = doc.createPosition(p1);
}
   }
 
Example 19
@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (target != null) {
        Caret caret = target.getCaret();
        if (!Utilities.isSelectionShowing(caret)) {
            try {
                int[] identifierBlock = Utilities.getIdentifierBlock((BaseDocument) target.getDocument(), caret.getDot());
                if (identifierBlock != null) {
                    caret.setDot(identifierBlock[0]);
                    caret.moveDot(identifierBlock[1]);
                }
            } catch (BadLocationException e) {
                LOGGER.log(Level.WARNING, null, e);
            }
        }

        EditorFindSupport findSupport = EditorFindSupport.getInstance();
        HashMap<String, Object> props = new HashMap<>(findSupport.createDefaultFindProperties());
        String searchWord = target.getSelectedText();
        if (searchWord != null) {
            int n = searchWord.indexOf('\n');
            if (n >= 0) {
                searchWord = searchWord.substring(0, n);
            }
            props.put(EditorFindSupport.FIND_WHAT, searchWord);
            Document doc = target.getDocument();
            EditorUI eui = org.netbeans.editor.Utilities.getEditorUI(target);
            if (eui.getComponent().getClientProperty("AsTextField") == null) { //NOI18N
                findSupport.setFocusedTextComponent(eui.getComponent());
            }
            findSupport.putFindProperties(props);
            findSupport.find(null, false);

            if (caret instanceof EditorCaret) {
                EditorCaret editorCaret = (EditorCaret) caret;
                try {
                    int[] blocks = findSupport.getBlocks(new int[]{-1, -1}, doc, 0, doc.getLength());
                    if (blocks[0] >= 0 && blocks.length % 2 == 0) {
                        List<Position> newCarets = new ArrayList<>();

                        for (int i = 0; i < blocks.length; i += 2) {
                            int start = blocks[i];
                            int end = blocks[i + 1];
                            if (start == -1 || end == -1) {
                                break;
                            }
                            Position startPos = doc.createPosition(start);
                            Position endPos = doc.createPosition(end);
                            newCarets.add(endPos);
                            newCarets.add(startPos);
                        }

                        editorCaret.replaceCarets(newCarets, null); // TODO handle biases
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
}
 
Example 20
Source Project: netbeans   File: PositionRegion.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Construct new position region based on the knowledge
 * of the document and starting and ending offset.
 */
public PositionRegion(Document doc, int startOffset, int endOffset) throws BadLocationException {
    this(doc.createPosition(startOffset), doc.createPosition(endOffset));
}