Java Code Examples for javax.swing.text.JTextComponent#getSelectionEnd()

The following examples show how to use javax.swing.text.JTextComponent#getSelectionEnd() . 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 File: NameAutocompleter.java    From plugins with GNU General Public License v3.0 8 votes vote down vote up
private boolean isExpectedNext(JTextComponent input, String nextChar)
{
	String expected;
	if (input.getSelectionStart() < input.getSelectionEnd())
	{
		try
		{
			expected = input.getText(input.getSelectionStart(), 1);
		}
		catch (BadLocationException ex)
		{
			log.warn("Could not get first character from input selection.", ex);
			return false;
		}
	}
	else
	{
		expected = "";
	}
	return nextChar.equalsIgnoreCase(expected);
}
 
Example 2
Source File: TplCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public boolean instantSubstitution(JTextComponent component) {
    if (component != null) {
        try {
            int substitutionOffset = CodeCompletionUtils.getSubstitutionLenght(component.getDocument(), component.getCaretPosition());
            int caretOffset = component.getSelectionEnd();
            if (caretOffset > substitutionOffset) {
                String currentText = component.getDocument().getText(substitutionOffset, caretOffset - substitutionOffset);
                if (!getSubstituteText().toString().startsWith(currentText)) {
                    return false;
                }
            }
        } catch (BadLocationException ble) {
        }
    }
    defaultAction(component);
    return true;
}
 
Example 3
Source File: GsfCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean instantSubstitution(JTextComponent component) {
    ElementKind kind = item.getKind();
    if (kind == ElementKind.PARAMETER || kind == ElementKind.CLASS || kind == ElementKind.MODULE) {
        // These types of elements aren't ever instant substituted in Java - use same behavior here
        return false;
    }

    if (component != null) {
        try {
            int caretOffset = component.getSelectionEnd();
            if (caretOffset > substitutionOffset) {
                String text = component.getDocument().getText(substitutionOffset, caretOffset - substitutionOffset);
                if (!getInsertPrefix().toString().startsWith(text)) {
                    return false;
                }
            }
        }
        catch (BadLocationException ble) {}
    }
    defaultAction(component);
    return true;
}
 
Example 4
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 *
 * Note that the strings returned will not contain the terminating line feeds
 * If the document is empty, then an empty string array is returned.  So
 * you can always iterate over the returned array without a null check
 *
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or line containing dot
 */
public static String[] getSelectedLines(JTextComponent target) {
	String[] lines = null;
	try {
		PlainDocument pDoc = (PlainDocument) target.getDocument();
		int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
		int end;
		if (target.getSelectionStart() == target.getSelectionEnd()) {
			end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
		} else {
			// if more than one line is selected, we need to subtract one from the end
			// so that we do not select the line with the caret and no selection in it
			end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
		}
		target.select(start, end);
		lines = pDoc.getText(start, end - start).split("\n");
		target.select(start, end);
	} catch (BadLocationException ex) {
		Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
		lines = EMPTY_STRING_ARRAY;
	}
	return lines;
}
 
Example 5
Source File: HtmlCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean instantSubstitution(JTextComponent component) {
    if (component != null) {
        try {
            int caretOffset = component.getSelectionEnd();
            if (caretOffset > substitutionOffset) {
                String currentText = component.getDocument().getText(substitutionOffset, caretOffset - substitutionOffset);
                if (!getSubstituteText().toString().startsWith(currentText)) {
                    return false;
                }
            }
        } catch (BadLocationException ble) {
        }
    }
    defaultAction(component);
    return true;
}
 
Example 6
Source File: SyntaxUtil.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds.
 * 
 * The text component will then have the full lines set as selection.
 * 
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument document = (PlainDocument) target.getDocument();
        int start = document.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = document.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = document.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = document.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
        lines = EMPTY_STRING_ARRAY;
    }
    
    return lines;
}
 
