org.eclipse.jface.text.IDocument#replace ( )源码实例Demo

下面列出了org.eclipse.jface.text.IDocument#replace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: tm4e   文件: ToggleLineCommentHandler.java
private void removeLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	int endLineNumber = selection.getEndLine();
	String oldText = document.get();
	int deletedChars = 0;
	Boolean isStartBeforeComment = false;

	while (lineNumber <= endLineNumber) {
		int commentOffset = oldText.indexOf(comment, document.getLineOffset(lineNumber) + deletedChars);
		document.replace(commentOffset - deletedChars, comment.length(), "");
		if (deletedChars == 0) {
			isStartBeforeComment = commentOffset > selection.getOffset();
		}
		if (lineNumber != endLineNumber) {
			deletedChars += comment.length();
		}
		lineNumber++;
	}
	ITextSelection newSelection = new TextSelection(
			selection.getOffset() - (isStartBeforeComment ? 0 : comment.length()),
			selection.getLength() - deletedChars);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
源代码2 项目: e4macs   文件: JoinLineHandler.java
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
throws BadLocationException {
	int result = NO_OFFSET;
	boolean isNormal = (getUniversalCount() == 1);
	int line = document.getLineOfOffset(getCursorOffset(editor,currentSelection));
	// check buffer location of line
	if ((isNormal ? line != 0 : ++line < document.getNumberOfLines()-1)) {
		int eolLen = document.getLineDelimiter(line-1).length();
		IRegion region = document.getLineInformation(line);
		// position between lines
		int joinOffset = region.getOffset() - eolLen;
		selectAndReveal(editor, joinOffset, joinOffset);
		document.replace(joinOffset, eolLen, EMPTY_STR);
		// TODO: need semantic decision here based on content of join
		result = transformSpace(editor, document, joinOffset, SPACE_STR, false);
	} 
	return result;
}
 
private void updateSlaves(MultiVariable variable, IDocument document, Object oldChoice) {
	Object choice= variable.getCurrentChoice();
	if (!oldChoice.equals(choice)) {
		Set<MultiVariable> slaves= fDependencies.get(variable);
		for (Iterator<MultiVariable> it= slaves.iterator(); it.hasNext();) {
			MultiVariable slave= it.next();
			VariablePosition pos= fPositions.get(slave);

			Object slavesOldChoice= slave.getCurrentChoice();
			slave.setKey(choice); // resets the current choice
			try {
				document.replace(pos.getOffset(), pos.getLength(), slave.getDefaultValue());
			} catch (BadLocationException x) {
				// ignore and continue
			}
			// handle slaves recursively
			if (fDependencies.containsKey(slave))
				updateSlaves(slave, document, slavesOldChoice);
		}
	}
}
 
@Override
public void apply(IDocument document) {
    int replacedLength = preSelectedRegionLength;
    int offset = replacementOffset;
    String text = replacementString;

    if (StringUtils.emptyToNull(prefix) != null && replacementString.toLowerCase().contains(prefix)) {
        if (replacementString.toLowerCase().startsWith(prefix)) {
            text = text.substring(prefix.length());
        } else {
            offset = replacementOffset - prefix.length();
            replacedLength = prefix.length();              
        }
    }
    
    try {
        document.replace(offset, replacedLength, text);
    } catch (BadLocationException x) {
        // ignore
    }
}
 
