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

The following examples show how to use org.eclipse.lsp4j.Position#getCharacter() . 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: XDocument.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public int getOffSet(Position position) throws IndexOutOfBoundsException {
	int l = contents.length();
	char NL = '\n';
	int line = 0;
	int column = 0;
	for (var 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() + ((printSourceOnError) ? "" : (" text was : " + contents)));
}
 
Example 2
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 3
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 4
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 5
Source File: CamelPropertyFileKeyInstance.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<List<CompletionItem>> getCompletions(Position position) {
	if (CAMEL_KEY_PREFIX.length() == position.getCharacter() && camelPropertyFileKey.startsWith(CAMEL_KEY_PREFIX)) {
		return getTopLevelCamelCompletion();
	} else if(camelComponentPropertyFilekey != null && camelComponentPropertyFilekey.isInRange(position.getCharacter())) {
		return camelComponentPropertyFilekey.getCompletions(position);
	}
	return CompletableFuture.completedFuture(Collections.emptyList());
}
 
Example 6
Source File: EntityNotDeclaredCodeAction.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Add a code action that inserts the DOCTYPE declaration containing
 * an internal subset with an entity declaration
 * 
 * @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 addDoctypeAndEntityCodeAction(String entityName, Diagnostic diagnostic, DOMDocument document,
		SharedSettings settings, List<CodeAction> codeActions) throws BadLocationException {
	Position insertPosition = getDoctypeInsertPosition(document);

	String delimiter = document.lineDelimiter(insertPosition.getLine());
	String message = "Declare DOCTYPE containing ENTITY " + entityName;
	DOMElement root = document.getDocumentElement();
	if (root == null) {
		return;
	}

	XMLBuilder insertString = new XMLBuilder(settings, null, delimiter);
	if (insertPosition.getCharacter() > 0) {
		insertString.linefeed();
	}
	insertString.startDoctype().addParameter(root.getTagName())
			.startDoctypeInternalSubset().linefeed().indent(1);

	addEntityDeclaration(entityName, insertString);

	insertString.linefeed()
			.endDoctypeInternalSubset().closeStartElement();
	
	Position rootStartPosition = document.positionAt(root.getStart());
	if (insertPosition.getLine() == rootStartPosition.getLine()) {
		insertString.linefeed();
	}

	CodeAction action = CodeActionFactory.insert(message, insertPosition, insertString.toString(),
			document.getTextDocument(), diagnostic);
	codeActions.add(action);
}
 
Example 7
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 8
Source File: ParserXMLFileHelper.java    From camel-language-server with Apache License 2.0 4 votes vote down vote up
@Override
public int getPositionInCamelURI(TextDocumentItem textDocumentItem, Position position) {
	return position.getCharacter() - parserFileHelperUtil.getLine(textDocumentItem, position).indexOf(URI_PARAM) - 5;
}
 
Example 9
Source File: ParserJavaFileHelper.java    From camel-language-server with Apache License 2.0 4 votes vote down vote up
@Override
public int getPositionInCamelURI(TextDocumentItem textDocumentItem, Position position) {
	String beforeCamelURI = getCorrespondingMethodName(textDocumentItem, position.getLine()) + "(" + getEnclosingStringCharacter();
	return position.getCharacter() - parserFileHelperUtil.getLine(textDocumentItem, position).indexOf(beforeCamelURI) - beforeCamelURI.length();
}
 
Example 10
Source File: CamelKYamlDSLParser.java    From camel-language-server with Apache License 2.0 4 votes vote down vote up
@Override
public int getPositionInCamelURI(TextDocumentItem textDocumentItem, Position position) {
	String line = parserFileHelperUtil.getLine(textDocumentItem, position.getLine());
	return position.getCharacter() - findStartPositionOfURI(line);
}
 
Example 11
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 12
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 13
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
public void documentChanged(DocumentEvent event) {
    if (editor.isDisposed()) {
        return;
    }
    if (event.getDocument() == editor.getDocument()) {
        //Todo - restore when adding hover support
        // long predTime = System.nanoTime(); //So that there are no hover events while typing
        changesParams.getTextDocument().setVersion(version++);

        if (syncKind == TextDocumentSyncKind.Incremental) {
            TextDocumentContentChangeEvent changeEvent = changesParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int newTextLength = event.getNewLength();
            Position lspPosition = DocumentUtils.offsetToLSPPos(editor, offset);
            int startLine = lspPosition.getLine();
            int startColumn = lspPosition.getCharacter();
            CharSequence oldText = event.getOldFragment();

            //if text was deleted/replaced, calculate the end position of inserted/deleted text
            int endLine, endColumn;
            if (oldText.length() > 0) {
                endLine = startLine + StringUtil.countNewLines(oldText);
                String[] oldLines = oldText.toString().split("\n");
                int oldTextLength = oldLines.length == 0 ? 0 : oldLines[oldLines.length - 1].length();
                endColumn = oldLines.length == 1 ? startColumn + oldTextLength : oldTextLength;
            } else { //if insert or no text change, the end position is the same
                endLine = startLine;
                endColumn = startColumn;
            }
            Range range = new Range(new Position(startLine, startColumn), new Position(endLine, endColumn));
            changeEvent.setRange(range);
            changeEvent.setRangeLength(newTextLength);
            changeEvent.setText(newText.toString());
        } else if (syncKind == TextDocumentSyncKind.Full) {
            changesParams.getContentChanges().get(0).setText(editor.getDocument().getText());
        }
        requestManager.didChange(changesParams);
    } else {
        LOG.error("Wrong document for the EditorEventManager");
    }
}
 
Example 14
Source File: Utils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static int getOffset(Document doc, Position pos) {
    return LineDocumentUtils.getLineStartFromIndex((LineDocument) doc, pos.getLine()) + pos.getCharacter();
}
 
Example 15
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));
  }
 
Example 16
Source File: DdlTokenAnalyzer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public String positionToString(Position position) {
    return "Line " + (position.getLine() + 1) + " Column " + (position.getCharacter() + 1);
}
 
Example 17
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 18
Source File: TextEditUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static int getOffset(Document doc, Position pos) throws BadLocationException {
	return doc.getLineOffset(pos.getLine()) + pos.getCharacter();
}
 
Example 19
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 20
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));
      }
  }