Java Code Examples for org.eclipse.lsp4j.Position#getLine()

The following examples show how to use org.eclipse.lsp4j.Position#getLine() . 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: Document.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public int getOffSet(Position position) throws IndexOutOfBoundsException {
	int l = contents.length();
	char NL = '\n';
	int line = 0;
	int column = 0;
	for (int i = 0; i < l; i++) {
		char ch = contents.charAt(i);
		if (position.getLine() == line && position.getCharacter() == column) {
			return i;
		}
		if (ch == NL) {
			line++;
			column = 0;
		} else {
			column++;
		}
	}
	if (position.getLine() == line && position.getCharacter() == column) {
		return l;
	}
	throw new IndexOutOfBoundsException(position.toString() + getSourceOnError());
}
 
Example 2
Source File: TextDocument.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public Range getWordRangeAt(int textOffset, Pattern wordDefinition) {
	try {
		Position pos = positionAt(textOffset);
		ILineTracker lineTracker = getLineTracker();
		Line line = lineTracker.getLineInformation(pos.getLine());
		String text = super.getText();
		String lineText = text.substring(line.offset, textOffset);
		int position = lineText.length();
		Matcher m = wordDefinition.matcher(lineText);
		int currentPosition = 0;
		while (currentPosition != position) {
			if (m.find()) {
				currentPosition = m.end();
				if (currentPosition == position) {
					return new Range(new Position(pos.getLine(), m.start()), pos);
				}
			} else {
				currentPosition++;
			}
			m.region(currentPosition, position);
		}
		return new Range(pos, pos);
	} catch (BadLocationException e) {
		return null;
	}
}
 
Example 3
Source File: XMLRename.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Renames all occurences of the namespace in a document, that match
 * the given old namespace.
 * @param document
 * @param oldNamespace
 * @param newNamespace
 * @param rootAttr
 * @return
 */
private static List<TextEdit> renameAllNamespaceOccurrences(DOMDocument document, String oldNamespace, String newNamespace, @Nullable DOMAttr rootAttr) {
	DOMElement rootElement = document.getDocumentElement();
	
	List<TextEdit> edits = new ArrayList<TextEdit>();

	// Renames the xmlns:NAME_SPACE attribute
	if(rootAttr != null) {
		Position start;
		try {
			start = document.positionAt(rootAttr.getStart() + "xmlns:".length());
		} catch (BadLocationException e) {
			start = null;
		}
	
		if(start != null) {
			Position end = new Position(start.getLine(), start.getCharacter() + oldNamespace.length());
			edits.add(new TextEdit(new Range(start, end), newNamespace));
		}
	}

	//Renames all elements with oldNamespace
	List<DOMNode> children = Arrays.asList(rootElement);
	return renameElementsNamespace(document, edits, children, oldNamespace, newNamespace);
}
 
Example 4
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Position computeEndPositionForRemovedText(Position startPos, String removedText) {
    int endLine = startPos.getLine();
    int endChar = startPos.getCharacter();
    for (char c : removedText.toCharArray()) {
        if (c == '\n') {
            endLine++;
            endChar = 0;
        } else {
            endChar++;
        }
    }
    return new Position(endLine, endChar);
}
 
