org.eclipse.jface.text.IAutoEditStrategy#org.eclipse.jface.text.DocumentCommand源码实例Demo

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

源代码1 项目: xtext-eclipse   文件: AbstractEditStrategy.java
protected String getDocumentContent(IDocument document, DocumentCommand command) throws BadLocationException {
	final ITypedRegion partition = document.getPartition(command.offset);
	ITypedRegion[] partitions = document.getDocumentPartitioner().computePartitioning(0, document.getLength());
	Iterable<ITypedRegion> partitionsOfCurrentType = Iterables.filter(Arrays.asList(partitions),
			new Predicate<ITypedRegion>() {
				@Override
				public boolean apply(ITypedRegion input) {
					return input.getType().equals(partition.getType());
				}
			});
	StringBuilder builder = new StringBuilder();
	for (ITypedRegion position : partitionsOfCurrentType) {
		builder.append(document.get(position.getOffset(), position.getLength()));
	}
	return builder.toString();
}
 
/**
 * Expects the cursor to be in the same line as the start terminal
 * puts any text between start terminal and cursor into a separate newline before the cursor.
 * puts any text between cursor and end terminal into a separate newline after the cursor.
 * puts the closing terminal into a separate line at the end.
 * adds a closing terminal if not existent.
 */
protected CommandInfo handleCursorInFirstLine(IDocument document, DocumentCommand command, IRegion startTerminal,
		IRegion stopTerminal) throws BadLocationException {
	CommandInfo newC = new CommandInfo();
	newC.isChange = true;
	newC.offset = command.offset;
	newC.text += command.text + indentationString;
	newC.cursorOffset = command.offset + newC.text.length();
	if (stopTerminal == null && atEndOfLineInput(document, command.offset)) {
		newC.text += command.text + getRightTerminal();
	}
	if (stopTerminal != null && stopTerminal.getOffset() >= command.offset && util.isSameLine(document, stopTerminal.getOffset(), command.offset)) {
		String string = document.get(command.offset, stopTerminal.getOffset() - command.offset);
		if (string.trim().length() > 0)
			newC.text += string.trim();
		newC.text += command.text;
		newC.length += string.length();
	}
	return newC;
}
 
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	if (command.text.equals("") && command.length == 1) {
		if (command.offset + right.length() + left.length() > document.getLength())
			return;
		if (command.offset + command.length - left.length() < 0)
			return;
		if (command.length != left.length())
			return;
		String string = document.get(command.offset, left.length() + right.length());
		if (string.equals(left + right)) {
			command.length = left.length() + right.length();
		}
	}
}
 
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

	if (!isSmartMode())
		return;

	if (command.text != null) {
		if (command.length == 0) {
			String[] lineDelimiters= document.getLegalLineDelimiters();
			int index= TextUtilities.endsWith(lineDelimiters, command.text);
			if (index > -1) {
				// ends with line delimiter
				if (lineDelimiters[index].equals(command.text))
					// just the line delimiter
					indentAfterNewLine(document, command);
				return;
			}
		}

		if (command.text.equals("/")) { //$NON-NLS-1$
			indentAfterCommentEnd(document, command);
			return;
		}
	}
}
 
源代码5 项目: texlipse   文件: TexEditorTools.java
/**
 * Returns a text String of the (line + <code>lineDif</code>). 
 * @param document 	IDocument that contains the line.
 * @param command 	DocumentCommand that determines the line.
 * @param delim 	are delimiters included
 * @param lineDif 	0 = current line, 1 = next line, -1 previous line etc...
 * @return 			the text of the line. 
 */
public String getStringAt(IDocument document, 
		DocumentCommand command, boolean delim, int lineDif) {
	String line = "";
       int lineBegin, lineLength;
       try {
           if (delim) {
               lineLength = getLineLength(document, command, true, lineDif);
           } else {
               lineLength = getLineLength(document, command, false, lineDif);
           }
           if (lineLength > 0) {
               lineBegin = document.getLineOffset(document
                       .getLineOfOffset(command.offset) + lineDif);
               line = document.get(lineBegin, lineLength);
           }
       } catch (BadLocationException e) {
           TexlipsePlugin.log("TexEditorTools.getStringAt", e);
       }
       return line;
}
 