Example 7
Source File: HTMLTextAreaSearchUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public Shape paintLayer(Graphics g, int offs0, int offs1,
                        Shape bounds, JTextComponent c, View view) {
    
    int selStart = c.getSelectionStart();
    int selEnd = c.getSelectionEnd();
    
    // No selection or selection fully outside of the highlight
    if (selEnd - selStart == 0 || offs0 >= selEnd || offs1 <= selStart) return super.paintLayer(g, offs0, offs1, bounds, c, view);
    
    // Selection fully covers the highlight
    if (offs0 >= selStart && offs1 <= selEnd) return bounds;
    
    // Selection partially covers the highlight
    if (offs0 < selStart || offs1 > selEnd) {
        // Selection ends inside of the highlight
        if (offs0 >= selStart) return super.paintLayer(g, selEnd, offs1, bounds, c, view);
        // Selection starts inside of the highlight
        else if (offs1 <= selEnd) return super.paintLayer(g, offs0, selStart, bounds, c, view);
        
        // Selection fully inside of the highlight
        super.paintLayer(g, offs0, selStart, bounds, c, view);
        super.paintLayer(g, selEnd, offs1, bounds, c, view);
    }
    
    return bounds;
}
 
Example 8
Source File: CutCommand.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void adjust() {
    boolean   enable = false;
    Component comp   = getFocusOwner();
    if (comp instanceof JTextComponent && comp.isEnabled()) {
        JTextComponent textComp = (JTextComponent) comp;
        if (textComp.isEditable()) {
            enable = textComp.getSelectionStart() != textComp.getSelectionEnd();
        }
    } else {
        Cutable cutable = getTarget(Cutable.class);
        if (cutable != null) {
            enable = cutable.canCutSelection();
        }
    }
    setEnabled(enable);
}
 
Example 9
Source File: Markers.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * add highlights for the given region on the given pane
 * @param pane
 * @param start
 * @param end
 * @param marker
 */
public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) {
    try {
        Highlighter hiliter = pane.getHighlighter();
        int selStart = pane.getSelectionStart();
        int selEnd = pane.getSelectionEnd();
        // if there is no selection or selection does not overlap
        if(selStart == selEnd || end < selStart || start > selStart) {
            hiliter.addHighlight(start, end, marker);
            return;
        }
        // selection starts within the highlight, highlight before slection
        if(selStart > start && selStart < end ) {
            hiliter.addHighlight(start, selStart, marker);
        }
        // selection ends within the highlight, highlight remaining
        if(selEnd > start && selEnd < end ) {
            hiliter.addHighlight(selEnd, end, marker);
        }

    } catch (BadLocationException ex) {
        // nothing we can do if the request is out of bound
        LOG.log(Level.SEVERE, null, ex);
    }
}
 
Example 10
Source File: MyMarkers.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * add highlights for the given region on the given pane
 *
 * @param pane Editor
 * @param start Start index
 * @param end End index
 * @param marker Marker
 */
public static void markText(JTextComponent pane, int start, int end, Highlighter.HighlightPainter marker) {
    try {
        Highlighter hiliter = pane.getHighlighter();
        int selStart = pane.getSelectionStart();
        int selEnd = pane.getSelectionEnd();
        // if there is no selection or selection does not overlap
        if (selStart == selEnd || end < selStart || start > selStart) {
            hiliter.addHighlight(start, end, marker);
            return;
        }
        // selection starts within the highlight, highlight before slection
        if (selStart > start && selStart < end) {
            hiliter.addHighlight(start, selStart, marker);
        }
        // selection ends within the highlight, highlight remaining
        if (selEnd > start && selEnd < end) {
            hiliter.addHighlight(selEnd, end, marker);
        }

    } catch (BadLocationException ex) {

    }
}
 
Example 11
Source File: Markers.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * add highlights for the given region on the given pane
 * @param pane
 * @param start
 * @param end
 * @param marker
 */
public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) {
    try {
        Highlighter hiliter = pane.getHighlighter();
        int selStart = pane.getSelectionStart();
        int selEnd = pane.getSelectionEnd();
        // if there is no selection or selection does not overlap
        if(selStart == selEnd || end < selStart || start > selStart) {
            hiliter.addHighlight(start, end, marker);
            return;
        }
        // selection starts within the highlight, highlight before slection
        if(selStart > start && selStart < end ) {
            hiliter.addHighlight(start, selStart, marker);
        }
        // selection ends within the highlight, highlight remaining
        if(selEnd > start && selEnd < end ) {
            hiliter.addHighlight(selEnd, end, marker);
        }

    } catch (BadLocationException ex) {
        // nothing we can do if the request is out of bound
        LOG.log(Level.SEVERE, null, ex);
    }
}
 