源代码5 项目: e4macs   文件: IndentForTabHandler.java
/**
 * Insert tab/spaces at selection offset and each subsequent line origin
 * 
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
throws BadLocationException {
	// if we're here, either ^U or no relevant ^I
	ColumnSupport cs = new ColumnSupport(document,editor); 
	String tab = cs.getSpaces(0,cs.getTabWidth());
	int off = currentSelection.getOffset();
	Position coff = new Position(getCursorOffset(editor,currentSelection),0);
	try {
		document.addPosition(coff);
		int begin = document.getLineOfOffset(off);
		int end = document.getLineOfOffset(off+ currentSelection.getLength());
		if (begin != end) {
			while (++begin <= end) {
				document.replace(document.getLineOffset(begin), 0, tab);
			}
		}
		document.replace(off, 0, tab);
	} finally {
		document.removePosition(coff);
	} 
	return coff.offset;
}
 
@Override
public void setInformation(String content) {
	super.setInformation(content);
	IDocument doc= getViewer().getDocument();
	if (doc == null)
		return;

	// ensure that we can scroll enough
	ensureScrollable();

	String start= null;
	if (IJavaPartitions.JAVA_DOC.equals(fPartition)) {
		start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
	} else if (IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(fPartition)) {
		start= "/*" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
	}
	if (start != null) {
		try {
			doc.replace(0, 0, start);
			int startLen= start.length();
			getViewer().setDocument(doc, startLen, doc.getLength() - startLen);
		} catch (BadLocationException e) {
			// impossible
			Assert.isTrue(false);
		}
	}

	getViewer().getTextWidget().setHorizontalPixel(fHorizontalScrollPixel);
}
 
源代码7 项目: tm4e   文件: ToggleLineCommentHandler.java
private void addBlockComment(IDocument document, ITextSelection selection, CharacterPair blockComment,
		ITextEditor editor) throws BadLocationException {
	document.replace(selection.getOffset(), 0, blockComment.getKey());
	document.replace(selection.getOffset() + selection.getLength() + blockComment.getKey().length(), 0,
			blockComment.getValue());
	ITextSelection newSelection = new TextSelection(selection.getOffset() + blockComment.getKey().length(),
			selection.getLength());
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
源代码8 项目: xtext-eclipse   文件: ToSaveOrNotToSaveTest.java
protected void smudge(ITextEditor... editors) throws BadLocationException {
	for (ITextEditor editor : editors) {
		IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
		document.replace(document.getLength(), 0, " ");
		if(editor instanceof XtextEditor) {
			waitForReconciler((XtextEditor) editor);
		}
		waitForDisplay();
		assertTrue(editor.isDirty());
	}
}
 
/**
 * Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
 * Leaves leading comment signs alone.
 *
 * @param document the document
 * @param line the line
 * @param indent the indentation to insert
 * @param commentlines
 * @throws BadLocationException on concurrent document modification
 */
private static void addIndent(IDocument document, int line, CharSequence indent, boolean[] commentlines, int relative) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int insert= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	if (!commentlines[relative]) {
		while (insert < endOffset - 2 && document.get(insert, 2).equals(SLASHES))
			insert += 2;
	}

	// insert indent
	document.replace(insert, 0, indent.toString());
}
 
public void apply(IDocument document) {
	try {
		document.replace(fReplacementPosition.getOffset(), fReplacementPosition.getLength(), fReplacementString);
	} catch (BadLocationException x) {
		// ignore
	}
}
 
源代码11 项目: Pydev   文件: PyConsoleCompletion.java
/**
 * Applies the completion to the document and also updates the caret offset.
 */
@Override
public void apply(IDocument document, char trigger, int stateMask, int offset, IAdaptable projectAdaptable) {
    if (!triggerCharAppliesCurrentCompletion(trigger, document, offset)) {
        //note: no need to walk the offset as in the other cases.
        return;
    }

    try {
        this.diff = offset - (fReplacementOffset + fReplacementLength);

        deltaInLine = document.getLength() - (fReplacementOffset + fReplacementLength);

        String currentLineContents = document.get(commandLineOffset, document.getLength() - commandLineOffset);

        StringBuffer buf = new StringBuffer(currentLineContents);
        int startReplace = currentLineContents.length() - deltaInLine - fReplacementLength;
        int endReplace = currentLineContents.length() - deltaInLine + diff;

        String newCurrentLineString = buf.replace(startReplace, endReplace, fReplacementString).toString();

        //clear the current line contents
        document.replace(commandLineOffset, document.getLength() - commandLineOffset, "");

        boolean addImport = realImportRep.length() > 0;
        String delimiter = PyAction.getDelimiter(document);

        //now, add the import if that should be done...

        if (addImport) {
            //add the import and the contents of the current line
            document.replace(commandLineOffset, 0, realImportRep + delimiter + newCurrentLineString);
        } else {
            //just add the completion contents without doing the import
            document.replace(document.getLength(), 0, newCurrentLineString);
        }
    } catch (BadLocationException x) {
        Log.log(x);
    }
}
 
源代码12 项目: Pydev   文件: PyConvertSpaceToTab.java
/**
 * Performs the action with a given PySelection
 * 
 * @param ps
 *            Given PySelection
 * @param textEditor 
 * @return boolean The success or failure of the action
 */
public static boolean perform(PySelection ps, ITextEditor textEditor) {
    // What we'll be replacing the selected text with
    FastStringBuffer strbuf = new FastStringBuffer();

    // If they selected a partial line, count it as a full one
    ps.selectCompleteLine();

    int i;

    try {
        // For each line, strip their whitespace
        String tabSpace = getTabSpace(textEditor);
        if (tabSpace == null) {
            return false; //could not get it
        }
        IDocument doc = ps.getDoc();
        int endLineIndex = ps.getEndLineIndex();
        String endLineDelim = ps.getEndLineDelim();

        for (i = ps.getStartLineIndex(); i <= endLineIndex; i++) {
            IRegion lineInformation = doc.getLineInformation(i);
            String line = doc.get(lineInformation.getOffset(), lineInformation.getLength());
            strbuf.append(line.replaceAll(tabSpace, "\t")).append((i < endLineIndex ? endLineDelim : ""));
        }

        // If all goes well, replace the text with the modified information
        doc.replace(ps.getStartLine().getOffset(), ps.getSelLength(), strbuf.toString());
        return true;
    } catch (Exception e) {
        beep(e);
    }

    // In event of problems, return false
    return false;
}
 