/**
 * Creates the Javadoc tags for newly inserted comments.
 *
 * @param document the document
 * @param command the command
 * @param indentation the base indentation to use
 * @param lineDelimiter the line delimiter to use
 * @param unit the compilation unit shown in the editor
 * @return the tags to add to the document
 * @throws CoreException if accessing the Java model fails
 * @throws BadLocationException if accessing the document fails
 */
private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit)
	throws CoreException, BadLocationException
{
	IJavaElement element= unit.getElementAt(command.offset);
	if (element == null)
		return null;

	switch (element.getElementType()) {
	case IJavaElement.TYPE:
		return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);

	case IJavaElement.METHOD:
		return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element);

	default:
		return null;
	}
}
 
源代码7 项目: texlipse   文件: TexAutoIndentStrategy.java
/**
 * Erases the \item -string from a line
 * 
 * @param d
 * @param c
 */
private void dropItem(IDocument d, DocumentCommand c) {
    try {
        if (itemSetted && itemAtLine == (d.getLineOfOffset(c.offset) - 1)) {
            IRegion r = d.getLineInformationOfOffset(c.offset);
            String line = d.get(r.getOffset(), r.getLength());
            if ("\\item".equals(line.trim()) || "\\item[]".equals(line.trim())) {
            	c.shiftsCaret = false;
            	c.length = line.length();
            	c.offset = r.getOffset();
            	c.text = getIndentation(line);
            	c.caretOffset = c.offset + c.text.length();
            }
        }
    } catch (BadLocationException e) {
        TexlipsePlugin.log("TexAutoIndentStrategy:dropItem", e);
    }
    itemSetted = false;
}
 
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
	
	if (command.text.equalsIgnoreCase("\"")) {
		command.text = "\"\"";
		configureCommand(command);
	}
	else if (command.text.equalsIgnoreCase("'")) {
		command.text = "''";
		configureCommand(command);
	}
	else if (command.text.equalsIgnoreCase("[")) {
		command.text = "[]";
		configureCommand(command);
	}
	else if (command.text.equalsIgnoreCase("(")) {
		command.text = "()";
		configureCommand(command);
	}

}
 
源代码9 项目: gef   文件: DotAutoEditStrategy.java
private String computeEndTag(IDocument document, DocumentCommand command) {

		IUnitOfWork<String, XtextResource> endTagComputationWork = new IUnitOfWork<String, XtextResource>() {

			@Override
			public String exec(XtextResource state) throws Exception {
				HtmlTag openTag = findOpenTag(state, command);
				if (openTag != null) {
					return "</" + openTag.getName() + ">"; //$NON-NLS-1$ //$NON-NLS-2$
				} else {
					return ""; //$NON-NLS-1$
				}
			}

		};

		return ((XtextDocument) document).readOnly(endTagComputationWork);
	}
 
源代码10 项目: gef   文件: DotAutoEditStrategy.java
private HtmlTag findOpenTag(XtextResource resource,
		DocumentCommand command) {
	if (!resource.getContents().isEmpty()) {
		EObject dotAst = resource.getContents().get(0);
		INode rootNode = NodeModelUtils.getNode(dotAst);
		int cursorPosition = command.offset;
		ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode,
				cursorPosition);

		String leafNodeText = leafNode.getText();

		String htmlLabelText = extractHtmlLabelContent(leafNodeText);

		if (htmlLabelText == null) {
			return null;
		}

		int htmlLabelStartOffset = leafNode.getOffset() + 1
				+ leafNodeText.substring(1).indexOf('<');
		int htmlLabelCursorPosition = cursorPosition - htmlLabelStartOffset;

		return findOpenTag(htmlLabelText, htmlLabelCursorPosition);

	}
	return null;
}
 
源代码11 项目: typescript.java   文件: JSDocAutoIndentStrategy.java
private String createMethodTags(IDocument document, DocumentCommand command, String indentation,
		String lineDelimiter, IFunction method) throws CoreException, BadLocationException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	IFunction inheritedMethod = getInheritedMethod(method);
	String comment = CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
	if (comment != null) {
		comment = comment.trim();
		boolean javadocComment = comment.startsWith("/**"); //$NON-NLS-1$
		if (!isFirstComment(document, command, method, javadocComment))
			return null;
		boolean isJavaDoc = partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
		if (javadocComment == isJavaDoc) {
			return prepareTemplateComment(comment, indentation, method.getJavaScriptProject(), lineDelimiter);
		}
	}
	return null;
}
 