Example 12
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Get the selection if there's any or get the identifier around
* the position if there's no selection.
* @param c component to work with
* @param offset position in document - usually the caret.getDot()
* @return the block (starting and ending position) enclosing the identifier
*   or null if no identifier was found
*/
public static int[] getSelectionOrIdentifierBlock(JTextComponent c, int offset)
throws BadLocationException {
    Document doc = c.getDocument();
    Caret caret = c.getCaret();
    int[] ret;
    if (Utilities.isSelectionShowing(caret)) {
        ret = new int[] { c.getSelectionStart(), c.getSelectionEnd() }; 
    } else if (doc instanceof BaseDocument){
        ret = getIdentifierBlock((BaseDocument)doc, offset);
    } else {
        ret = getIdentifierBlock(c, offset);
    }
    return ret;
}
 
Example 13
Source File: SpringXMLConfigCompletionItem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void processKeyEvent(KeyEvent evt) {
    if (evt.getID() == KeyEvent.KEY_TYPED) {
        if(evt.getKeyChar() == '/') { // NOI18N
            Completion.get().hideDocumentation();
            JTextComponent component = (JTextComponent)evt.getSource();
            int caretOffset = component.getSelectionEnd();
            substituteText(component, substitutionOffset, caretOffset - substitutionOffset, Character.toString(evt.getKeyChar()));
            Completion.get().showCompletion();
            evt.consume();
        }
    }
}
 
Example 14
Source File: CssActionsImplementationProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public TextComponentTask(EditorCookie ec) {
    JTextComponent textC = ec.getOpenedPanes()[0];
    this.document = textC.getDocument();
    this.caretOffset = textC.getCaretPosition();
    this.selectionStart = textC.getSelectionStart();
    this.selectionEnd = textC.getSelectionEnd();
}
 
Example 15
Source File: InjectCompositeComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke() {
    JTextComponent textComponent = EditorRegistry.lastFocusedComponent();
    Document doc = textComponent.getDocument();
    int from = textComponent.getSelectionStart();
    int to = textComponent.getSelectionEnd();

    inject(doc, from, to);

}
 
Example 16
Source File: CPActionsImplementationProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public TextComponentTask(EditorCookie ec) {
    JTextComponent textC = ec.getOpenedPanes()[0];
    this.document = textC.getDocument();
    this.caretOffset = textC.getCaretPosition();
    this.selectionStart = textC.getSelectionStart();
    this.selectionEnd = textC.getSelectionEnd();
}
 
Example 17
Source File: StatusBar.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent evt) {
    Caret c = caret;
    JTextComponent component = editorUI.getComponent();

    // Also check whether the component is last focused since when undocking an editor
    // all the components' carets fire this listener and so invalid component's
    // data would get displayed in the global status bar.
    if (component != null && component == EditorRegistry.lastFocusedComponent()) {
        if (c != null) {
            BaseDocument doc = Utilities.getDocument(component);
            if (doc != null && doc.getDefaultRootElement().getElementCount()>0) {
                int pos = c.getDot();
                String s = Utilities.debugPosition(doc, pos, ":");
                if (CARET_OFFSET_LOG.isLoggable(Level.FINE)) { // Possibly add caret offset info
                    s += " <" + pos + ">"; // NOI18N
                }
                int countOfSelectedChars = component.getSelectionEnd() - component.getSelectionStart();
                final boolean hasSelection = countOfSelectedChars > 0;
                if (hasSelection) {
                    try {
                        //count of selected lines
                        int lineEnd = Utilities.getLineOffset(doc, component.getSelectionEnd());
                        int lineStart = Utilities.getLineOffset(doc, component.getSelectionStart());
                        s += "/" + (lineEnd - lineStart + 1);
                    } catch (BadLocationException ex) {
                    }
                    //count of selected characters
                    s += ":" + countOfSelectedChars;
                }
                //rows:cols/countRows:countCols
                setText(CELL_POSITION, s);
            }
        }

        Boolean b = (Boolean)editorUI.getProperty(EditorUI.OVERWRITE_MODE_PROPERTY);
        boolean om = (b != null && b.booleanValue());
        if (om != overwriteModeDisplayed) {
            overwriteModeDisplayed = om;
            setText(CELL_TYPING_MODE, overwriteModeDisplayed ? ovrText : insText);
        }
    }
}
 
Example 18
Source File: EditMenuControls.java    From pumpernickel with MIT License 4 votes vote down vote up
@Override
public boolean accepts(JTextComponent jtc) {
	int i1 = jtc.getSelectionStart();
	int i2 = jtc.getSelectionEnd();
	return i1 != i2;
}
 
