vscode-languageserver-textdocument#TextDocument TypeScript Examples

The following examples show how to use vscode-languageserver-textdocument#TextDocument. 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: utils.ts    From volar with MIT License 7 votes vote down vote up
export function getDocumentSafely(documents: vscode.TextDocuments<TextDocument>, uri: string) {

	const normalizeUri = shared.normalizeUri(uri);
	const document = documents.get(uri) ?? documents.get(normalizeUri);

	if (document) {
		return document;
	}

	for (const document of documents.all()) {
		if (shared.normalizeUri(document.uri).toLowerCase() === normalizeUri.toLowerCase()) {
			return document;
		}
	}
}
Example #2
Source File: completion-items.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export function getCompletionItems(opts: {
  model: UI5SemanticModel;
  textDocumentPosition: TextDocumentPositionParams;
  document: TextDocument;
  documentSettings: Settings;
}): CompletionItem[] {
  const documentText = opts.document.getText();
  const { cst, tokenVector } = parse(documentText);
  const ast = buildAst(cst as DocumentCstNode, tokenVector);
  const suggestions = getXMLViewCompletions({
    model: opts.model,
    offset: opts.document.offsetAt(opts.textDocumentPosition.position),
    cst: cst as DocumentCstNode,
    ast: ast,
    tokenVector: tokenVector,
    settings: { codeAssist: opts.documentSettings.codeAssist },
  });

  const completionItems = transformToLspSuggestions(
    suggestions,
    opts.model,
    opts.textDocumentPosition
  );
  return completionItems;
}
Example #3
Source File: aslYamlLanguageService.ts    From amazon-states-language-service with MIT License 6 votes vote down vote up
function convertYAMLDiagnostic(yamlDiagnostic: YAMLDocDiagnostic, textDocument: TextDocument): Diagnostic {
    const startLoc = yamlDiagnostic.location.start
    let endLoc = yamlDiagnostic.location.end
    let severity = yamlDiagnostic.severity

    // Duplicate positioning returns incorrect end position and needs to be ovewritten
    if (yamlDiagnostic.message === YAML_PARSER_MESSAGES.DUPLICATE_KEY) {
        const text = textDocument.getText()
        // Update severity to error
        severity = 1

        for (let loc = yamlDiagnostic.location.start; loc < text.length; loc++) {
            // Colon and whitespace character signal the end of the key.
            if (text.slice(loc, loc + 2).match(/:\s/)) {
                endLoc = loc
            } else if (text[loc] === '\n') {
                break
            }
        }
    }

    const startPos = textDocument.positionAt(startLoc)
    const endPos = textDocument.positionAt(endLoc)

    return {
        range: Range.create(startPos, endPos),
        message: yamlDiagnostic.message,
        severity
    }
}
Example #4
Source File: fileProvider.ts    From macro-executor with MIT License 6 votes vote down vote up
public get(file: string): MacroFileType | undefined {
	
		let uri = this.resolveReference(file);
		if (uri) {
			
			let doc = getParsedDocument(this.documents, uri, (document => {
				let parser = new Parser(this);
				return parser.parseMacroFile(document);
			}));
			if (!doc) {		
				try {
					const file = readFileSync(URI.parse(uri).fsPath, 'utf-8');
					let document = TextDocument.create(uri!, 'macro', 1, file.toString());
					try {
						
						let macrofile = new Parser(this).parseMacroFile(document);
						doc = {
							macrofile: macrofile,
							document: document,
							version: 1
						};
						parsedDocuments.set(uri, doc);
					}
					catch (err){
						this.connection?.console.log(err);
					}
				}
				catch (err) {
					this.connection?.console.log(err);
					return undefined;
				}
			}
			return doc;
		}
		return undefined;
	}