源代码12 项目: typescript.java   文件: JSDocAutoIndentStrategy.java
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

		if (!isSmartMode())
			return;

		if (command.text != null) {
			if (command.length == 0) {
				String[] lineDelimiters = document.getLegalLineDelimiters();
				int index = TextUtilities.endsWith(lineDelimiters, command.text);
				if (index > -1) {
					// ends with line delimiter
					if (lineDelimiters[index].equals(command.text))
						// just the line delimiter
						indentAfterNewLine(document, command);
					return;
				}
			}

			if (command.text.equals("/")) { //$NON-NLS-1$
				indentAfterCommentEnd(document, command);
				return;
			}
		}
	}
 
private boolean checkAndPrepareForNewline(IDocument document,
    DocumentCommand command) {
  try {
    String documentAndCommandText = document.get(0, command.offset)
        + command.text;
    /*
     * The only case where we want to add an indentation after newline is if
     * there is a opening curly brace.
     */
    Matcher matcher = NEWLINE_AFTER_OPEN_BRACE.matcher(documentAndCommandText);
    if (!matcher.matches()) {
      return false;
    }
  } catch (BadLocationException e) {
    return false;
  }

  /*
   * The StructuredAutoEditStrategyCSS will only add proper indentation if the
   * last character is a newline. We remove the whitespace following the
   * newline which was added by the XML autoedit strategy that comes before
   * us.
   */
  command.text = command.text.replaceAll("\\n\\s+$", "\n");
  return command.text.endsWith("\n");
}
 
private void handleSmartTrigger(IDocument document, char trigger, int referenceOffset) throws BadLocationException {
	DocumentCommand cmd= new DocumentCommand() {
	};

	cmd.offset= referenceOffset;
	cmd.length= 0;
	cmd.text= Character.toString(trigger);
	cmd.doit= true;
	cmd.shiftsCaret= true;
	cmd.caretOffset= getReplacementOffset() + getCursorPosition();

	SmartSemicolonAutoEditStrategy strategy= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING);
	strategy.customizeDocumentCommand(document, cmd);

	replace(document, cmd.offset, cmd.length, cmd.text);
	setCursorPosition(cmd.caretOffset - getReplacementOffset() + cmd.text.length());
}
 
private ICompletionProposal escape(DocumentCommand command) {
	try {
		String charsetName= fFile.getCharset();
		if (!charsetName.equals(fCharsetName)) {
			fCharsetName= charsetName;
			fCharsetEncoder= Charset.forName(fCharsetName).newEncoder();
		}
	} catch (CoreException e) {
		return null;
	}

	String text= command.text;
	boolean escapeUnicodeChars= !fCharsetEncoder.canEncode(text);
	boolean escapeBackslash= (text.length() > 1) && ((escapeUnicodeChars && PropertiesFileEscapes.containsUnescapedBackslash(text)) || PropertiesFileEscapes.containsInvalidEscapeSequence(text));

	if (!escapeUnicodeChars && !escapeBackslash)
		return null;

	command.text= PropertiesFileEscapes.escape(text, false, false, escapeUnicodeChars);
	if (escapeBackslash) {
		String proposalText= PropertiesFileEscapes.escape(text, false, true, escapeUnicodeChars);
		return new EscapeBackslashCompletionProposal(proposalText, command.offset, command.text.length(),
				PropertiesFileEditorMessages.EscapeBackslashCompletionProposal_escapeBackslashesInOriginalString);
	}
	return null;
}
 
源代码16 项目: n4js   文件: JSDocEditStrategy.java
/**
 * Expects the cursor to be in the same line as the start terminal puts any text between start terminal and cursor
 * into a separate newline before the cursor. puts any text between cursor and end terminal into a separate newline
 * after the cursor. puts the closing terminal into a separate line at the end. adds a closing terminal if not
 * existent. If the next astElement is a method with parameters or return the JSDoc-tags will be added as an
 * addition.
 */