Example 5
Source File: ChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Delete line containing the given offset (the offset need not point to the beginning of the line). Will do nothing
 * if 'deleteOnlyIfEmpty' is set to <code>true</code> and the given line is non-empty, i.e. contains characters
 * other than {@link Character#isWhitespace(char) white space}.
 */
public static TextEdit deleteLine(Document doc, int offset, boolean deleteOnlyIfEmpty) {
	Position offPosition = doc.getPosition(offset);
	String lineContent = doc.getLineContent(offPosition.getLine());
	if (deleteOnlyIfEmpty && !lineContent.isBlank()) {
		return null;
	}

	Position posStart = new Position(offPosition.getLine(), 0);
	Position posEnd = new Position(offPosition.getLine() + 1, 0);
	Range range = new Range(posStart, posEnd);
	return new TextEdit(range, "");
}
 
Example 6
Source File: StringLSP4J.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** @return string for given element */
public String toString(Range range) {
	if (range == null) {
		return "";
	}
	Position start = range.getStart();
	Position end = range.getEnd();
	String stringPosStr = start.getLine() + ":" + start.getCharacter();
	String endPosStr = end.getLine() + ":" + end.getCharacter();
	return "[" + stringPosStr + " - " + endPosStr + "]";
}
 
Example 7
Source File: XMLRename.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private List<TextEdit> getTagNameRenameTextEdits(DOMDocument xmlDocument, DOMElement element, Position position, String newText) {
	
	Range startTagRange = getTagNameRange(TokenType.StartTag, element.getStart(), xmlDocument);
	Range endTagRange = element.hasEndTag() ? getTagNameRange(TokenType.EndTag, element.getEndTagOpenOffset(), xmlDocument)
		: null;
	
	//Check if xsd namespace rename
	String fullNodeName = element.getNodeName();
	int indexOfColon = fullNodeName.indexOf(":");
	if(indexOfColon > 0) {
		Position startTagStartPosition = startTagRange.getStart();
		Position startTagPrefixPosition = new Position(startTagStartPosition.getLine(), startTagStartPosition.getCharacter() + indexOfColon);

		Position endTagStartPosition = endTagRange.getStart();
		Position endTagPrefixPosition = new Position(endTagStartPosition.getLine(), endTagStartPosition.getCharacter() + indexOfColon);

		Range startTagPrefixRange = new Range(startTagStartPosition, startTagPrefixPosition);
		Range endTagPrefixRange = new Range(endTagStartPosition, endTagPrefixPosition);

		if (doesTagCoverPosition(startTagPrefixRange, endTagPrefixRange, position)) {// Element prefix rename
			String prefix = element.getPrefix();
			return renameElementNamespace(xmlDocument, element, prefix.length(), newText);
		} else { //suffix rename without wiping namespace
			String suffixName = element.getLocalName();
			int suffixLength = suffixName.length();
			Position startTagEndPosition = startTagRange.getEnd();
			Position suffixStartPositionStart = new Position(startTagEndPosition.getLine(), startTagEndPosition.getCharacter() - suffixLength);

			Position endTagEndPosition = endTagRange.getEnd();
			Position suffixEndPositionStart = new Position(endTagEndPosition.getLine(), endTagEndPosition.getCharacter() - suffixLength);

			Range suffixRangeStart = new Range(suffixStartPositionStart, startTagEndPosition);
			Range suffixRangeEnd = new Range(suffixEndPositionStart, endTagEndPosition);

			return getRenameList(suffixRangeStart, suffixRangeEnd, newText);
		}
	}
	//Regular tag name rename
	return getRenameList(startTagRange, endTagRange, newText);
}
 
Example 8
Source File: XMLDeclarationSnippetContext.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean isMatch(ICompletionRequest request, Map<String, String> model) {
	DOMDocument document = request.getXMLDocument();
	DOMNode node = request.getNode();
	int offset = request.getOffset();
	if ((node.isComment() || node.isDoctype()) && offset < node.getEnd()) {
		// completion was triggered inside comment, xml processing instruction
		// --> <?xml version="1.0" encoding="UTF-8" | ?>
		return false;
	}
	// check if document already defined a xml declaration.
	if (document.isBeforeProlog(offset) || inProlog(document, offset)) {
		return false;
	}
	Position start = request.getReplaceRange().getStart();
	if (start.getLine() > 0) {
		// The xml processing instruction must be declared in the first line.
		return false;
	}
	// No xml processing instruction, check if completion was triggered before the
	// document element
	DOMElement documentElement = document.getDocumentElement();
	if (documentElement != null && documentElement.getTagName() != null) {
		return offset <= documentElement.getStart();
	}
	return true;
}
 
Example 9
Source File: XMLFormatter.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private void enlargePositionToGutters(Position start, Position end) throws BadLocationException {
	start.setCharacter(0);

	if (end.getCharacter() == 0 && end.getLine() > 0) {
		end.setLine(end.getLine() - 1);
	}

	end.setCharacter(this.textDocument.lineText(end.getLine()).length());
}
 
Example 10
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String _toExpectation(final Position it) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("[");
  int _line = it.getLine();
  _builder.append(_line);
  _builder.append(", ");
  int _character = it.getCharacter();
  _builder.append(_character);
  _builder.append("]");
  return _builder.toString();
}
 