Example #5
Source File: svindexer.ts    From svlangserver with MIT License 6 votes vote down vote up
public updateFileInfoOnSave(document: TextDocument) {
        let file: string = uriToPath(document.uri);
        let info = this._indexedFilesInfo.get(file);
        let symbolsInfo: SystemVerilogParser.SystemVerilogFileSymbolsInfo = info.symbolsInfo;
        let pkgdeps: string[] = info.pkgdeps == null ? [] : info.pkgdeps;

        this._indexIsSaveable = true;
        if (this._lastSavedFilesInfo.has(file)) {
            this._indexedFilesInfo.set(file, this._lastSavedFilesInfo.get(file));
            this._lastSavedFilesInfo.delete(file);
        }
        this._incrementalUpdateFileInfo(file, symbolsInfo, pkgdeps);
        for (let entry of this._preprocCache.values()) {
            this._indexedFilesInfo.set(entry.file, {symbolsInfo: symbolsInfo, pkgdeps: null, rank: 0});
        }
    }
Example #6
Source File: pugDocument.ts    From volar with MIT License 6 votes vote down vote up
export function register(htmlLs: html.LanguageService) {

	return (pugCode: string) => {

		const parsed = baseParse(pugCode);
		const htmlTextDocument = TextDocument.create('foo.html', 'html', 0, parsed.htmlCode);
		const sourceMap = new SourceMap(
			parsed.pugTextDocument,
			htmlTextDocument,
			parsed.sourceMap.mappings,
		);
		const htmlDocument = htmlLs.parseHTMLDocument(htmlTextDocument);

		return {
			pugTextDocument: parsed.pugTextDocument,
			htmlTextDocument,
			htmlDocument,
			sourceMap,
			error: parsed.error,
			ast: parsed.ast,
		};
	};
}
Example #7
Source File: lang-server.ts    From vscode-q with MIT License 6 votes vote down vote up
private async onDidChangeWatchedFiles(change: DidChangeWatchedFilesParams) {
        this.connection.console.info('Received file change event(s)');
        const changedFiles: string[] = [];
        change.changes.forEach(event => {
            switch (event.type) {
                case FileChangeType.Deleted:
                    this.connection.console.info(`Removing ${event.uri} from cache`);
                    this.analyzer.remove(event.uri);
                    break;
                default:
                    changedFiles.push(event.uri);
            }
        });
        changedFiles.forEach(file => {
            const filepath = URI.parse(file).fsPath;
            if (!Analyzer.matchFile(filepath))
                return;
            try {
                this.analyzer.analyzeDoc(file, TextDocument.create(file, 'q', 1, fs.readFileSync(filepath, 'utf8')));
                this.analyzer.analyzeLoadFiles(file);
            } catch (error) {
                this.connection.console.warn(`Cannot analyze ${file}`);
            }
        });
    }
Example #8
Source File: DocumentsManager.ts    From vscode-groovy-lint with GNU General Public License v3.0 6 votes vote down vote up
// Return TextDocument from uri
	getDocumentFromUri(docUri: string, setCurrent = false, throwError = true): TextDocument {
		const textDocument = this.documents.get(docUri)!;
		// eslint-disable-next-line eqeqeq
		if (textDocument == null && throwError == true) {
			throw new Error(`ERROR: Document not found for URI ${docUri}`);
		}
		// eslint-disable-next-line eqeqeq
		if (textDocument != null && setCurrent) {
			this.setCurrentDocumentUri(docUri);
		}
		return textDocument;
	}
Example #9
Source File: coffeescriptDocumentRegionParser.ts    From coffeesense with MIT License 6 votes vote down vote up
export function parseCoffeescriptDocumentRegions(document: TextDocument) {
  const text = document.getText();
  const regions: EmbeddedRegion[] = [
    {
      languageId: 'javascript',
      start: 0,
      end: text.length,
      type: 'script'
    }
  ];
  return {
    importedScripts: [],
    regions
  };
}
Example #10
Source File: tree-sitter-document.ts    From vscode-teal with MIT License 6 votes vote down vote up
async init(uri: string, text: string) {
        await Parser.init();
        this._parser = new Parser();
        const langPath = path.resolve(__dirname, "..", "tree-sitter-teal.wasm");
        this._lang = await Parser.Language.load(langPath);
        this._parser.setLanguage(this._lang);
        this._document = TextDocument.create(uri, "teal", 1, text);
        this._tree = this._parser.parse(text);
        this._uri = uri;
        this._isInit = true;
    }