@Override
protected CommandInfo handleCursorInFirstLine(IDocument document, DocumentCommand command, IRegion startTerminal,
		IRegion stopTerminal) throws BadLocationException {
	CommandInfo newC = new CommandInfo();
	List<String> returnTypeAndParameterNames = getReturnTypeAndParameterNames(document, startTerminal);
	String paramString = "";
	String returnString = "";
	if ((returnTypeAndParameterNames.size() > 0) && returnTypeAndParameterNames.get(0).equals("return")) {
		returnString = INDENTATION_STR + RETURN_STR + command.text;
	}
	if (returnTypeAndParameterNames.size() > 1) {
		for (int i = 1; i < returnTypeAndParameterNames.size(); i += 1) {
			paramString += command.text + INDENTATION_STR + PARAM_STR + returnTypeAndParameterNames.get(i);
		}
	}
	newC.isChange = true;
	newC.offset = command.offset;
	newC.text += command.text + INDENTATION_STR;
	newC.cursorOffset = command.offset + newC.text.length();
	if (stopTerminal == null && atEndOfLineInput(document, command.offset)) {
		newC.text += command.text + getRightTerminal();
	}
	if (stopTerminal != null && stopTerminal.getOffset() >= command.offset
			&& util.isSameLine(document, stopTerminal.getOffset(), command.offset)) {
		String string = document.get(command.offset, stopTerminal.getOffset() - command.offset);
		if (string.trim().length() > 0)
			newC.text += string.trim();
		if (!(returnTypeAndParameterNames.size() == 0)) {
			newC.text += paramString + command.text + returnString;
		} else {
			newC.text += command.text;
		}

		newC.length += string.length();
	}
	return newC;
}
 
/**
 * 	See bug 403812
 * 	Closing terminal is already included, so that the command must not contain a new closing brace
 */
@Test public void testFindStopTerminal() throws Exception {
	MultiLineTerminalsEditStrategy strategy = new MultiLineTerminalsEditStrategy("{", "\t","}",true);
	DocumentCommand command= DocumentCommandTest.getDocumentCommandTest(17);
	strategy.customizeDocumentCommand(getDocument("Hello {\n  Thomas{\n   Birthday\n  }//\n}!"),command);
	assertEquals("",command.text.trim());
}
 
/**
 * See bug 403812
 * Closing terminal is not available, so that the command has to contain a new closing brace
 */
@Test public void testFindStopTerminal_2() throws Exception {
	MultiLineTerminalsEditStrategy strategy = new MultiLineTerminalsEditStrategy("{", "\t","}",true);
	DocumentCommand command= DocumentCommandTest.getDocumentCommandTest(17);
	strategy.customizeDocumentCommand(getDocument("Hello {\n  Thomas{\n   Birthday\n  //\n}!"),command);
	assertEquals("}",command.text.trim());
}
 
/**
 * See bug 403812
 * If all partitions after the inner closing brace are of type __sl_comment there should be
 * a new closing brace as well.
 */
@Test public void testFindStopTerminal_3() throws Exception {
	MultiLineTerminalsEditStrategy strategy = new MultiLineTerminalsEditStrategy("{", "\t","}",true);
	DocumentCommand command= DocumentCommandTest.getDocumentCommandTest(17);
	strategy.customizeDocumentCommand(getDocument("Hello {\n  Thomas{\n   Birthday\n }//}!"),command);
	assertEquals("}",command.text.trim());
}
 
public static DocumentCommand getDocumentCommandTest(int offset){
	DocumentCommand command = new DocumentCommandTest();
	command.caretOffset=-1;
	command.doit=true;
	command.length=0;
	command.offset=offset;
	command.text="\r\n  ";
	command.shiftsCaret=true;
	return command;
}
 
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
	if (c.offset == -1 || d.getLength() == 0)
		return;

	try {
		int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
		int line= d.getLineOfOffset(p);
		int start= d.getLineOffset(line);
		int whiteend= findEndOfWhiteSpace(d, start, c.offset);

		JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
		JavaIndenter indenter= new JavaIndenter(d, scanner, fProject);

		// shift only when line does not contain any text up to the closing bracket
		if (whiteend == c.offset) {
			// evaluate the line with the opening bracket that matches out closing bracket
			int reference= indenter.findReferencePosition(c.offset, false, true, false, false);
			int indLine= d.getLineOfOffset(reference);
			if (indLine != -1 && indLine != line) {
				// take the indent of the found line
				StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
				// add the rest of the current line including the just added close bracket
				replaceText.append(d.get(whiteend, c.offset - whiteend));
				replaceText.append(c.text);
				// modify document command
				c.length += c.offset - start;
				c.offset= start;
				c.text= replaceText.toString();
			}
		}
	} catch (BadLocationException e) {
		JavaPlugin.log(e);
	}
}
 