Example 11
Source File: SignatureHelpProvider.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
private int getActiveParameter(Position position, List<Expression> expressions) {
	for (int i = 0; i < expressions.size(); i++) {
		Expression expr = expressions.get(i);
		Range exprRange = GroovyLanguageServerUtils.astNodeToRange(expr);
		if (position.getLine() < exprRange.getEnd().getLine()) {
			return i;
		}
		if (position.getLine() == exprRange.getEnd().getLine()
				&& position.getCharacter() <= exprRange.getEnd().getCharacter()) {
			return i;
		}
	}
	return expressions.size();
}
 
Example 12
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 4 votes vote down vote up
public static boolean isBeforeOrEqual(Position pos1, Position pos2) {
	return pos1.getLine() < pos2.getLine()
			|| (pos1.getLine() == pos2.getLine() && pos1.getCharacter() <= pos2.getCharacter());
}
 
Example 13
Source File: EntityNotDeclaredCodeAction.java    From lemminx with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Add a code action that inserts entity declaration to the
 * current DOCTYPE's internal subset
 * 
 * If the internal subset does not exist, the code action
 * inserts it as well
 * 
 * @param entityName  the entity name for the entity declaration
 * @param diagnostic  the code action's diagnostic
 * @param document    the DOMDocument
 * @param settings    the settings
 * @param codeActions the list of code actions
 * @throws BadLocationException
 */
private void addEntityCodeAction(String entityName, Diagnostic diagnostic, DOMDocument document,
		SharedSettings settings, List<CodeAction> codeActions) throws BadLocationException {

	DOMDocumentType docType = document.getDoctype();
	Position docTypeEnd = document.positionAt(docType.getEnd());
	Position insertPosition = getEntityInsertPosition(document);
	String message = "Declare ENTITY " + entityName;
	String delimiter = document.lineDelimiter(insertPosition.getLine());

	XMLBuilder insertString = new XMLBuilder(settings, null, delimiter);

	boolean hasInternalSubset = docType.getInternalSubset() != null;
	if (!hasInternalSubset) {
		String doctypeContent = docType.getTextContent();

		if (!Character.isWhitespace(doctypeContent.charAt(doctypeContent.length() - 2))) {
			// doctype ends with " >", "\n>", "\r\n>", etc.
			insertString.startDoctypeInternalSubset();
		} else {
			insertString.startUnindentedDoctypeInternalSubset();
		}
		
		if (insertPosition.getLine() > 0) {
			insertString.linefeed();
		}
	} else if (insertPosition.getCharacter() != 0) {
		insertString.linefeed(); // add the new entity in a new line
	}

	insertString.indent(1);
	addEntityDeclaration(entityName, insertString);

	if (docType.getInternalSubset() == null) {
		insertString.linefeed().endDoctypeInternalSubset();
	} else if (docTypeEnd.getLine() == insertPosition.getLine()) {
		insertString.linefeed();
	}

	CodeAction action = CodeActionFactory.insert(message, insertPosition, insertString.toString(),
			document.getTextDocument(), diagnostic);
	codeActions.add(action);
}
 
Example 14
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionForMissingField(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if (offsetNode instanceof IMXMLInstanceNode)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              IMXMLTagData offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
              if(offsetTag != null)
              {
                  //workaround for bug in Royale compiler
                  Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
                  int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
                  offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
              }
          }
      }
      IIdentifierNode identifierNode = null;
      if (offsetNode instanceof IIdentifierNode)
      {
          IASNode parentNode = offsetNode.getParent();
          if (parentNode instanceof IMemberAccessExpressionNode)
          {
              IMemberAccessExpressionNode memberAccessExpressionNode = (IMemberAccessExpressionNode) offsetNode.getParent();
              IExpressionNode leftOperandNode = memberAccessExpressionNode.getLeftOperandNode();
              if (leftOperandNode instanceof ILanguageIdentifierNode)
              {
                  ILanguageIdentifierNode leftIdentifierNode = (ILanguageIdentifierNode) leftOperandNode;
                  if (leftIdentifierNode.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS)
                  {
                      identifierNode = (IIdentifierNode) offsetNode;
                  }
              }
          }
          else //no member access
          {
              identifierNode = (IIdentifierNode) offsetNode;
          }
      }
      if (identifierNode == null)
      {
          return;
      }
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }
      WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForGenerateFieldVariable(
          identifierNode, path.toUri().toString(), fileText);
      if(edit == null)
      {
          return;
      }
      
      CodeAction codeAction = new CodeAction();
      codeAction.setDiagnostics(Collections.singletonList(diagnostic));
      codeAction.setTitle("Generate Field Variable");
      codeAction.setEdit(edit);
      codeAction.setKind(CodeActionKind.QuickFix);
      codeActions.add(Either.forRight(codeAction));
  }
 