/**
 * Cuts the visual equivalent of <code>toDelete</code> characters out of the
 * indentation of line <code>line</code> in <code>document</code>. Leaves
 * leading comment signs alone.
 *
 * @param document the document
 * @param line the line
 * @param toDelete the number of space equivalents to delete.
 * @throws BadLocationException on concurrent document modification
 */
private static void cutIndent(IDocument document, int line, int toDelete, int tabSize, boolean[] commentLines, int relative) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int from= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	while (from < endOffset - 2 && document.get(from, 2).equals(SLASHES))
		from += 2;

	int to= from;
	while (toDelete > 0 && to < endOffset) {
		char ch= document.getChar(to);
		if (!Character.isWhitespace(ch))
			break;
		toDelete -= computeVisualLength(ch, tabSize);
		if (toDelete >= 0)
			to++;
		else
			break;
	}

	if (endOffset > to + 1 && document.get(to, 2).equals(SLASHES))
		commentLines[relative]= true;

	document.replace(from, to - from, null);
}
 
源代码14 项目: xtext-xtend   文件: JavaEditorExtension.java
public ITextEditor changeContent(final ITextEditor editor, final String oldText, final String newText) {
  try {
    ITextEditor _xblockexpression = null;
    {
      final IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
      final String model = document.get();
      document.replace(model.indexOf(oldText), oldText.length(), newText);
      _xblockexpression = editor;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
源代码15 项目: n4js   文件: Replacement.java
@Override
public void apply(IDocument document) throws BadLocationException {
	document.replace(getOffset(), getLength(), getText());
}
 
源代码16 项目: Pydev   文件: DocCmd.java
public void doExecute(IDocument document) throws BadLocationException {
    document.replace(offset, length, text);
}
 
源代码17 项目: CogniCrypt   文件: QuickFixProcessor.java
/**
 * getCorrections Method that gets invoked if hasCorrections returns true Returns a new completion proposal for the specific problem
 */
@Override
public IJavaCompletionProposal[] getCorrections(final IInvocationContext context, final IProblemLocation[] locations) throws CoreException {
	if (locations == null || locations.length == 0) {
		/*
		 * https://bugs.eclipse.org/444120 Eclipse can call this method even when there are no markers, then this case would occur.
		 */
		return null;
	}

	return new IJavaCompletionProposal[] {new IJavaCompletionProposal() {

		/**
		 * apply Method that applys the Quickfix/CompletionProposal Currently replaces the text of the example case "cypher.getinstance('AES')" with
		 * "cypher.getinstance('AES/CBC/PKCS5PADDING')"
		 *
		 * @param d Document or File for which the Quickfix is supposed to work
		 */
		@Override
		public void apply(final IDocument d) {
			try {
				d.replace(context.getSelectionOffset(), context.getSelectionLength(), "Cipher.getInstance(\"AES/CBC/PKCS5PADDING\")");
				context.getCompilationUnit().getResource().deleteMarkers(QuickFixProcessor.MARKER_TYPE, false, IResource.DEPTH_ZERO);
			}
			catch (final CoreException | BadLocationException e) {
				Activator.getDefault().logError(e);
			}
		}

		/**
		 * Not used in the example
		 */
		@Override
		public String getAdditionalProposalInfo() {
			return null;
		}

		/**
		 * Not used in the example
		 */
		@Override
		public IContextInformation getContextInformation() {
			return null;
		}

		/**
		 * Display String for the Quickfix
		 */
		@Override
		public String getDisplayString() {
			final String display = "Change to a more secure Encryption";
			return display;
		}

		/**
		 * Not used in the example
		 */
		@Override
		public Image getImage() {
			return null;
		}

		/**
		 * Not used in the example
		 */
		@Override
		public Point getSelection(final IDocument document) {
			return null;
		}

		/**
		 * Used to define the relevance of a Quickfix
		 */
		@Override
		public int getRelevance() {
			return 1;
		}
	}};
}
 
/**
 * Copies the indentation of the previous line and adds a star.
 * If the Javadoc just started on this line add standard method tags
 * and close the Javadoc.
 *
 * @param d the document to work on
 * @param c the command to deal with
 */
private void indentAfterNewLine(IDocument d, DocumentCommand c) {

	int offset= c.offset;
	if (offset == -1 || d.getLength() == 0)
		return;

	try {
		int p= (offset == d.getLength() ? offset - 1 : offset);
		IRegion line= d.getLineInformationOfOffset(p);

		int lineOffset= line.getOffset();
		int firstNonWS= findEndOfWhiteSpace(d, lineOffset, offset);
		Assert.isTrue(firstNonWS >= lineOffset, "indentation must not be negative"); //$NON-NLS-1$

		StringBuffer buf= new StringBuffer(c.text);
		IRegion prefix= findPrefixRange(d, line);
		String indentation= d.get(prefix.getOffset(), prefix.getLength());
		int lengthToAdd= Math.min(offset - prefix.getOffset(), prefix.getLength());

		buf.append(indentation.substring(0, lengthToAdd));

		if (firstNonWS < offset) {
			if (d.getChar(firstNonWS) == '/') {
				// Javadoc started on this line
				buf.append(" * "); //$NON-NLS-1$

				if (isPreferenceTrue(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, offset)) {
					c.shiftsCaret= false;
					c.caretOffset= c.offset + buf.length();
					String lineDelimiter= TextUtilities.getDefaultLineDelimiter(d);

					int eolOffset= lineOffset + line.getLength();
					int replacementLength= eolOffset - p;
					String restOfLine= d.get(p, replacementLength);
					String endTag= lineDelimiter + indentation + " */"; //$NON-NLS-1$

					if (isPreferenceTrue(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)) {
						// we need to close the comment before computing
						// the correct tags in order to get the method
						d.replace(offset, replacementLength, endTag);

						// evaluate method signature
						ICompilationUnit unit= getCompilationUnit();

						if (unit != null) {
							try {
								JavaModelUtil.reconcile(unit);
								String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
								buf.append(restOfLine);
								// only add tags if they are non-empty - the empty line has already been added above.
								if (string != null && !string.trim().equals("*")) //$NON-NLS-1$
									buf.append(string);
							} catch (CoreException e) {
								// ignore
							}
						}
					} else {
						c.length= replacementLength;
						buf.append(restOfLine);
						buf.append(endTag);
					}
				}

			}
		}

		// move the caret behind the prefix, even if we do not have to insert it.
		if (lengthToAdd < prefix.getLength())
			c.caretOffset= offset + prefix.getLength() - lengthToAdd;
		c.text= buf.toString();

	} catch (BadLocationException excp) {
		// stop work
	}
}
 
private static void insertTag(IDocument textBuffer, int offset, int length, String[] paramNames, String[] exceptionNames, String returnType, String[] typeParameterNames, boolean isDeprecated,
		String lineDelimiter) throws BadLocationException {
	IRegion region= textBuffer.getLineInformationOfOffset(offset);
	if (region == null) {
		return;
	}
	String lineStart= textBuffer.get(region.getOffset(), offset - region.getOffset());

	StringBuffer buf= new StringBuffer();
	for (int i= 0; i < typeParameterNames.length; i++) {
		if (buf.length() > 0) {
			buf.append(lineDelimiter).append(lineStart);
		}
		buf.append("@param <").append(typeParameterNames[i]).append('>'); //$NON-NLS-1$
	}
	for (int i= 0; i < paramNames.length; i++) {
		if (buf.length() > 0) {
			buf.append(lineDelimiter).append(lineStart);
		}
		buf.append("@param ").append(paramNames[i]); //$NON-NLS-1$
	}
	if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$
		if (buf.length() > 0) {
			buf.append(lineDelimiter).append(lineStart);
		}
		buf.append("@return"); //$NON-NLS-1$
	}
	if (exceptionNames != null) {
		for (int i= 0; i < exceptionNames.length; i++) {
			if (buf.length() > 0) {
				buf.append(lineDelimiter).append(lineStart);
			}
			buf.append("@throws ").append(exceptionNames[i]); //$NON-NLS-1$
		}
	}
	if (isDeprecated) {
		if (buf.length() > 0) {
			buf.append(lineDelimiter).append(lineStart);
		}
		buf.append("@deprecated"); //$NON-NLS-1$
	}
	if (buf.length() == 0 && isAllCommentWhitespace(lineStart)) {
		int prevLine= textBuffer.getLineOfOffset(offset) - 1;
		if (prevLine > 0) {
			IRegion prevRegion= textBuffer.getLineInformation(prevLine);
			int prevLineEnd= prevRegion.getOffset() + prevRegion.getLength();
			// clear full line
			textBuffer.replace(prevLineEnd, offset + length - prevLineEnd, ""); //$NON-NLS-1$
			return;
		}
	}
	textBuffer.replace(offset, length, buf.toString());
}
 
源代码20 项目: texlipse   文件: TexHardLineWrapAction.java
/**
     * 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());
    }