源代码22 项目: xtext-eclipse   文件: InterpreterAutoEdit.java
private BigDecimal computeResult(IDocument document, DocumentCommand command) {
	return xtextDocumentUtil.getXtextDocument(document).tryReadOnly((XtextResource resource) -> {
		Evaluation stmt = findEvaluation(command, resource);
		if (stmt == null) {
			return null;
		}
		return evaluate(stmt);
	});
}
 
/**
 * Unindents a typed slash ('/') if it forms the end of a comment.
 *
 * @param d the document
 * @param c the command
 */
private void indentAfterCommentEnd(IDocument d, DocumentCommand c) {
	if (c.offset < 2 || d.getLength() == 0) {
		return;
	}
	try {
		if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$
			// modify document command
			c.length++;
			c.offset--;
		}
	} catch (BadLocationException excp) {
		// stop work
	}
}
 
源代码24 项目: xtext-eclipse   文件: ShortCutEditStrategy.java
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	matched = false;
	int shortCutIndex = shortcut.length() - 1;
	boolean isLastCharacterOfShortCut = command.text.equals(shortcut.substring(shortCutIndex));
	int startOffset = command.offset - shortCutIndex;
	boolean isShortCut = startOffset>=0 && document.get(startOffset, shortCutIndex).equals(shortcut.subSequence(0, shortCutIndex));
	if (isLastCharacterOfShortCut && isShortCut) {
		command.offset = startOffset;
		command.length = shortCutIndex;
		command.text = longForm;
		matched = true;
	}
}
 
源代码25 项目: xtext-eclipse   文件: AbstractEditStrategy.java
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
	if (skipNext)
		return;
	try {
		internalCustomizeDocumentCommand(document, command);
	} catch (BadLocationException e) {
		handleBadLocationException(e);
	}
}
 
private boolean isLineDelimiter(IDocument document, DocumentCommand command) {
	if (command.length != 0) {
		return false;
	}
	String originalText = command.text;
	String[] lineDelimiters = document.getLegalLineDelimiters();
	int delimiterIndex = TextUtilities.startsWith(lineDelimiters, originalText);
	return delimiterIndex != -1 && originalText.trim().length() == 0;
}
 
/**
 * Expects the cursor not to be in the first line of the block
 * inserts a closing terminal if not existent.
 */
protected CommandInfo handleNoStopTerminal(IDocument document, DocumentCommand command, IRegion startTerminal,
		IRegion stopTerminal) throws BadLocationException {
	if (atEndOfLineInput(document, command.offset)) {
		CommandInfo newC = new CommandInfo();
		newC.isChange = true;
		String textPartBeforeCursor = command.text + Strings.removeLeadingWhitespace(indentationString);
		newC.cursorOffset = command.offset+textPartBeforeCursor.length();
		newC.text = textPartBeforeCursor + command.text + Strings.removeLeadingWhitespace(getRightTerminal());
		return newC;
	}
	return null;
}
 
/**
 * adds a new line with required indentation after the cursor.
 */
protected CommandInfo handleCursorBetweenStartAndStopLine(IDocument document, DocumentCommand command,
		IRegion startTerminal, IRegion stopTerminal) throws BadLocationException {
	if (indentationString.trim().length()>0 && !atBeginningOfLineInput(document, command.offset)) {
		CommandInfo newC = new CommandInfo();
		newC.isChange = true;
		newC.text += command.text + Strings.removeLeadingWhitespace(indentationString);
		return newC;
	}
	return null;
}
 
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	handleInsertLeftTerminal(document, command);
	handleInsertRightTerminal(document, command);
	handleDeletion(document, command);
}
 
protected void handleInsertLeftTerminal(IDocument document, DocumentCommand command) throws BadLocationException {
	if (command.text.length() > 0 && appliedText(document, command).endsWith(getLeftTerminal())
			&& isInsertClosingTerminal(document, command.offset + command.length)) {
		String documentContent = getDocumentContent(document, command);
		int opening = count(getLeftTerminal(), documentContent);
		int closing = count(getRightTerminal(), documentContent);
		int occurences = opening + closing;
		if (occurences % 2 == 0) {
			command.caretOffset = command.offset + command.text.length();
			command.text = command.text + getRightTerminal();
			command.shiftsCaret = false;
		}
	}
}