Example 15
Source File: ParserFileHelperUtil.java    From camel-language-server with Apache License 2.0 4 votes vote down vote up
public String getLine(TextDocumentItem textDocumentItem, Position position) {
	int line = position.getLine();
	return getLine(textDocumentItem, line);
}
 
Example 16
Source File: Positions.java    From groovy-language-server with Apache License 2.0 4 votes vote down vote up
public static boolean valid(Position p) {
	return p.getLine() >= 0 || p.getCharacter() >= 0;
}
 
Example 17
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private boolean isValid(Position position) {
	return position != null && position.getLine() >= 0 && position.getCharacter() >= 0;
}
 
Example 18
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionsForImport(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      ILspProject project = folderData.project;
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      IMXMLTagData offsetTag = null;
      boolean isMXML = path.toUri().toString().endsWith(FILE_EXTENSION_MXML);
      if (isMXML)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
          }
      }
      if (offsetNode instanceof IMXMLInstanceNode && offsetTag != null)
      {
          //workaround for bug in Royale compiler
          Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
          int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
          offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
      }
      if (offsetNode == null || !(offsetNode instanceof IIdentifierNode))
      {
          return;
      }
      ImportRange importRange = null;
      if (offsetTag != null)
      {
          importRange = ImportRange.fromOffsetTag(offsetTag, currentOffset);
      }
      else
      {
          importRange = ImportRange.fromOffsetNode(offsetNode);
      }
      String uri = importRange.uri;
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      IIdentifierNode identifierNode = (IIdentifierNode) offsetNode;
      String typeString = identifierNode.getName();

      List<IDefinition> types = ASTUtils.findTypesThatMatchName(typeString, project.getCompilationUnits());
      for (IDefinition definitionToImport : types)
      {
          WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForAddImport(definitionToImport, fileText, uri, importRange);
          if (edit == null)
          {
              continue;
          }
          CodeAction codeAction = new CodeAction();
          codeAction.setTitle("Import " + definitionToImport.getQualifiedName());
          codeAction.setEdit(edit);
          codeAction.setKind(CodeActionKind.QuickFix);
          codeAction.setDiagnostics(Collections.singletonList(diagnostic));
          codeActions.add(Either.forRight(codeAction));
      }
  }
 
Example 19
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private String toPositionFragment(Position it, String uri) {
	return "position line: " + it.getLine() + " column: " + it.getCharacter() + " in resource: " + uri;
}
 
Example 20
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionForMissingMethod(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      ILspProject project = folderData.project;
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if (offsetNode == null)
      {
          return;
      }
      if (offsetNode instanceof IMXMLInstanceNode)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              IMXMLTagData offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
              if(offsetTag != null)
              {
                  //workaround for bug in Royale compiler
                  Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
                  int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
                  offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
              }
          }
      }
      IASNode parentNode = offsetNode.getParent();

      IFunctionCallNode functionCallNode = null;
      if (offsetNode instanceof IFunctionCallNode)
      {
          functionCallNode = (IFunctionCallNode) offsetNode;
      }
      else if (parentNode instanceof IFunctionCallNode)
      {
          functionCallNode = (IFunctionCallNode) offsetNode.getParent();
      }
      else if(offsetNode instanceof IIdentifierNode
              && parentNode instanceof IMemberAccessExpressionNode)
      {
          IASNode gpNode = parentNode.getParent();
          if (gpNode instanceof IFunctionCallNode)
          {
              functionCallNode = (IFunctionCallNode) gpNode;
          }
      }
      if (functionCallNode == null)
      {
          return;
      }
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForGenerateMethod(
          functionCallNode, path.toUri().toString(), fileText, project);
      if(edit == null)
      {
          return;
      }

      CodeAction codeAction = new CodeAction();
      codeAction.setDiagnostics(Collections.singletonList(diagnostic));
      codeAction.setTitle("Generate Method");
      codeAction.setEdit(edit);
      codeAction.setKind(CodeActionKind.QuickFix);
      codeActions.add(Either.forRight(codeAction));
  }