Here are the examples of the java api org.netbeans.lib.editor.util.swing.DocumentUtilities.getText() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
57 Examples
19
Source : DocumentFinder.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static FindReplaceResult findBlocks(Doreplacedent doc, int startOffset, int endOffset, Map<String, Object> props, int[] blocks) throws BadLocationException {
BlocksFinder finder;
try {
finder = (BlocksFinder) getFinder(doc, props, false, true);
} catch (PatternSyntaxException pse) {
FindReplaceResult findReplaceResult = new FindReplaceResult(new int[] { -1, -1 }, "");
findReplaceResult.setErrorMsg(NbBundle.getMessage(DoreplacedentFinder.clreplaced, "pattern-error-dialog-content") + " " + pse.getDescription());
return findReplaceResult;
}
if (finder == null) {
return new FindReplaceResult(blocks, "");
}
CharSequence cs = DoreplacedentUtilities.getText(doc, startOffset, endOffset - startOffset);
if (cs == null) {
return null;
}
synchronized (finder) {
finder.reset();
finder.setBlocks(blocks);
finder.find(startOffset, cs);
int[] ret = finder.getBlocks();
return new FindReplaceResult(ret, "");
}
}
19
Source : WrapInfoUpdater.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get word info in case there's a word around boundaryOffset.
* @param boundaryOffset there must be word's char before and after this offset
* to return non-null result.
* @param startLimitOffset start offset of inspected area.
* @return word info or null if a non-empty word cannot be created.
*/
private WordInfo getWordInfo(int boundaryOffset, int startLimitOffset) {
CharSequence docText = DoreplacedentUtilities.getText(docView.getDoreplacedent());
boolean prevCharIsWordPart = (boundaryOffset > startLimitOffset) && Character.isLetterOrDigit(docText.charAt(boundaryOffset - 1));
int docTextLength;
if (prevCharIsWordPart && (boundaryOffset < (docTextLength = docText.length()))) {
// Check if next char is word part as well
// [TODO] Check surrogates
boolean nextCharIsWordPart = Character.isLetterOrDigit(docText.charAt(boundaryOffset));
if (nextCharIsWordPart) {
int wordEndOffset;
for (wordEndOffset = boundaryOffset + 1; wordEndOffset < docTextLength; wordEndOffset++) {
// [TODO] Check surrogates
if (!Character.isLetterOrDigit(docText.charAt(wordEndOffset))) {
break;
}
}
return new WordInfo(docText, boundaryOffset, startLimitOffset, wordEndOffset);
}
}
return null;
}
19
Source : BaseDocumentTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testGetText() throws Exception {
BaseDoreplacedent doc = new BaseDoreplacedent(false, "text/plain");
CharSequence text = DoreplacedentUtilities.getText(doc);
replacedertEquals(1, text.length());
replacedertEquals('\n', text.charAt(0));
text = DoreplacedentUtilities.getText(doc);
doc.insertString(0, "a\nb", null);
for (int i = 0; i < doc.getLength() + 1; i++) {
replacedertEquals(doc.getText(i, 1).charAt(0), text.charAt(i));
}
}
19
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getPreviousWordEnd(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getPreviousWordEnd(docText, clreplacedifier, offset);
}
19
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get first non-whitespace character in doreplacedent in forward direction.
*
* @param doc doreplacedent to operate on
* @param offset offset of first character to examine for WS.
* @param limitOffset offset above the last character to examine for WS.
* @return position of the next non-WS character or -1 if not found.
*/
public static int getNextNonWhitespace(@NonNull LineDoreplacedent doc, int offset, int limitOffset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getNextNonWhitespace(docText, clreplacedifier, offset, limitOffset);
}
19
Source : ToggleBlockCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private boolean allComments(LineDoreplacedent doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
final int lineCommentStringLen = lineCommentString.length();
for (int offset = startOffset; lineCount > 0; lineCount--) {
int firstNonWhitePos = LineDoreplacedentUtils.getLineFirstNonWhitespace(doc, offset);
if (firstNonWhitePos == -1) {
return false;
}
if (LineDoreplacedentUtils.getLineEnd(doc, firstNonWhitePos) - firstNonWhitePos < lineCommentStringLen) {
return false;
}
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
if (!CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
return false;
}
offset = getNexLineOffset(doc, offset);
}
return true;
}
18
Source : PlainTokenList.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public boolean nextWord() {
if (hidden)
return false;
try {
int offset = nextSearchOffset;
boolean searching = true;
CharSequence content = DoreplacedentUtilities.getText(doc);
while (offset < content.length()) {
char c = content.charAt(offset);
if (searching) {
if (Character.isLetter(c)) {
searching = false;
currentStartOffset = offset;
}
} else {
if (!Character.isLetter(c)) {
nextSearchOffset = offset;
currentWord = doc.getText(currentStartOffset, offset - currentStartOffset);
return true;
}
}
offset++;
}
nextSearchOffset = doc.getLength();
if (searching) {
return false;
}
currentWord = doc.getText(currentStartOffset, doc.getLength() - currentStartOffset);
return true;
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
return false;
}
}
18
Source : PlainTokenList.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void setStartOffset(int offset) {
currentWord = null;
currentStartOffset = (-1);
CharSequence content = DoreplacedentUtilities.getText(doc);
while (offset > 0 && offset < content.length()) {
if (!Character.isLetter(content.charAt(offset))) {
break;
}
offset--;
}
this.nextSearchOffset = offset;
FileObject fileObject = FileUtil.getConfigFile("Spellcheckers/Plain");
Boolean b = (Boolean) fileObject.getAttribute("Hidden");
hidden = Boolean.TRUE.equals(b);
}
18
Source : EmbeddedSectionsHighlighting.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static boolean isWhitespace(Doreplacedent doreplacedent, int startOffset, int endOffset) throws BadLocationException {
CharSequence chars = DoreplacedentUtilities.getText(doreplacedent, startOffset, endOffset - startOffset);
for (int i = 0; i < chars.length(); i++) {
if (!Character.isWhitespace(chars.charAt(i))) {
return false;
}
}
return true;
}
18
Source : IndentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get indentation of a line in a doreplacedent as a number of spaces.
*
* @param doc non-null doreplacedent.
* @param lineStartOffset >= 0 start offset of a line in the doreplacedent.
* @throws BadLocationException for invalid offset
*/
public static int lineIndent(Doreplacedent doc, int lineStartOffset) throws BadLocationException {
IndentImpl.checkOffsetInDoreplacedent(doc, lineStartOffset);
CharSequence docText = DoreplacedentUtilities.getText(doc);
int indent = 0;
int tabSize = -1;
while (lineStartOffset < docText.length()) {
char ch;
switch(ch = docText.charAt(lineStartOffset)) {
case // NOI18N
'\n':
return indent;
case // NOI18N
'\t':
if (tabSize == -1)
tabSize = tabSize(doc);
// Round to next tab stop
indent = (indent + tabSize) / tabSize * tabSize;
break;
default:
if (Character.isWhitespace(ch)) {
indent++;
} else {
return indent;
}
}
lineStartOffset++;
}
return indent;
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getNextWordStart(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getNextWordStart(docText, clreplacedifier, offset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get first non-whitespace character in doreplacedent in forward direction.
*
* @param doc doreplacedent to operate on
* @param offset offset of first character to examine for WS.
* @param limitOffset the offset of the last character to examine for WS.
* @return position of the next non-WS character or -1 if not found.
*/
public static int getPreviousNonWhitespace(@NonNull LineDoreplacedent doc, int offset, int limitOffset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getPreviousNonWhitespace(docText, clreplacedifier, offset, limitOffset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get first whitespace character in doreplacedent in backward direction.
*
* @param doc doreplacedent to operate on
* @param offset offset above first character to examine for WS.
* @param limitOffset offset of the last character (in backward direction) to examine for WS.
* @return position of the previous WS character or -1 if not found.
*/
public static int getPreviousWhitespace(@NonNull LineDoreplacedent doc, int offset, int limitOffset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getPreviousWhitespace(docText, clreplacedifier, offset, limitOffset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Tests whether the line at the given offset contains no characters except the ending new-line.
* @param doc doreplacedent to operate on
* @param offset position anywhere on the tested line
* @return whether the line is empty or not
*/
public static boolean isLineEmpty(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.isLineEmpty(docText, offset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get the first non-whitespace character on a line represented by the given
* offset.
*
* @param doc doreplacedent to operate on
* @param offset position in doreplacedent anywhere on the line
* @return position of the first non-white char on the line or -1 if there's
* no non-white character on that line.
*/
public static int getLineFirstNonWhitespace(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
Element lineElement = doc.getParagraphElement(offset);
return TextSearchUtils.getNextNonWhitespace(docText, clreplacedifier, lineElement.getStartOffset(), lineElement.getEndOffset() - 1);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getWordStart(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getWordStart(docText, clreplacedifier, offset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getNextNonNewline(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getNextNonNewline(docText, offset, doc.getLength() + 1);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get start of a previous word in backward direction.
*
* @param doc non-null doreplacedent.
* @param offset >= 0 offset in doreplacedent.
* @return previous word boundary offset.
* @since 1.4
*/
public static int getPreviousWordStart(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getPreviousWordStart(docText, clreplacedifier, offset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getWordEnd(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getWordEnd(docText, clreplacedifier, offset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static int getPreviousNonNewline(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getPreviousNonNewline(docText, offset, 0);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get first whitespace character in doreplacedent in forward direction.
*
* @param doc doreplacedent to operate on
* @param offset position in doreplacedent where to start searching
* @param limitOffset offset above the last character to examine for WS.
* @return position of the next WS character or -1 if not found.
*/
public static int getNextWhitespace(@NonNull LineDoreplacedent doc, int offset, int limitOffset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getNextWhitespace(docText, clreplacedifier, offset, limitOffset);
}
18
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get the word at given offset.
* @param doc doreplacedent to operate on
* @param wordStartOffset offset of word start.
* @return word starting at offset.
*/
public static String getWord(@NonNull LineDoreplacedent doc, int wordStartOffset) throws BadLocationException {
checkOffsetValid(doc, wordStartOffset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
return TextSearchUtils.getWord(docText, clreplacedifier, wordStartOffset).toString();
}
18
Source : ToggleBlockCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private int findCommentEnd(LineDoreplacedent doc, CommentHandler handler, int offsetFrom, int offsetTo) throws BadLocationException {
int to = LineDoreplacedentUtils.getPreviousNonWhitespace(doc, offsetTo, offsetFrom);
if (to == -1) {
return offsetTo;
}
String endDelim = handler.getCommentEndDelimiter();
if (DoreplacedentUtilities.getText(doc).subSequence(Math.max(offsetFrom, to - endDelim.length() + 1), to + 1).equals(endDelim)) {
// after end of the delimiter
return to + 1;
}
return offsetFrom;
}
18
Source : ToggleBlockCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void uncomment(LineDoreplacedent doc, int startOffset, int lineCount, String lineCommentString) throws BadLocationException {
final int lineCommentStringLen = lineCommentString.length();
for (int offset = startOffset; lineCount > 0; lineCount--) {
// Get the first non-whitespace char on the current line
int firstNonWhitePos = LineDoreplacedentUtils.getLineFirstNonWhitespace(doc, offset);
// If there is any, check wheter it's the line-comment-chars and remove them
if (firstNonWhitePos != -1) {
if (LineDoreplacedentUtils.getLineEnd(doc, firstNonWhitePos) - firstNonWhitePos >= lineCommentStringLen) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, firstNonWhitePos, lineCommentStringLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, lineCommentString)) {
doc.remove(firstNonWhitePos, lineCommentStringLen);
}
}
}
offset = getNexLineOffset(doc, offset);
}
}
18
Source : ToggleBlockCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private boolean isInComment(Doreplacedent doc, CommentHandler commentHandler, int offset) {
// shared instance, low cost
CharSequence text = DoreplacedentUtilities.getText(doc);
int lastCommentStartIndex = CharSequenceUtilities.lastIndexOf(text, commentHandler.getCommentStartDelimiter(), offset);
int lastCommentEndIndex = CharSequenceUtilities.lastIndexOf(text, commentHandler.getCommentEndDelimiter(), offset);
return lastCommentStartIndex > -1 && (lastCommentStartIndex > lastCommentEndIndex || lastCommentEndIndex == -1 || lastCommentEndIndex == offset);
}
18
Source : EmbeddedSectionsHighlighting.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static boolean isWhitespace(Doreplacedent doreplacedent, int startOffset, int endOffset) throws BadLocationException {
int docLen = doreplacedent.getLength();
replacedert startOffset >= 0;
replacedert startOffset <= docLen;
replacedert endOffset >= 0;
replacedert endOffset <= docLen;
replacedert endOffset >= startOffset;
CharSequence chars = DoreplacedentUtilities.getText(doreplacedent, startOffset, endOffset - startOffset);
for (int i = 0; i < chars.length(); i++) {
if (!Character.isWhitespace(chars.charAt(i))) {
return false;
}
}
return true;
}
17
Source : Utils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static List<TextEdit> computeDefaultOnTypeIndent(Doreplacedent doc, int changeStart, Position startPos, String newText) {
List<TextEdit> edits = new ArrayList<>();
try {
int indentLevel = IndentUtils.indentLevelSize(doc);
int lineStart = IndentUtils.lineStartOffset(doc, changeStart);
int indent = IndentUtils.lineIndent(doc, lineStart);
if (newText.equals("}") && indent == changeStart - lineStart) {
CharSequence cs = DoreplacedentUtilities.getText(doc);
int balance = 1;
int idx = changeStart - 1;
while (idx >= 0 && balance > 0) {
switch(cs.charAt(idx)) {
case '{':
balance--;
break;
case '}':
balance++;
break;
}
idx--;
}
int newIndent;
if (balance == 0) {
newIndent = IndentUtils.lineIndent(doc, IndentUtils.lineStartOffset(doc, idx));
} else {
newIndent = 0;
}
edits.add(new TextEdit(new Range(new Position(startPos.getLine(), 0), new Position(startPos.getLine(), indent)), IndentUtils.createIndentString(doc, newIndent)));
} else if (newText.equals("\n")) {
Position insertPos = new Position(startPos.getLine() + 1, 0);
int newIndent = indent;
if (changeStart > 0 && DoreplacedentUtilities.getText(doc, changeStart - 1, 1).charAt(0) == '{') {
newIndent += indentLevel;
}
edits.add(new TextEdit(new Range(insertPos, insertPos), IndentUtils.createIndentString(doc, newIndent)));
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
return edits;
}
17
Source : ToggleCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private boolean isCommentedLine(BaseDoreplacedent doc, String mimeType, int offset) throws BadLocationException {
Feature feature = null;
boolean suffixCommentOk = false;
boolean prefixCommentOk = false;
try {
Language language = LanguagesManager.getDefault().getLanguage(mimeType);
feature = language.getFeatureList().getFeature(CodeCommentAction.COMMENT_LINE);
} catch (LanguageDefinitionNotFoundException e) {
}
if (feature != null) {
// NOI18N
String prefix = (String) feature.getValue("prefix");
if (prefix == null) {
return true;
}
// NOI18N
String suffix = (String) feature.getValue("suffix");
if (suffix != null) {
int lastNonWhitePos = Utilities.getRowLastNonWhite(doc, offset);
if (lastNonWhitePos != -1) {
int commentLen = suffix.length();
if (lastNonWhitePos - Utilities.getRowStart(doc, offset) >= commentLen) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, lastNonWhitePos - commentLen + 1, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, suffix)) {
suffixCommentOk = true;
}
}
}
} else {
suffixCommentOk = true;
}
int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
if (firstNonWhitePos != -1) {
int commentLen = prefix.length();
if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= prefix.length()) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, firstNonWhitePos, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, prefix)) {
prefixCommentOk = true;
}
}
}
return prefixCommentOk && suffixCommentOk;
} else {
return true;
}
}
17
Source : ToggleCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void uncommentLine(BaseDoreplacedent doc, String mimeType, int offset) throws BadLocationException {
Feature feature = null;
try {
Language language = LanguagesManager.getDefault().getLanguage(mimeType);
feature = language.getFeatureList().getFeature(CodeCommentAction.COMMENT_LINE);
} catch (LanguageDefinitionNotFoundException e) {
}
if (feature != null) {
// NOI18N
String prefix = (String) feature.getValue("prefix");
if (prefix == null) {
return;
}
// NOI18N
String suffix = (String) feature.getValue("suffix");
if (suffix != null) {
int lastNonWhitePos = Utilities.getRowLastNonWhite(doc, offset);
if (lastNonWhitePos != -1) {
int commentLen = suffix.length();
if (lastNonWhitePos - Utilities.getRowStart(doc, offset) >= commentLen) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, lastNonWhitePos - commentLen + 1, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, suffix)) {
doc.remove(lastNonWhitePos - commentLen + 1, commentLen);
}
}
}
}
int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
if (firstNonWhitePos != -1) {
int commentLen = prefix.length();
if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= prefix.length()) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, firstNonWhitePos, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, prefix)) {
doc.remove(firstNonWhitePos, commentLen);
}
}
}
}
}
17
Source : CodeUncommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void modifyLine(BaseDoreplacedent doc, String mimeType, int offset) throws BadLocationException {
Feature feature = null;
try {
Language language = LanguagesManager.getDefault().getLanguage(mimeType);
feature = language.getFeatureList().getFeature(CodeCommentAction.COMMENT_LINE);
} catch (LanguageDefinitionNotFoundException e) {
}
if (feature != null) {
// NOI18N
String prefix = (String) feature.getValue("prefix");
if (prefix == null) {
return;
}
// NOI18N
String suffix = (String) feature.getValue("suffix");
if (suffix != null) {
int lastNonWhitePos = Utilities.getRowLastNonWhite(doc, offset);
if (lastNonWhitePos != -1) {
int commentLen = suffix.length();
if (lastNonWhitePos - Utilities.getRowStart(doc, offset) >= commentLen) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, lastNonWhitePos - commentLen + 1, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, suffix)) {
doc.remove(lastNonWhitePos - commentLen + 1, commentLen);
}
}
}
}
int firstNonWhitePos = Utilities.getRowFirstNonWhite(doc, offset);
if (firstNonWhitePos != -1) {
int commentLen = prefix.length();
if (Utilities.getRowEnd(doc, firstNonWhitePos) - firstNonWhitePos >= prefix.length()) {
CharSequence maybeLineComment = DoreplacedentUtilities.getText(doc, firstNonWhitePos, commentLen);
if (CharSequenceUtilities.textEquals(maybeLineComment, prefix)) {
doc.remove(firstNonWhitePos, commentLen);
}
}
}
}
}
17
Source : Abbrev.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public String getExpandString() {
BaseDoreplacedent doc = (BaseDoreplacedent) editorUI.getDoreplacedent();
String abbrevStr = getAbbrevString();
int abbrevStrLen = abbrevStr.length();
Object expansion = translateAbbrev(abbrevStr);
Caret caret = editorUI.getComponent().getCaret();
int dotPos = caret.getDot();
if (abbrevStr != null && expansion != null && dotPos >= abbrevStrLen) {
if (checkDocText) {
try {
CharSequence prevChars = DoreplacedentUtilities.getText(doc, dotPos - abbrevStrLen, abbrevStrLen);
if (CharSequenceUtilities.textEquals(prevChars, abbrevStr)) {
// abbrev chars really match text
if (!checkTextDelimiter || dotPos == abbrevStrLen || resetAcceptor.accept(doc.getChars(dotPos - abbrevStrLen - 1, 1)[0])) {
return abbrevStr;
}
}
} catch (BadLocationException e) {
}
}
}
return null;
}
17
Source : DefaultEditorCharacterServices.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Override
public int getIdentifierEnd(Doreplacedent doc, int offset, boolean backward) {
DoreplacedentCharacterAcceptor characterAcceptor = DoreplacedentCharacterAcceptor.get(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
if (backward) {
while (--offset >= 0 && characterAcceptor.isIdentifier(docText.charAt(offset))) {
}
return offset + 1;
} else {
int docTextLen = docText.length();
while (offset < docTextLen && characterAcceptor.isIdentifier(docText.charAt(offset))) {
offset++;
}
return offset;
}
}
17
Source : LineDocumentUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Get the last non-white character on the line. The doreplacedent.isWhitespace()
* is used to test whether the particular character is white space or not.
*
* @param doc doreplacedent to operate on
* @param offset position in doreplacedent anywhere on the line
* @return position of the last non-white char on the line or -1 if there's
* no non-white character on that line.
*/
public static int getLineLastNonWhitespace(@NonNull LineDoreplacedent doc, int offset) throws BadLocationException {
checkOffsetValid(doc, offset);
CharClreplacedifier clreplacedifier = getValidClreplacedifier(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
Element lineElement = doc.getParagraphElement(offset);
return TextSearchUtils.getPreviousNonWhitespace(docText, clreplacedifier, lineElement.getEndOffset() - 1, lineElement.getStartOffset());
}
17
Source : HyperlinkImpl.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public int[] getHyperlinkSpan(Doreplacedent doc, int offset, HyperlinkType type) {
if (!(doc instanceof BaseDoreplacedent)) {
return null;
}
try {
BaseDoreplacedent bdoc = (BaseDoreplacedent) doc;
int start = Utilities.getRowStart(bdoc, offset);
int end = Utilities.getRowEnd(bdoc, offset);
for (int[] span : Parser.recognizeURLs(DoreplacedentUtilities.getText(doc, start, end - start))) {
if (span[0] + start <= offset && offset <= span[1] + start) {
return new int[] { span[0] + start, span[1] + start };
}
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
17
Source : ToggleBlockCommentAction.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private int findCommentStart(LineDoreplacedent doc, CommentHandler handler, int offsetFrom, int offsetTo) throws BadLocationException {
int from = LineDoreplacedentUtils.getNextNonWhitespace(doc, offsetFrom, offsetTo);
if (from == -1) {
return offsetFrom;
}
String startDelim = handler.getCommentStartDelimiter();
if (CharSequenceUtilities.equals(DoreplacedentUtilities.getText(doc).subSequence(from, Math.min(offsetTo, from + startDelim.length())), startDelim)) {
return from;
}
return offsetFrom;
}
16
Source : HighlightsViewUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
static View breakView(int axis, int breakPartStartOffset, float x, float len, HighlightsView fullView, int partShift, int partLength, TextLayout partTextLayout) {
if (axis == View.X_AXIS) {
DoreplacedentView docView = fullView.getDoreplacedentView();
// [TODO] Should check for RTL text
replacedert (partTextLayout != null) : "Null partTextLayout";
if (docView != null && partLength > 1) {
// The logic
int fullViewStartOffset = fullView.getStartOffset();
int partStartOffset = fullViewStartOffset + partShift;
if (breakPartStartOffset - partStartOffset < 0 || breakPartStartOffset - partStartOffset > partLength) {
throw new IllegalArgumentException(// NOI18N
"offset=" + breakPartStartOffset + "partStartOffset=" + // NOI18N
partStartOffset + ", partLength=" + // NOI18N
partLength);
}
// Compute charIndex relative to given textLayout
int breakCharIndex = breakPartStartOffset - partStartOffset;
replacedert (breakCharIndex >= 0);
float breakCharIndexX;
if (breakCharIndex != 0) {
TextHitInfo hit = TextHitInfo.leading(breakCharIndex);
float[] locs = partTextLayout.getCaretInfo(hit);
breakCharIndexX = locs[0];
} else {
breakCharIndexX = 0f;
}
TextHitInfo hitInfo = x2Index(partTextLayout, breakCharIndexX + len);
// Check that the width is not too wide
float[] locs = partTextLayout.getCaretInfo(hitInfo);
float endX = locs[0];
if (endX - breakCharIndexX > len) {
if (hitInfo.getCharIndex() > 0) {
hitInfo = TextHitInfo.leading(hitInfo.getCharIndex() - 1);
}
}
int breakPartEndOffset = partStartOffset + hitInfo.getCharIndex();
if (breakPartEndOffset > breakPartStartOffset) {
// Now perform corrections if wrapping at word boundaries is required
if (docView.op.getLineWrapType() == LineWrapType.WORD_BOUND) {
CharSequence paragraph = DoreplacedentUtilities.getText(docView.getDoreplacedent()).subSequence(breakPartStartOffset, partStartOffset + partLength);
/* Don't enable allowWhitespaceBeyondEnd if we are printing the line
continuation character
(see DoreplacedentViewOp.getLineContinuationCharTextLayout), since the latter
would usually then end up beyond the edge of the editor viewport. */
boolean allowWhitespaceBeyondEnd = !docView.op.isNonPrintableCharactersVisible();
breakPartEndOffset = adjustBreakOffsetToWord(paragraph, breakPartEndOffset - breakPartStartOffset, allowWhitespaceBeyondEnd) + breakPartStartOffset;
}
}
// Length must be > 0; BTW TextLayout can't be constructed with empty string.
boolean doNotBreak = // No need to split the line in two if the first part would be empty.
(breakPartEndOffset - breakPartStartOffset == 0) || // No need to split the line in two if the second part would be empty.
(breakPartEndOffset - breakPartStartOffset >= partLength);
// if (ViewHierarchyImpl.BUILD_LOG.isLoggable(Level.FINE)) {
// ViewHierarchyImpl.BUILD_LOG.fine("HV.breakView(): <" + partStartOffset + // NOI18N
// "," + (partStartOffset+partLength) + // NOI18N
// "> => <" + breakPartStartOffset + "," + (partStartOffset+breakPartEndOffset) + // NOI18N
// ">, x=" + x + ", len=" + len + // NOI18N
// ", charIndexX=" + breakCharIndexX + "\n"); // NOI18N
// }
if (doNotBreak) {
return null;
}
return new HighlightsViewPart(fullView, breakPartStartOffset - fullViewStartOffset, breakPartEndOffset - breakPartStartOffset);
}
}
return null;
}
16
Source : DocUtils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Transpose letter at offset with the next one at offset+1.
* @param doc non-null doreplacedent that should be write-locked.
* @param offset
* @return true if succeeded or false when at end of doc.
*/
public static boolean transposeLetters(@NonNull Doreplacedent doc, int offset) {
if (offset >= 0 && offset <= doc.getLength() - 2) {
CharSequence text = DoreplacedentUtilities.getText(doc);
char ch = text.charAt(offset);
try {
doc.remove(offset, 1);
doc.insertString(offset + 1, String.valueOf(ch), null);
} catch (BadLocationException ex) {
LOG.log(Level.FINE, null, ex);
Toolkit.getDefaultToolkit().beep();
}
return true;
}
return false;
}
16
Source : TrailingWhitespaceRemoveTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void checkNoTrailingWhitespace(Doreplacedent doc) {
Element lineRoot = DoreplacedentUtilities.getParagraphRootElement(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
for (int i = 0; i < lineRoot.getElementCount(); i++) {
Element lineElem = lineRoot.getElement(i);
int lineLastOffset = lineElem.getEndOffset() - 2;
if (lineLastOffset >= lineElem.getStartOffset()) {
// At least one non newline char
switch(docText.charAt(lineLastOffset)) {
case ' ':
case '\t':
throw new IllegalStateException(// NOI18N
"Trailing whitespace exists at lineIndex=" + i + ", lineStartOffset=" + // NOI18N
lineElem.getStartOffset() + ", lineEndOffset=" + // NOI18N
lineElem.getEndOffset() + '\n' + dumpLines(null, doc));
}
}
}
}
16
Source : Context.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Modify indent of the line at the offset preplaceded as the parameter.
*
* @param lineStartOffset start offset of a line where the indent is being modified.
* @param newIndent new indent as a number of spaces. The method will possibly use tabs
* according to the indentation settings for the given doreplacedent.
* @throws javax.swing.text.BadLocationException if the given lineStartOffset is not within
* corresponding doreplacedent's bounds.
*/
public void modifyIndent(int lineStartOffset, int newIndent) throws BadLocationException {
Doreplacedent doc = doreplacedent();
IndentImpl.checkOffsetInDoreplacedent(doc, lineStartOffset);
// Determine old indent first together with oldIndentEndOffset
int indent = 0;
int tabSize = -1;
CharSequence docText = DoreplacedentUtilities.getText(doc);
int oldIndentEndOffset = lineStartOffset;
while (oldIndentEndOffset < docText.length()) {
char ch = docText.charAt(oldIndentEndOffset);
if (ch == '\n') {
break;
} else if (ch == '\t') {
if (tabSize == -1)
tabSize = IndentUtils.tabSize(doc);
// Round to next tab stop
indent = (indent + tabSize) / tabSize * tabSize;
} else if (Character.isWhitespace(ch)) {
indent++;
} else {
// non-whitespace
break;
}
oldIndentEndOffset++;
}
String newIndentString = IndentUtils.createIndentString(doc, newIndent);
modifyIndent(lineStartOffset, oldIndentEndOffset - lineStartOffset, newIndentString);
}
16
Source : CodeTemplatesPanel.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void saveCurrentTemplate() {
if (unsavedTemplateIndex < 0) {
return;
}
CodeTemplatesModel.TM tableModel = (CodeTemplatesModel.TM) tTemplates.getModel();
// Don't use JEditorPane.getText(), because it goes through EditorKit.write()
// and performs conversion as if the text was written to a file (eg. EOL
// translations). See #130095 for details.
try {
tableModel.setDescription(unsavedTemplateIndex, CharSequenceUtilities.toString(DoreplacedentUtilities.getText(epDescription.getDoreplacedent(), 0, epDescription.getDoreplacedent().getLength())));
tableModel.setText(unsavedTemplateIndex, CharSequenceUtilities.toString(DoreplacedentUtilities.getText(epExpandedText.getDoreplacedent(), 0, epExpandedText.getDoreplacedent().getLength())));
unsavedTemplateIndex = -1;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
firePropertyChange(OptionsPanelController.PROP_CHANGED, null, null);
}
15
Source : HighlightsView.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
TextLayout createPartTextLayout(int shift, int length) {
checkTextLayoutValid();
if (breakInfo == null) {
breakInfo = new TextLayoutBreakInfo(textLayout.getCharacterCount());
}
TextLayout partTextLayout = breakInfo.findPartTextLayout(shift, length);
if (partTextLayout == null) {
DoreplacedentView docView = getDoreplacedentView();
Doreplacedent doc = docView.getDoreplacedent();
CharSequence docText = DoreplacedentUtilities.getText(doc);
int startOffset = getStartOffset();
String text = docText.subSequence(startOffset + shift, startOffset + shift + length).toString();
if (docView.op.isNonPrintableCharactersVisible()) {
text = text.replace(' ', DoreplacedentViewOp.PRINTING_SPACE);
}
AttributeSet attrs = ViewUtils.getFirstAttributes(getAttributes());
Font font = ViewUtils.getFont(attrs, docView.op.getDefaultFont());
partTextLayout = docView.op.createTextLayout(text, font);
breakInfo.add(shift, length, partTextLayout);
}
return partTextLayout;
}
15
Source : TrailingWhitespaceRemoveTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static void removeTrailingWhitespace(Doreplacedent doc) throws Exception {
Element lineRoot = DoreplacedentUtilities.getParagraphRootElement(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
int lineCount = lineRoot.getElementCount();
for (int i = 0; i < lineCount; i++) {
Element lineElem = lineRoot.getElement(i);
int lineStartOffset = lineElem.getStartOffset();
int lineLastOffset = lineElem.getEndOffset() - 1;
int offset;
for (offset = lineLastOffset - 1; offset >= lineStartOffset; offset--) {
char c = docText.charAt(offset);
// Currently only remove ' ' and '\t' - may be revised
if (c != ' ' && c != '\t') {
break;
}
}
// Increase offset (either below lineStartOffset or on non-white char)
offset++;
if (offset < lineLastOffset) {
doc.remove(offset, lineLastOffset - offset);
}
}
}
15
Source : Context.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Modify indent of the line at the offset preplaceded as the parameter, by stripping the given
* number of input characters and inserting the given indent.
*
* @param lineStartOffset start offset of a line where the indent is being modified.
* @param oldIndentCharCount number of characters to remove.
* @param newIndent new indent.
* @throws javax.swing.text.BadLocationException if the given lineStartOffset is not within
* corresponding doreplacedent's bounds.
* @since 1.49
*/
public void modifyIndent(int lineStartOffset, int oldIndentCharCount, String newIndent) throws BadLocationException {
Doreplacedent doc = doreplacedent();
IndentImpl.checkOffsetInDoreplacedent(doc, lineStartOffset);
CharSequence docText = DoreplacedentUtilities.getText(doc);
int oldIndentEndOffset = lineStartOffset + oldIndentCharCount;
// Attempt to match the begining characters
int offset = lineStartOffset;
for (int i = 0; i < newIndent.length() && lineStartOffset + i < oldIndentEndOffset; i++) {
if (newIndent.charAt(i) != docText.charAt(lineStartOffset + i)) {
offset = lineStartOffset + i;
newIndent = newIndent.substring(i);
break;
}
}
// Replace the old indent
if (!doc.getText(offset, oldIndentEndOffset - offset).equals(newIndent)) {
if (offset < oldIndentEndOffset) {
doc.remove(offset, oldIndentEndOffset - offset);
}
if (newIndent.length() > 0) {
doc.insertString(offset, newIndent, null);
}
}
}
15
Source : EditorDocumentContentTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testSimplePositionSharingMods() throws Exception {
RandomTestContainer container = createContainer();
RandomTestContainer.Context context = container.context();
DoreplacedentContentTesting.insert(context, 0, "ahoj");
Position pos = DoreplacedentContentTesting.createPosition(context, 1);
Position pos1 = DoreplacedentContentTesting.createPosition(context, 1);
// Positions are shared
replacedertSame(pos, pos1);
Position pos2 = DoreplacedentContentTesting.createPosition(context, 2);
DoreplacedentContentTesting.remove(context, 1, 1);
Position pos11 = DoreplacedentContentTesting.createPosition(context, 1);
// Reuse last position among ones with the same offset
replacedertSame(pos2, pos11);
DoreplacedentContentTesting.insert(context, 1, "b");
// Check subsequences correctness
Doreplacedent doc = DoreplacedentContentTesting.getDoreplacedent(container);
CharSequence docText = DoreplacedentUtilities.getText(doc);
CharSequence txt1 = docText.subSequence(0, 3);
replacedertEquals('a', txt1.charAt(0));
replacedertEquals('b', txt1.charAt(1));
replacedertEquals('o', txt1.charAt(2));
replacedertEquals("abo", txt1.toString());
CharSequence subTxt1 = txt1.subSequence(1, 3);
replacedertEquals("bo", subTxt1.toString());
CharSequence subTxt2 = txt1.subSequence(0, 1);
replacedertEquals("a", subTxt2.toString());
CharSequence txt2 = docText.subSequence(0, 1);
replacedertEquals('a', txt2.charAt(0));
replacedertEquals("a", txt2.toString());
CharSequence txt3 = docText.subSequence(2, 3);
replacedertEquals('o', txt3.charAt(0));
replacedertEquals("o", txt3.toString());
Position pos111 = DoreplacedentContentTesting.createPosition(context, 1);
replacedertNotSame(pos2, pos111);
DoreplacedentContentTesting.undo(context, 1);
container.runChecks(context);
}
15
Source : LineRootElement.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void insertUpdate(DoreplacedentEvent evt, UndoableEdit edit, AttributeSet attr) {
int insertOffset = evt.getOffset();
int insertEndOffset = insertOffset + evt.getLength();
CharSequence text = DoreplacedentUtilities.getText(doc);
if (insertOffset > 0) {
// [Swing] marks (and elements) at offset zero do not move up
insertOffset--;
}
try {
// Index of the elements modification - computed lazily
int index = -1;
// Collected added lines
List<LineElement> addedLines = null;
// Removed line element
LineElement removedLine = null;
Position lastAddedLineEndPos = null;
for (int offset = insertOffset; offset < insertEndOffset; offset++) {
if (text.charAt(offset) == '\n') {
if (index == -1) {
// Not computed yet
index = getElementIndex(offset);
removedLine = (LineElement) getElement(index);
lastAddedLineEndPos = removedLine.getStartPosition();
addedLines = new ArrayList<LineElement>(2);
}
Position lineEndPos = doc.createPosition(offset + 1);
addedLines.add(new LineElement(this, lastAddedLineEndPos, lineEndPos));
lastAddedLineEndPos = lineEndPos;
}
}
if (index != -1) {
// Some lines were added
// If the text was inserted at the line boundary i.e. right after existing '\n'
// and the ending char of the inserted text was not '\n' (otherwise
// it would be a "clean" line insert) then there must be two line elements
// removed.
Position removedLineEndPos = removedLine.getEndPosition();
int removedLineEndOffset = removedLineEndPos.getOffset();
// removed line elements
Element[] removed;
int lastAddedLineEndOffset = lastAddedLineEndPos.getOffset();
if (insertEndOffset == removedLineEndOffset && lastAddedLineEndOffset != removedLineEndOffset) // && index + 1 < getElementCount()
{
LineElement removedLine2 = (LineElement) getElement(index + 1);
removed = new Element[] { removedLine, removedLine2 };
removedLineEndPos = removedLine2.getEndPosition();
removedLineEndOffset = removedLineEndPos.getOffset();
} else {
// just one line removed
removed = new Element[] { removedLine };
}
if (lastAddedLineEndOffset < removedLineEndOffset) {
addedLines.add(new LineElement(this, lastAddedLineEndPos, removedLineEndPos));
}
Element[] added = new Element[addedLines.size()];
addedLines.toArray(added);
edit.addEdit(new Edit(index, removed, added));
replace(index, removed.length, added);
}
} catch (BadLocationException e) {
throw new IllegalStateException(e.toString());
}
}
14
Source : DocumentFinder.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static FindReplaceResult findReplaceImpl(String replaceText, Doreplacedent doc, int startOffset, int endOffset, Map<String, Object> props, boolean oppositeDir) throws BadLocationException {
int[] ret = new int[2];
if (endOffset == -1) {
endOffset = doc.getLength();
}
DocFinder finder = null;
try {
finder = getFinder(doc, props, oppositeDir, false);
} catch (PatternSyntaxException pse) {
FindReplaceResult findReplaceResult = new FindReplaceResult(new int[] { -1, -1 }, "");
findReplaceResult.setErrorMsg(NbBundle.getMessage(DoreplacedentFinder.clreplaced, "pattern-error-dialog-content") + " " + pse.getDescription());
return findReplaceResult;
}
if (finder == null) {
return null;
}
finder.reset();
Boolean b = (Boolean) props.get(EditorFindSupport.FIND_BACKWARD_SEARCH);
boolean back = (b != null && b.booleanValue());
if (oppositeDir) {
back = !back;
}
b = (Boolean) props.get(EditorFindSupport.FIND_BLOCK_SEARCH);
boolean blockSearch = (b != null && b.booleanValue());
Position blockStartPos = (Position) props.get(EditorFindSupport.FIND_BLOCK_SEARCH_START);
int blockSearchStartOffset = (blockStartPos != null) ? blockStartPos.getOffset() : 0;
if (blockSearchStartOffset > doc.getLength()) {
blockSearchStartOffset = 0;
}
Position pos = (Position) props.get(EditorFindSupport.FIND_BLOCK_SEARCH_END);
int blockSearchEndOffset = (pos != null) ? pos.getOffset() : doc.getLength();
if (blockSearchEndOffset > doc.getLength()) {
blockSearchEndOffset = doc.getLength();
}
if (blockSearchStartOffset > blockSearchEndOffset) {
LOG.log(Level.WARNING, "end=" + blockSearchEndOffset + " < start=" + blockSearchStartOffset);
// Changing places start and end block position
int tmp = blockSearchStartOffset;
blockSearchStartOffset = blockSearchEndOffset;
blockSearchEndOffset = tmp;
}
// exclude the artificial last \n
CharSequence docText = DoreplacedentUtilities.getText(doc).subSequence(0, doc.getLength());
CharSequence blockText = blockSearch ? docText.subSequence(blockSearchStartOffset, blockSearchEndOffset) : docText;
int initOffset;
if (blockSearch && endOffset < startOffset) {
int temp = endOffset;
endOffset = startOffset;
startOffset = temp;
}
if (blockSearch) {
if (back) {
initOffset = endOffset - startOffset;
} else {
initOffset = startOffset - blockSearchStartOffset;
}
} else {
if (back) {
initOffset = oppositeDir ? startOffset : endOffset;
} else {
initOffset = startOffset;
}
}
if (initOffset < 0 || initOffset > blockText.length()) {
LOG.log(Level.INFO, "Index: " + initOffset + "\nOffset: " + startOffset + "-" + endOffset + "\nBlock: " + blockSearchStartOffset + "-" + blockSearchEndOffset + "\nLength : " + blockText.length());
initOffset = Math.max(initOffset, 0);
initOffset = Math.min(initOffset, blockText.length());
}
int findRet = finder.find(initOffset, blockText);
if (!finder.isFound()) {
ret[0] = -1;
return new FindReplaceResult(ret, replaceText);
}
if (blockSearch) {
ret[0] = blockSearchStartOffset + findRet;
} else {
ret[0] = findRet;
}
if (finder instanceof StringFinder) {
int length = ((StringFinder) finder).getFoundLength();
ret[1] = ret[0] + length;
}
if (finder instanceof RegExpFinder) {
Matcher matcher = ((RegExpFinder) finder).getMatcher();
if (matcher != null && replaceText != null) {
CharSequence foundString = docText.subSequence(ret[0], ret[1]);
matcher.reset(foundString);
if (matcher.find()) {
try {
replaceText = matcher.replaceFirst(convertStringForMatcher(replaceText));
} catch (IndexOutOfBoundsException | IllegalArgumentException ioobe) {
// NOI18N
String additionalHint = "";
if (ioobe instanceof IllegalArgumentException) {
// NOI18N
additionalHint = "\n" + NbBundle.getMessage(DoreplacedentFinder.clreplaced, "pattern-error-missing-escape-hint");
}
FindReplaceResult findReplaceResult = new FindReplaceResult(new int[] { -1, -1 }, "");
findReplaceResult.setErrorMsg(NbBundle.getMessage(DoreplacedentFinder.clreplaced, "pattern-error-dialog-content") + " " + ioobe.getLocalizedMessage() + additionalHint);
return findReplaceResult;
}
}
}
}
return new FindReplaceResult(ret, replaceText);
}
14
Source : TrailingWhitespaceRemoveTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static StringBuilder dumpLines(StringBuilder sb, Doreplacedent doc) {
if (sb == null)
sb = new StringBuilder(doc.getLength() + 200);
Element lineRoot = DoreplacedentUtilities.getParagraphRootElement(doc);
CharSequence docText = DoreplacedentUtilities.getText(doc);
int lineCount = lineRoot.getElementCount();
sb.append(lineCount).append(" doreplacedent lines:\n");
for (int i = 0; i < lineCount; i++) {
Element lineElem = lineRoot.getElement(i);
int startOffset = lineElem.getStartOffset();
int endOffset = lineElem.getEndOffset();
ArrayUtilities.appendBracketedIndex(sb, i, 2);
sb.append('<').append(startOffset).append(',').append(endOffset).append("> \"");
while (startOffset < endOffset) {
CharSequenceUtilities.debugChar(sb, docText.charAt(startOffset++));
}
sb.append("\"\n");
}
return sb;
}
14
Source : LineRootElement.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
UndoableEdit insertUpdate(int insertOffset, int insertLength) {
int lastInsertedCharOffset = insertOffset + insertLength - 1;
CharSequence text = DoreplacedentUtilities.getText(doc);
Edit edit = null;
// Index of the elements modification
int index = -1;
// Removed line elements
Element[] removeElements = null;
// Index in the addedLines array - adding from last to first
// nothing added yet
int firstAddedLineIndex = addedLines.length;
int offset = lastInsertedCharOffset;
// insertAtPrevLineEndOffset - whether the insert was done at the end (after '\n')
// of a previous line i.e. in fact at a begining of the next line.
boolean insertAtPrevLineEndOffset;
// in fact Math.max(insertOffset - 1, 0)
int beforeInsertOffset;
if (insertOffset == 0) {
// [swing] marks (and elements) at offset zero do not move up
beforeInsertOffset = 0;
insertAtPrevLineEndOffset = false;
} else {
// inserting inside doc
// check char before offset for '\n'
beforeInsertOffset = insertOffset - 1;
insertAtPrevLineEndOffset = (text.charAt(beforeInsertOffset) == '\n');
}
try {
// Go through all the inserted lines plus the char at beforeInsertOffset (if exists)
// and create new line elements at every occurrence of '\n'
Position futureAddedLineEndPos = null;
while (offset >= beforeInsertOffset) {
if (text.charAt(offset) == '\n') {
// line break at offset
// whether line element should be added
boolean addLine = true;
if (futureAddedLineEndPos == null) {
// Find the first line element that will be removed
index = getElementIndex(insertOffset);
LineElement removeLine = (LineElement) getElement(index);
// If inserting at begining of line (insertAtPrevLineEndOffset == true)
// and the inserted chars do not end with '\n'
// then not only current line must be removed
// but the next one as well.
if (insertAtPrevLineEndOffset) {
// '\n' at (insertOffset - 1)
if (offset == lastInsertedCharOffset) {
// inserted 'xxx\n'
removeElements = new Element[] { removeLine };
futureAddedLineEndPos = removeLine.getEndPosition();
// do not add new line in this case
addLine = false;
} else {
LineElement nextRemoveLine = (LineElement) getElement(index + 1);
removeElements = new Element[] { removeLine, nextRemoveLine };
futureAddedLineEndPos = nextRemoveLine.getEndPosition();
}
} else {
// otherwise use the next element as the next for added
removeElements = new Element[] { removeLine };
futureAddedLineEndPos = removeLine.getEndPosition();
}
}
if (addLine) {
if (firstAddedLineIndex == 0) {
// no more space to add
firstAddedLineIndex = doubleAddedLinesCapacity();
}
// will fill in added line element soon
firstAddedLineIndex--;
Position lineStartPos = doc.createPosition(offset + 1);
addedLines[firstAddedLineIndex] = new LineElement(this, lineStartPos, futureAddedLineEndPos);
futureAddedLineEndPos = lineStartPos;
}
}
offset--;
}
if (futureAddedLineEndPos != null) {
// will add (and remove) lines
// Create array of added lines and add extra one at begining
int addedLineCount = addedLines.length - firstAddedLineIndex;
Element[] addElements = new Element[addedLineCount + 1];
System.arraycopy(addedLines, firstAddedLineIndex, addElements, 1, addedLineCount);
addElements[0] = new LineElement(this, ((LineElement) removeElements[0]).getStartPosition(), futureAddedLineEndPos);
replace(index, removeElements.length, addElements);
edit = new Edit(index, removeElements, addElements);
}
} catch (BadLocationException e) {
// Should never happen but in case it happens
// retain the current consistent state (no replace is done)
// and report this as serious error
ErrorManager.getDefault().notify(ErrorManager.ERROR, e);
}
// checkConsistency();
return edit;
}
14
Source : MulticaretHandler.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
void release() {
String firstRegionText = getFirstRegionText();
if (firstRegionText != null) {
int regionCount = regions.size();
for (int i = 1; i < regionCount; i++) {
MutablePositionRegion region = regions.get(i);
int offset = region.getStartOffset();
int length = region.getEndOffset() - offset;
try {
final CharSequence old = DoreplacedentUtilities.getText(doc, offset, length);
if (!CharSequenceUtilities.textEquals(firstRegionText, old)) {
int res = -1;
for (int k = 0; k < Math.min(old.length(), firstRegionText.length()); k++) {
if (old.charAt(k) == firstRegionText.charAt(k)) {
res = k;
} else {
break;
}
}
String insert = firstRegionText.substring(res + 1);
CharSequence remove = old.subSequence(res + 1, old.length());
if (insert.length() > 0) {
doc.insertString(offset + res + 1, insert, null);
}
if (remove.length() > 0) {
doc.remove(offset + res + 1 + insert.length(), remove.length());
}
}
} catch (BadLocationException e) {
Exceptions.printStackTrace(e);
}
}
}
}
14
Source : GsfUtilities.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Adjust the indentation of the line containing the given offset to the provided
* indentation. Returns the length difference of old and new indentation. The doreplacedent
* must support {@link LineDoreplacedent} services, otherwise {@code -1} is returned.
* <p>
* Copied from Indent module's "modifyIndent"
*
* @param doc the doreplacedent
* @param lineOffset character index into the line
* @param newIndent new indentation level
* @throws BadLocationException in case of position error
* @return old indentation, or {@code -1} if the doreplacedent is not supported.
* @since 2.65
*/
public static int setLineIndentation(Doreplacedent doc, int lineOffset, int newIndent) throws BadLocationException {
LineDoreplacedent ld = LineDoreplacedentUtils.as(doc, LineDoreplacedent.clreplaced);
if (ld == null) {
return -1;
}
int lineStartOffset;
try {
lineStartOffset = LineDoreplacedentUtils.getLineStart(ld, lineOffset);
} catch (IndexOutOfBoundsException ex) {
throw new BadLocationException(ex.getMessage(), lineOffset);
}
// Determine old indent first together with oldIndentEndOffset
int indent = 0;
int tabSize = -1;
CharSequence docText = DoreplacedentUtilities.getText(doc);
int oldIndentEndOffset = lineStartOffset;
while (oldIndentEndOffset < docText.length()) {
char ch = docText.charAt(oldIndentEndOffset);
if (ch == '\n') {
break;
} else if (ch == '\t') {
if (tabSize == -1) {
tabSize = IndentUtils.tabSize(doc);
}
// Round to next tab stop
indent = (indent + tabSize) / tabSize * tabSize;
} else if (Character.isWhitespace(ch)) {
indent++;
} else {
// non-whitespace
break;
}
oldIndentEndOffset++;
}
String newIndentString = IndentUtils.createIndentString(doc, newIndent);
// Attempt to match the begining characters
int offset = lineStartOffset;
boolean different = false;
int i = 0;
for (; i < newIndentString.length() && lineStartOffset + i < oldIndentEndOffset; i++) {
if (newIndentString.charAt(i) != docText.charAt(lineStartOffset + i)) {
offset = lineStartOffset + i;
newIndentString = newIndentString.substring(i);
different = true;
break;
}
}
if (!different) {
offset = lineStartOffset + i;
newIndentString = newIndentString.substring(i);
}
// Replace the old indent
if (offset < oldIndentEndOffset) {
doc.remove(offset, oldIndentEndOffset - offset);
}
if (newIndentString.length() > 0) {
doc.insertString(offset, newIndentString, null);
}
return newIndentString.length() - (oldIndentEndOffset - offset);
}
See More Examples