Example #11
Source File: server.ts    From vscode-css-variables with MIT License 6 votes vote down vote up
function getCurrentWord(document: TextDocument, offset: number): string {
  let left = offset - 1;
  let right = offset + 1;
  const text = document.getText();

  while (left >= 0 && ' \t\n\r":{[()]},*>+'.indexOf(text.charAt(left)) === -1) {
    left--;
  }

  while (
    right <= text.length &&
    ' \t\n\r":{[()]},*>+'.indexOf(text.charAt(right)) === -1
  ) {
    right++;
  }

  return text.substring(left, right);
}
Example #12
Source File: server.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
documents = new TextDocuments(TextDocument)
Example #13
Source File: yamlUtils.ts    From amazon-states-language-service with MIT License 5 votes vote down vote up
function processLineWithoutColon(document: TextDocument, cursorPosition: Position, currentLine: string, currentLineEnd: number): ProcessYamlDocForCompletionOutput {
    let modifiedDocText: string
    let shouldPrependSpace: boolean = false

    const tempPositionForCompletions: Position = { ...cursorPosition }
    const startPositionForInsertion: Position = { ...cursorPosition }

    // Since there's no colon to separate the key and value, replace all text after the cursor.
    const endPositionForInsertion: Position = {
        line: cursorPosition.line,
        character: currentLine.length
    }

    const docText = document.getText()
    const docTextLength = docText.length
    const lineOffsets = getLineOffsets(docText)
    const trimmedLine = currentLine.trim()

    let preText: string
    let postText: string
    let insertedText: string

    // Current line has no non-space characters, insert a placeholder node at the end of the line
    if (trimmedLine.length === 0) {
        preText = docText.substring(0, currentLineEnd)
        insertedText = '"":\n'
        postText = docText.substr(lineOffsets[cursorPosition.line + 1] || docTextLength)

        tempPositionForCompletions.character += 1

    // Trimmed line starts with '-'
    } else if (trimmedLine.length >= 1 && trimmedLine[0] === '-') {
        // Set start of insertion range to be immediately after the hyphen.
        const hyphenIndex = currentLine.indexOf('-')
        startPositionForInsertion.character = hyphenIndex + 1
        shouldPrependSpace = true

        const postHyphenTextTrimmed = currentLine.substring(hyphenIndex + 1).trim()

        // No non-space characters after the hyphen, insert a placeholder node after the hyphen
        if (postHyphenTextTrimmed.length === 0) {
            tempPositionForCompletions.character = hyphenIndex + 3
            preText = docText.substring(0, lineOffsets[cursorPosition.line] + hyphenIndex)
            insertedText = "- '':\n"
            postText = docText.substr(lineOffsets[cursorPosition.line + 1] || docTextLength)

        // There are non-space character after the hyphen, but no colon. Just insert colon at end of line.
        } else {
            preText = docText.substring(0, currentLineEnd)
            insertedText = (!currentLine.endsWith(' ') ? ' ' : '') + ':\n'
            postText = docText.substr(lineOffsets[cursorPosition.line + 1] || docTextLength)
        }

    // Non-empty line but missing colon, add colon to end of current line
    } else {
        preText = docText.substring(0, currentLineEnd)
        insertedText = ':\n'
        postText = docText.substr(lineOffsets[cursorPosition.line + 1] || docTextLength)

        // Starting pos is first non-space character
        startPositionForInsertion.character = currentLine.indexOf(trimmedLine)
    }

    modifiedDocText = `${preText}${insertedText}${postText}`

    return {
        modifiedDocText,
        tempPositionForCompletions,
        startPositionForInsertion,
        endPositionForInsertion,
        shouldPrependSpace
    }
}
Example #14
Source File: server.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
async function validateTextDocument(textDocument: TextDocument): Promise<void> {
  connection.console.info("v2");
  // In this simple example we get the settings for every validate run.
  let settings = globalSettings;
  // await getDocumentSettings(textDocument.uri);

  // The validator creates diagnostics for all uppercase words length 2 and more
  let text = textDocument.getText();
  let pattern = /\b[A-Z]{2,}\b/g;
  let m: RegExpExecArray | null;

  let problems = 0;
  let diagnostics: Diagnostic[] = [];
  while ((m = pattern.exec(text)) && problems < settings.maxNumberOfProblems) {
    problems++;
    let diagnostic: Diagnostic = {
      severity: DiagnosticSeverity.Warning,
      range: {
        start: textDocument.positionAt(m.index),
        end: textDocument.positionAt(m.index + m[0].length),
      },
      message: `${m[0]} is all uppercase.`,
      source: "ex",
    };
    if (hasDiagnosticRelatedInformationCapability) {
      diagnostic.relatedInformation = [
        {
          location: {
            uri: textDocument.uri,
            range: Object.assign({}, diagnostic.range),
          },
          message: "Spelling matters",
        },
        {
          location: {
            uri: textDocument.uri,
            range: Object.assign({}, diagnostic.range),
          },
          message: "Particularly for names",
        },
      ];
    }
    diagnostics.push(diagnostic);
  }

  // Send the computed diagnostics to VSCode.
  connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
Example #15
Source File: server.ts    From fower with MIT License 5 votes vote down vote up
documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument)
Example #16
Source File: fileProvider.ts    From macro-executor with MIT License 5 votes vote down vote up
constructor(private workspaceFolder:string, private documents: TextDocuments<TextDocument>, private connection?:any) {}
Example #17
Source File: svformatter.ts    From svlangserver with MIT License 5 votes vote down vote up
public format(document: TextDocument, range: Range, options: FormattingOptions): Promise<TextEdit[]> {
        if (!this._command) {
            ConnectionLogger.error("Format command not provided");
            return Promise.resolve([]);
        }

        return new Promise((resolve, reject) => {
            try {
                let stdout: string = '';
                let stderr: string = '';
                let rangeArg: string = !!range ? ` --lines=${range.start.line + 1}-${range.end.line + 1}` : "";
                let commandArgs: string[] = (this._command + rangeArg + " -").split(/\s+/);
                let command: string = commandArgs.shift();
                let formatProc = child.spawn(command, commandArgs);
                formatProc.stdout.on('data', (chunk) => {
                    stdout += chunk;
                });
                formatProc.stderr.on('data', (chunk) => {
                    stderr += chunk;
                });
                formatProc.on('error', (err) => {
                    if (err && (<any>err).code === 'ENOENT') {
                        ConnectionLogger.error(`The format command "${this._command}" is not available.`);
                        resolve([]);
                    }
                });
                formatProc.on('close', (code) => {
                    if (stderr.length !== 0) {
                        ConnectionLogger.error(`Formatting gave errors`);
                        resolve([]);
                    }

                    if (code !== 0) {
                        ConnectionLogger.error(`Format command failed`);
                        resolve([]);
                    }

                    resolve([{
                        range: Range.create(0, 0, document.lineCount - 1, 0),
                        newText: stdout
                    }]);
                });
                formatProc.stdin.end(document.getText());
            } catch (error) {
                ConnectionLogger.error(error);
                resolve([]);
            }
        });
    }
Example #18
Source File: pugDocument.ts    From volar with MIT License 5 votes vote down vote up
constructor(
		public sourceDocument: TextDocument,
		public mappedDocument: TextDocument,
		public _mappings?: Mapping<Data>[],
	) {
		super(_mappings);
	}