Example 19
Source File: EditorFindSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
boolean replaceImpl(Map<String, Object> props, boolean oppositeDir, JTextComponent c) throws BadLocationException {
    props = getValidFindProperties(props);
    boolean back = Boolean.TRUE.equals(props.get(FIND_BACKWARD_SEARCH));
    if (oppositeDir) {
        back = !back;
    }
    boolean blockSearch = Boolean.TRUE.equals(props.get(FIND_BLOCK_SEARCH));
    Position blockSearchStartPos = (Position) props.get(FIND_BLOCK_SEARCH_START);
    int blockSearchStartOffset = (blockSearchStartPos != null) ? blockSearchStartPos.getOffset() : -1;

    if (c != null) {
        String s = (String)props.get(FIND_REPLACE_WITH);
        Caret caret = c.getCaret();
        if (caret.isSelectionVisible() && caret.getDot() != caret.getMark()){
            Object dp = props.get(FIND_BACKWARD_SEARCH);
            boolean direction = (dp != null) ? ((Boolean)dp).booleanValue() : false;
            int dotPos = (oppositeDir ^ direction ? c.getSelectionEnd() : c.getSelectionStart());
            c.setCaretPosition(dotPos);
        }
        
        FindReplaceResult result = findReplaceImpl(s, props, oppositeDir, c);
        if (result!=null){
            s  = result.getReplacedString();
        } else {
            return false;
        }

        Document doc = c.getDocument();
        int startOffset = c.getSelectionStart();
        int len = c.getSelectionEnd() - startOffset;
        DocUtils.atomicLock(doc);
        try {
            if (len > 0) {
                doc.remove(startOffset, len);
            }
            if (s != null && s.length() > 0) {
                try {
                    NavigationHistory.getEdits().markWaypoint(c, startOffset, false, true);
                } catch (BadLocationException e) {
                    LOG.log(Level.WARNING, "Can't add position to the history of edits.", e); //NOI18N
                }
                doc.insertString(startOffset, s, null);
                if (startOffset == blockSearchStartOffset) { // Replaced at begining of block
                    blockSearchStartPos = doc.createPosition(startOffset);
                    props.put(EditorFindSupport.FIND_BLOCK_SEARCH_START, blockSearchStartPos);
                }
            }
        } finally {
            DocUtils.atomicUnlock(doc);
            if (blockSearch){
                setBlockSearchHighlight(blockSearchStartOffset, getBlockEndOffset());
            }
        }
        
        // adjust caret pos after replace operation
        int adjustedCaretPos = (back || s == null) ? startOffset : startOffset + s.length();
        caret.setDot(adjustedCaretPos);
        
    }
    
    return true;
}
 
Example 20
Source File: NameAutocompleter.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void keyTyped(KeyEvent e)
{
	if (!hiscoreConfig.autocomplete())
	{
		return;
	}

	final JTextComponent input = (JTextComponent) e.getSource();
	final String inputText = input.getText();

	// Only autocomplete if the selection end is at the end of the text.
	if (input.getSelectionEnd() != inputText.length())
	{
		return;
	}

	// Character to be inserted at the selection start.
	final String charToInsert = Character.toString(e.getKeyChar());

	// Don't attempt to autocomplete if the name is invalid.
	// This condition is also true when the user presses a key like backspace.
	if (INVALID_CHARS.matcher(charToInsert).find()
		|| INVALID_CHARS.matcher(inputText).find())
	{
		return;
	}

	// Check if we are already autocompleting.
	if (autocompleteName != null && autocompleteNamePattern.matcher(inputText).matches())
	{
		if (isExpectedNext(input, charToInsert))
		{
			try
			{
				// Insert the character and move the selection.
				final int insertIndex = input.getSelectionStart();
				Document doc = input.getDocument();
				doc.remove(insertIndex, 1);
				doc.insertString(insertIndex, charToInsert, null);
				input.select(insertIndex + 1, input.getSelectionEnd());
			}
			catch (BadLocationException ex)
			{
				log.warn("Could not insert character.", ex);
			}

			// Prevent default behavior.
			e.consume();
		}
		else // Character to insert does not match current autocompletion. Look for another name.
		{
			newAutocomplete(e);
		}
	}
	else // Search for a name to autocomplete
	{
		newAutocomplete(e);
	}
}