/** 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 { BaseDocument doc = (BaseDocument)c.getDocument(); Caret caret = c.getCaret(); int[] ret; if (caret.isSelectionVisible()) { ret = new int[] { c.getSelectionStart(), c.getSelectionEnd() }; } else if !(doc instanceof BaseDocument){ ret = getIdentifierBlock(c, offset); } else { ret = getIdentifierBlock((BaseDocument)doc, caret.getDot()); } return ret; } /** Get the word around the given position . * @param c component to work with * @param offset position in document - usually the caret.getDot() * @return the word. */ public static String getWord(JTextComponent c, int offset) throws BadLocationException { int[] blk = getIdentifierBlock(c, offset); Document doc = c.getDocument(); return (blk != null) ? doc.getText(blk[0], blk[1] - blk[0]) : null; } /** Get the identifier around the given position or null if there's no identifier * around the given position. The identifier is not verified against SyntaxSupport.isIdentifier(). * @param c JTextComponent to work on * @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[] getIdentifierBlock(JTextComponent c, int offset) throws BadLocationException { String id = null; int[] ret = null; Document doc = c.getDocument(); int idStart = javax.swing.text.Utilities.getWordStart(c, offset); if (idStart >= 0) { int idEnd = javax.swing.text.Utilities.getWordEnd(c, idStart); if (idEnd >= 0) { id = doc.getText(idStart, idEnd - idStart); ret = new int[] { idStart, idEnd }; String trim = id.trim(); if (trim.length() == 0 || (trim.length() == 1 && !Character.isJavaIdentifierPart(trim.charAt(0)))) { int prevWordStart = javax.swing.text.Utilities.getPreviousWord(c, offset); if (offset == javax.swing.text.Utilities.getWordEnd(c,prevWordStart )){ ret = new int[] { prevWordStart, offset }; } } else if ((id != null) && (id.length() != 0) && (id.indexOf(".") != -1)){ int index = offset - idStart; int begin = id.substring(0, index).lastIndexOf("."); begin = (begin == -1) ? 0 : begin + 1; //first index after the dot, if exists int end = id.indexOf(".", index); end = (end == -1) ? id.length() : end; ret = new int[] { idStart+begin, idStart+end }; } } } return ret; }