org.eclipse.jface.text.DocumentCommand Java Examples

The following examples show how to use org.eclipse.jface.text.DocumentCommand. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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();
}
 
Example #2
Source File: AbstractJavaCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: StructuredAutoEditStrategyInlinedCss.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
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");
}
 
Example #4
Source File: PropertiesFileAutoEditStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: MultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 6 votes vote down vote up
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;
			}
		}
	}
 
Example #7
Source File: PartitionDeletionEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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();
		}
	}
}
 
Example #8
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 6 votes vote down vote up
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;
}
 
Example #9
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
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);
	}
 
Example #11
Source File: ImpexBracesAutoEditStrategy.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
@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);
	}

}
 
Example #12
Source File: TexAutoIndentStrategy.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #14
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
		}
	}
}
 
Example #15
Source File: TexEditorTools.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: JavaAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void smartIndentOnKeypress(IDocument document, DocumentCommand command) {
	switch (command.text.charAt(0)) {
		case '}':
			smartIndentAfterClosingBracket(document, command);
			break;
		case '{':
			smartIndentAfterOpeningBracket(document, command);
			break;
		case 'e':
			smartIndentUponE(document, command);
			break;
	}
}
 
Example #17
Source File: JavaStringAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
	try {
		if (command.text == null)
			return;
		if (isSmartMode())
			javaStringIndentAfterNewLine(document, command);
	} catch (BadLocationException e) {
	}
}
 
Example #18
Source File: TypeScriptAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
private void smartIndentOnKeypress(IDocument document, DocumentCommand command) {
	switch (command.text.charAt(0)) {
		case '}':
			smartIndentAfterClosingBracket(document, command);
			break;
		case '{':
			smartIndentAfterOpeningBracket(document, command);
			break;
		case 'e':
			smartIndentUponE(document, command);
			break;
	}
}
 
Example #19
Source File: TypeScriptAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
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);
		TypeScriptIndenter indenter= new TypeScriptIndenter(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) {
		JSDTTypeScriptUIPlugin.log(e);
	}
}
 
Example #20
Source File: StructuredAutoEditStrategyInlinedCss.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks to see if the given command can be handled by the
 * {@link StructuredAutoEditStrategyCSS} strategy. In some instances, it may
 * need to prepare the command by tweaking some of the text.
 * <p>
 * Calling the original strategy is expensive if done on every character
 * entered (since we are required to extract and generate a CSS model). This
 * method allows us to do this when we are sure the original strategy can
 * handle the command.
 * 
 * @param document the document receiving the command
 * @param command the document command
 * @return false is this command is unabled to be handled
 */
private boolean prepareForOriginalCssAutoEditStrategy(IDocument document,
    DocumentCommand command) {
  if (command.length != 0 || command.text == null) {
    return false;
  }

  if (!(checkAndPrepareForNewline(document, command)
      || command.text.equals("}")
      || command.text.equals("]") || command.text.equals(")"))) {
    return false;
  }

  return true;
}
 
Example #21
Source File: RubyRegexpAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void customizeDocumentCommand(IDocument document, DocumentCommand command)
{
	if (command.length == 0 && command.text != null)
	{
		if (isLineDelimiter(document, command.text) && !autoIndent(document, command))
		{
			autoIndentAfterNewLine(document, command);
		}
		else if (!isLineDelimiter(document, command.text))
		{
			autoDedent(document, command);
		}
	}
}
 
Example #22
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("nls")
@Override
public void customizeDocumentCommand(IDocument document,
		DocumentCommand command) {
	String text = command.text;
	if (">".equals(text)) {
		command.caretOffset = command.offset + text.length();
		command.text = text + computeEndTag(document, command);
		command.shiftsCaret = false;
	}
}
 
Example #23
Source File: ModulaAutoEditStrategy.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void customizeDocumentCommand(IDocument doc, DocumentCommand cmd) {
    ProcessingResult r1 = ProcessingResult.NONE;
    ProcessingResult r2 = ProcessingResult.NONE;
    try {
        boolean isEnterPressed = (TextUtilities.equals(doc.getLegalLineDelimiters(), cmd.text) != -1); 
        r1 = insertIndentIfNeed(doc, cmd, isEnterPressed);
        r2 = checkTypingAfterLine(doc, cmd, isEnterPressed, r1);
    } catch (Exception e) {}
    
    m2f = null;
    if (r1 == ProcessingResult.NONE && r2 == ProcessingResult.NONE) {
        super.customizeDocumentCommand(doc, cmd);
    }
}
 
