下面列出了org.eclipse.jface.text.IDocument#getLineDelimiter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Given a selection on a document, computes the lines fully or partially covered by
* <code>selection</code>. A line in the document is considered covered if
* <code>selection</code> comprises any characters on it, including the terminating delimiter.
* <p>Note that the last line in a selection is not considered covered if the selection only
* comprises the line delimiter at its beginning (that is considered part of the second last
* line).
* As a special case, if the selection is empty, a line is considered covered if the caret is
* at any position in the line, including between the delimiter and the start of the line. The
* line containing the delimiter is not considered covered in that case.
* </p>
*
* @param document the document <code>selection</code> refers to
* @param selection a selection on <code>document</code>
* @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
* @return a selection describing the range of lines (partially) covered by
* <code>selection</code>, without any terminating line delimiters
* @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
*/
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ITextViewer viewer) throws BadLocationException {
int low= document.getLineOffset(selection.getStartLine());
int endLine= selection.getEndLine();
int high= document.getLineOffset(endLine) + document.getLineLength(endLine);
// get everything up to last line without its delimiter
String delim= document.getLineDelimiter(endLine);
if (delim != null)
high -= delim.length();
// the new selection will cover the entire lines being moved, except for the last line's
// delimiter. The exception to this rule is an empty last line, which will stay covered
// including its delimiter
if (delim != null && document.getLineLength(endLine) == delim.length())
fAddDelimiter= true;
else
fAddDelimiter= false;
return new TextSelection(document, low, high - low);
}
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
IRegion match= super.findExtendedDoubleClickSelection(document, offset);
if (match != null)
return match;
try {
ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
if (offset == region.getOffset() + fHitDelta || offset == region.getOffset() + region.getLength() - fHitDelta) {
if (fLeftBorder == 0 && fRightBorder == 0)
return region;
if (fRightBorder == -1) {
String delimiter= document.getLineDelimiter(document.getLineOfOffset(region.getOffset() + region.getLength() - 1));
if (delimiter == null)
fRightBorder= 0;
else
fRightBorder= delimiter.length();
}
return new Region(region.getOffset() + fLeftBorder, region.getLength() - fLeftBorder - fRightBorder);
}
} catch (BadLocationException e) {
return null;
}
return null;
}
private void convertLineDelimiters(IDocument document) throws BadLocationException {
int lines= document.getNumberOfLines();
for (int line= 0; line < lines; line++) {
IRegion region= document.getLineInformation(line);
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null)
document.replace(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter);
}
}
@Override
protected IRegion getSelectedRegion(IDocument document, ITypedRegion completePartition) throws BadLocationException {
if (fLeftBorder == 0 && fRightBorder == 0)
return completePartition;
if (fRightBorder == -1) {
String delimiter = document.getLineDelimiter(document.getLineOfOffset(completePartition.getOffset()
+ completePartition.getLength() - 1));
if (delimiter == null)
fRightBorder = 0;
else
fRightBorder = delimiter.length();
}
return new Region(completePartition.getOffset() + fLeftBorder, completePartition.getLength() - fLeftBorder
- fRightBorder);
}
/**
* Returns the longest legal line delimiter.
* @param document IDocument
* @param command DocumentCommand
* @return the longest legal line delimiter
*/
public String getLineDelimiter(IDocument document, DocumentCommand command) {
String delimiter = "\n";
try {
delimiter = document.getLineDelimiter(0);
} catch (BadLocationException e) {
TexlipsePlugin.log("TexEditorTools.getLineDelimiter: ", e);
}
return delimiter == null ? "\n" : delimiter;
}
private ArrayList<ReplaceEdit> commentWholeLines(int startLine, int endLine, int realEndLine, IDocument doc, int offsAfter[]) throws BadLocationException {
//System.out.println("commentWholeLines " + startLine + " " + endLine);
int beg = doc.getLineOffset(startLine);
int end = doc.getLineOffset(endLine) + doc.getLineInformation(endLine).getLength();
String crlf = doc.getLineDelimiter(endLine);
if (crlf == null) crlf = ""; //$NON-NLS-1$
boolean isSingleLine = (startLine == realEndLine);
String openStr = isSingleLine ? "(*" : "(*" + crlf; //$NON-NLS-1$ //$NON-NLS-2$
String closeStr = isSingleLine ? " *)" : crlf+"*)"; //$NON-NLS-1$ //$NON-NLS-2$
ArrayList<ReplaceEdit> edits = commentRange(beg, end-beg, openStr, closeStr, offsAfter);
offsAfter[0] += crlf.length();
return edits;
}
protected List<IMarker> getMarkersFor(ISourceViewer sourceViewer, int offset) throws BadLocationException {
final IDocument document = sourceViewer.getDocument();
int line = document.getLineOfOffset(offset);
int lineOffset = document.getLineOffset(line);
String delim = document.getLineDelimiter(line);
int delimLength = delim != null ? delim.length() : 0;
int lineLength = document.getLineLength(line) - delimLength;
return getMarkersFor(sourceViewer, lineOffset, lineLength);
}
private void convertLineDelimiters(IDocument document) throws BadLocationException {
int lines= document.getNumberOfLines();
for (int line= 0; line < lines; line++) {
IRegion region= document.getLineInformation(line);
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null)
document.replace(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter);
}
}
/**
* @see com.mulgasoft.emacsplus.commands.EmacsPlusNoEditHandler#transform(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection, org.eclipse.core.commands.ExecutionEvent)
*/
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
ExecutionEvent event) throws BadLocationException {
String msg = null;
int offset = getCursorOffset(editor,currentSelection);
int docLen = document.getLength();
IRegion line = document.getLineInformationOfOffset(offset);
if (offset >= docLen) {
msg = String.format(EOB_POSITION, offset,docLen);
} else {
char curChar = document.getChar(offset);
String sChar = ""; //$NON-NLS-1$
int percent = new Float(((offset * 100) / docLen) + .5).intValue();
if (offset == line.getOffset() + line.getLength()){
String ld = document.getLineDelimiter(document.getLineOfOffset(offset));
char[] points = ld.toCharArray();
for (int i=0; i<points.length; i++) {
sChar += normalizeChar(points[i]);
}
msg = String.format(EOL_POSITION, sChar,offset,docLen,percent);
} else {
int curCode = (int) curChar;
sChar = (curChar <= ' ' ? normalizeChar(curChar) : String.valueOf(curChar));
msg = String.format(CURSOR_POSITION, sChar, curCode, curCode, curCode, offset, docLen, percent);
}
}
EmacsPlusUtils.showMessage(editor, msg, false);
setCmdResult(new Integer(offset));
return super.transform(editor, document, currentSelection, event);
}
protected final String getEol() {
IDocument document = getDocument();
if (eol == null) {
try {
if (document instanceof IDocumentExtension4) {
eol = ((IDocumentExtension4)document).getDefaultLineDelimiter();
} else {
eol = document.getLineDelimiter(0);
}
} catch (BadLocationException e) {
}
}
return eol;
}
private void setEolChars(IDocument document) {
try {
if (document instanceof IDocumentExtension4) {
eol = ((IDocumentExtension4)document).getDefaultLineDelimiter();
} else {
eol = document.getLineDelimiter(0);
}
int eolLen = eol.length();
eolcp = new int[eolLen];
for (int i=0; i<eolLen; i++) {
eolcp[i] = eol.codePointAt(i);
}
} catch (BadLocationException e) {
}
}
public static final String getEol(IDocument document) {
String eol = "\n"; //$NON-NLS-1$
try {
if (document instanceof IDocumentExtension4) {
eol = ((IDocumentExtension4)document).getDefaultLineDelimiter();
} else {
eol = document.getLineDelimiter(0);
}
} catch (BadLocationException e) {
}
return eol;
}
private int getLineDelimiterLen(IDocument doc, int line) {
try {
String lineDelimiter = doc.getLineDelimiter(line);
if (lineDelimiter == null) {
return 0;
}
return lineDelimiter.length();
} catch (BadLocationException e) {
return 0;
}
}
@Override
public void runWithEvent(Event event) {
ITextViewer viewer = getTextViewer();
if (viewer == null)
return;
if (!canModifyViewer())
return;
// get involved objects
IDocument document= viewer.getDocument();
if (document == null)
return;
StyledText widget= viewer.getTextWidget();
if (widget == null)
return;
// get selection
ITextSelection sel= (ITextSelection) viewer.getSelectionProvider().getSelection();
if (sel.isEmpty())
return;
ITextSelection skippedLine= getSkippedLine(document, sel);
if (skippedLine == null)
return;
try {
ITextSelection movingArea= getMovingSelection(document, sel, viewer);
// if either the skipped line or the moving lines are outside the widget's
// visible area, bail out
if (!containedByVisibleRegion(movingArea, viewer) || !containedByVisibleRegion(skippedLine, viewer))
return;
// get the content to be moved around: the moving (selected) area and the skipped line
String moving= movingArea.getText();
String skipped= skippedLine.getText();
if (moving == null || skipped == null || document.getLength() == 0)
return;
String delim;
String insertion;
int offset, deviation;
if (fUpwards) {
delim= document.getLineDelimiter(skippedLine.getEndLine());
if (fCopy) {
delim= TextUtilities.getDefaultLineDelimiter(document);
insertion= moving + delim;
offset= movingArea.getOffset();
deviation= 0;
} else {
Assert.isNotNull(delim);
insertion= moving + delim + skipped;
offset= skippedLine.getOffset();
deviation= -skippedLine.getLength() - delim.length();
}
} else {
delim= document.getLineDelimiter(movingArea.getEndLine());
if (fCopy) {
if (delim == null) {
delim= TextUtilities.getDefaultLineDelimiter(document);
insertion= delim + moving;
} else {
insertion= moving + delim;
}
offset= skippedLine.getOffset();
deviation= movingArea.getLength() + delim.length();
} else {
Assert.isNotNull(delim);
insertion= skipped + delim + moving;
offset= movingArea.getOffset();
deviation= skipped.length() + delim.length();
}
}
// modify the document
beginCompoundEdit();
if (fCopy) {
document.replace(offset, 0, insertion);
} else {
document.replace(offset, insertion.length(), insertion);
}
// move the selection along
int selOffset= movingArea.getOffset() + deviation;
int selLength= movingArea.getLength() + (fAddDelimiter ? delim.length() : 0);
if (! (viewer instanceof ITextViewerExtension5))
selLength= Math.min(selLength, viewer.getVisibleRegion().getOffset() + viewer.getVisibleRegion().getLength() - selOffset);
else {
// TODO need to check what is necessary in the projection case
}
selectAndReveal(viewer, selOffset, selLength);
} catch (BadLocationException x) {
// won't happen without concurrent modification - bail out
return;
}
}
private int getLineDelimiterLength(IDocument document, int line) throws BadLocationException {
String lineDelimiter= document.getLineDelimiter(line);
return lineDelimiter != null ? lineDelimiter.length() : 0;
}
/**
* This method does actual wrapping...
* @throws BadLocationException
*/
private void doWrap(TexSelections selection) throws BadLocationException {
boolean itemFound = false;
IDocument document = selection.getDocument();
//selection.selectCompleteLines();
selection.selectParagraph();
String delimiter = document.getLineDelimiter(selection.getStartLineIndex());
//String[] lines = document.get(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength()).split(delimiter);
String[] lines = selection.getCompleteSelection().split(delimiter);
if (lines.length == 0) return;
int index = 0;
StringBuffer buff = new StringBuffer();
boolean fix = true;
String selectedLine = "";
String correctIndentation = "";
while (index < lines.length) {
if (tools.isLineCommandLine(lines[index]) ||
tools.isLineCommentLine(lines[index]) ||
lines[index].trim().length() == 0) {
buff.append(lines[index]);
if (lines[index].trim().length() == 0 ||
isList(lines[index])) {
fix = true;
}
index++;
if (index < lines.length)
buff.append(delimiter);
continue;
}
// a current line is NOT a comment, a command or an empty line -> continue
// OO: fix empty lines and lists, but only on the next iteration?
if (fix) {
correctIndentation = tools.getIndentation(lines[index], tabWidth);
fix = false;
}
StringBuffer temp = new StringBuffer();
boolean end = false;
while (index < lines.length && !end) {
if (!tools.isLineCommandLine(lines[index]) &&
!tools.isLineCommentLine(lines[index]) &&
lines[index].trim().length() > 0) {
if (lines[index].trim().startsWith("\\item") && !itemFound) {
end = true;
itemFound = true;
} else {
temp.append(lines[index].trim() + " ");
itemFound = false;
//Respect \\ with a subsequent line break
if (lines[index].trim().endsWith("\\\\")) {
end = true;
}
index++;
}
} else {
/* a current line is a command, a comment or en empty ->
do not handle the line at this iteration. */
end = true;
}
}
int wsLast = 0;
selectedLine = temp.toString().trim();
while (selectedLine.length() > 0) {
/* find the last white space before MAX */
wsLast = tools.getLastWSPosition(selectedLine,
(lineLength - correctIndentation.length())) + 1;
if (wsLast == 0) {
/* there was no white space before MAX, try if there is
one after */
wsLast = tools.getFirstWSPosition(selectedLine,
(lineLength - correctIndentation.length())) + 1;
}
if (wsLast == 0 || wsLast > selectedLine.length() ||
selectedLine.length() < (lineLength - correctIndentation.length())){
//there was no white space character at the line
wsLast = selectedLine.length();
}
buff.append(correctIndentation);
buff.append(selectedLine.substring(0,wsLast));
selectedLine = selectedLine.substring(wsLast);
selectedLine = tools.trimBegin(selectedLine);
if (index < lines.length || selectedLine.length() > 0)
buff.append(delimiter);
}
}
// document.replace(selection.getTextSelection().getOffset(),
// selection.getSelLength(),
// buff.toString());
document.replace(document.getLineOffset(selection.getStartLineIndex()),
selection.getSelLength(),
buff.toString());
}
/**
* Returns the indentation level by looking at the previous line and the formatter settings for the tabs and spaces.
* This is the default way it's computed, unless a subclass override it. In case the subclass involves a parsing to
* get valid AST to compute the indentation, it might fail. Subclass that fail on the AST creation should call this
* method as a fall-back option.
*
* @param document
* @param offset
* @return
*/
public int detectIndentationLevel(IDocument document, int offset)
{
if (document.getLength() <= offset + 1)
{
return 0;
}
try
{
String lineDelimiter = document.getLineDelimiter(document.getLineOfOffset(offset));
if (lineDelimiter == null)
{
lineDelimiter = StringUtil.EMPTY;
}
int lineNumber = document.getLineOfOffset(Math.min(document.getLength(), offset + lineDelimiter.length()));
if (lineNumber > 0)
{
IRegion previousLineRegion = document.getLineInformation(lineNumber - 1);
String text = document.get(previousLineRegion.getOffset(), previousLineRegion.getLength());
// grab the empty string at the beginning of the text.
int spaceChars = 0;
int tabChars = 0;
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
if (!Character.isWhitespace(c))
{
break;
}
if (c == '\n' || c == '\r')
{
// ignore it
continue;
}
if (c == ' ')
{
spaceChars++;
}
else if (c == '\t')
{
tabChars++;
}
}
String indentType = getIndentType();
int indentSize = getIndentSize();
int tabSize = getTabSize();
if (CodeFormatterConstants.TAB.equals(indentType))
{
if (tabSize == 0)
{
return 0;
}
// treat the whitespace-chars as tabs
return (spaceChars / tabSize) + tabChars + 1;
}
if (CodeFormatterConstants.EDITOR.equals(indentType))
{
tabSize = getEditorSpecificTabWidth();
indentSize = tabSize;
}
if (indentSize > 0)
{
if (CodeFormatterConstants.SPACE.equals(indentType)
|| (CodeFormatterConstants.EDITOR.equals(indentType)))
{
// treat the tabs as spaces
return (spaceChars + (tabSize * tabChars)) / indentSize + 1;
}
else
{
// it's 'Mixed'
return (spaceChars + tabChars) / indentSize + 1;
}
}
}
}
catch (BadLocationException e)
{
IdeLog.logError(FormatterPlugin.getDefault(), e, IDebugScopes.DEBUG);
}
return 0;
}
@Override
public void apply(IDocument document) {
try {
//default apply
int lineOfOffset = document.getLineOfOffset(fReplacementOffset);
document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
if (SharedCorePlugin.inTestMode()) {
return;
}
int lineOffset = document.getLineOffset(lineOfOffset);
int lineLength = document.getLineLength(lineOfOffset);
String lineDelimiter = document.getLineDelimiter(lineOfOffset);
int lineDelimiterLen = lineDelimiter != null ? lineDelimiter.length() : 0;
ISourceViewer viewer = sourceViewer;
LinkedModeModel model = new LinkedModeModel();
LinkedPositionGroup group = new LinkedPositionGroup();
//the len-3 is because of the end of the string: " = " because the replacement string is
//something like "xxx = "
ProposalPosition proposalPosition = new ProposalPosition(document, fReplacementOffset,
fReplacementString.length() - 3, 0, new ICompletionProposal[0]);
group.addPosition(proposalPosition);
model.addGroup(group);
model.forceInstall();
final LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
ui.setExitPosition(viewer, lineOffset + lineLength - lineDelimiterLen, 0, Integer.MAX_VALUE);
Runnable r = new Runnable() {
@Override
public void run() {
ui.enter();
}
};
RunInUiThread.async(r);
} catch (Throwable x) {
// ignore
Log.log(x);
}
}
/**
* Given a selection on a document, computes the lines fully or partially covered by
* <code>selection</code>. A line in the document is considered covered if
* <code>selection</code> comprises any characters on it, including the terminating delimiter.
* <p>Note that the last line in a selection is not considered covered if the selection only
* comprises the line delimiter at its beginning (that is considered part of the second last
* line).
* As a special case, if the selection is empty, a line is considered covered if the caret is
* at any position in the line, including between the delimiter and the start of the line. The
* line containing the delimiter is not considered covered in that case.
* </p>
*
* @param document the document <code>selection</code> refers to
* @param selection a selection on <code>document</code>
* @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
* @return a selection describing the range of lines (partially) covered by
* <code>selection</code>, without any terminating line delimiters
* @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
*/
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ISourceViewer viewer) throws BadLocationException {
int low= document.getLineOffset(selection.getStartLine());
int endLine= selection.getEndLine();
int high= document.getLineOffset(endLine) + document.getLineLength(endLine);
// get everything up to last line without its delimiter
String delim= document.getLineDelimiter(endLine);
if (delim != null)
high -= delim.length();
return new TextSelection(document, low, high - low);
}
/**
* Given a selection on a document, computes the lines fully or partially covered by
* <code>selection</code>. A line in the document is considered covered if
* <code>selection</code> comprises any characters on it, including the terminating delimiter.
* <p>Note that the last line in a selection is not considered covered if the selection only
* comprises the line delimiter at its beginning (that is considered part of the second last
* line).
* As a special case, if the selection is empty, a line is considered covered if the caret is
* at any position in the line, including between the delimiter and the start of the line. The
* line containing the delimiter is not considered covered in that case.
* </p>
*
* @param document the document <code>selection</code> refers to
* @param selection a selection on <code>document</code>
* @return a selection describing the range of lines (partially) covered by
* <code>selection</code>, without any terminating line delimiters
* @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
*/
private ICoreTextSelection getMovingSelection(IDocument document, ICoreTextSelection selection)
throws BadLocationException {
int low = document.getLineOffset(selection.getStartLine());
int endLine = selection.getEndLine();
int high = document.getLineOffset(endLine) + document.getLineLength(endLine);
// get everything up to last line without its delimiter
String delim = document.getLineDelimiter(endLine);
if (delim != null) {
high -= delim.length();
}
return new CoreTextSelection(document, low, high - low);
}