Example #24
Source File: JavaAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
	if (c.doit == false)
		return;

	clearCachedValues();

	if (!fIsSmartMode) {
		super.customizeDocumentCommand(d, c);
		return;
	}

	if (!fIsSmartTab && isRepresentingTab(c.text))
		return;

	if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text)) {
		if (fIsSmartIndentAfterNewline)
			smartIndentAfterNewLine(d, c);
		else
			super.customizeDocumentCommand(d, c);
	}
	else if (c.text.length() == 1)
		smartIndentOnKeypress(d, c);
	else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
		if (fViewer == null || fViewer.getTextWidget() == null || !fViewer.getTextWidget().getBlockSelection())
			smartPaste(d, c); // no smart backspace for paste

}
 
Example #25
Source File: CommonAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected boolean checkNextLineForComment(IDocument document, DocumentCommand command)
{
	try
	{
		IRegion nextLineInfo = document.getLineInformationOfOffset(command.offset + 1);
		String nextLine = document.get(nextLineInfo.getOffset(), nextLineInfo.getLength()).trim();
		return (StringUtil.startsWith(nextLine, COMMENT_CHAR) && !StringUtil.startsWith(nextLine, COMMENT_END))
				|| nextLine.endsWith(COMMENT_END);
	}
	catch (BadLocationException e)
	{
	}
	return false;
}
 
Example #26
Source File: CommonAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected void handleScriptDoc(IDocument document, DocumentCommand command, StringBuilder buf,
		String commentIndent, String lineDelimiter)
{
	buf.append(commentIndent).append(COMMENT_CHAR).append(SPACE);

	command.shiftsCaret = false;
	command.caretOffset = command.offset + buf.length() + 1;

	List<String> list = getAdditionalComments(document, command);
	if (list != null && list.size() > 0)
	{
		buf.append(lineDelimiter).append(commentIndent).append(COMMENT_CHAR).append(SPACE);
		buf.append(StringUtil.join(lineDelimiter + commentIndent + COMMENT_CHAR + SPACE, list));
	}
}
 
Example #27
Source File: SmartSemicolonAutoEditStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the document command is applied on a multi
 * line selection, <code>false</code> otherwise.
 *
 * @param document the document
 * @param command the command
 * @return <code>true</code> if <code>command</code> is a multiline command
 */
private boolean isMultilineSelection(IDocument document, DocumentCommand command) {
	try {
		return document.getNumberOfLines(command.offset, command.length) > 1;
	} catch (BadLocationException e) {
		// ignore
		return false;
	}
}
 
Example #28
Source File: TexAutoIndentStrategy.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
    if (this.indent) {
        if (itemSetted && autoItem && command.length == 0 && command.text != null
                && TextUtilities.endsWith(document.getLegalLineDelimiters(), command.text) != -1) {
            dropItem(document, command);
        } else if (command.length == 0 && command.text != null
                &&  TextUtilities.endsWith(document.getLegalLineDelimiters(), command.text) != -1) {
            smartIndentAfterNewLine(document, command);
        } else if ("}".equals(command.text)) {
            smartIndentAfterBrace(document, command);
        } else {
            itemSetted = false;
        }
    }

    if (TexAutoIndentStrategy.hardWrap && command.length == 0 && command.text != null) {
        try {
            final String contentType = ((IDocumentExtension3) document).getContentType(
                    TexEditor.TEX_PARTITIONING, command.offset, true);
            // Do not wrap in verbatim partitions
            if (!FastLaTeXPartitionScanner.TEX_VERBATIM.equals(contentType)) {
                hlw.doWrapB(document, command, lineLength);
            }
        }
        catch (Exception e) {
            // If we cannot retrieve the current content type, do not break lines
        }
    }
}
 
Example #29
Source File: JSDocEditStrategy.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter,
		IType type) throws CoreException, BadLocationException {
	String comment = CodeGeneration.getTypeComment(type.getJavaScriptUnit(), type.getTypeQualifiedName('.'),
			lineDelimiter);
	if (comment != null) {
		boolean javadocComment = comment.startsWith("/**"); //$NON-NLS-1$
		if (!isFirstComment(document, command, type, javadocComment))
			return null;
		return prepareTemplateComment(comment.trim(), indentation, type.getJavaScriptProject(), lineDelimiter);
	}
	return null;
}