vscode#Location TypeScript Examples

The following examples show how to use vscode#Location. 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: yaccValidation.ts    From yash with MIT License 6 votes vote down vote up
export function doYACCValidation(document: TextDocument, yaccDocument: YACCDocument): Diagnostic[] {
    const diags: Diagnostic[] = [];
    yaccDocument.problems.forEach(problem => {
        const range = new Range(document.positionAt(problem.offset), document.positionAt(problem.end));
        let severity: DiagnosticSeverity = DiagnosticSeverity.Information;
        switch (problem.type) {
            case ProblemType.Error:
                severity = DiagnosticSeverity.Error;
                break;
            case ProblemType.Information:
                severity = DiagnosticSeverity.Information;
                break;
            case ProblemType.Warning:
                severity = DiagnosticSeverity.Warning;
                break;
        }
        const diag = new Diagnostic(range, problem.message, severity);
        if (problem.related) {
            diag.relatedInformation = [new DiagnosticRelatedInformation(
                new Location(document.uri, new Range(document.positionAt(problem.related.offset), document.positionAt(problem.related.end))),
                problem.related.message
            )];
        }
        diags.push(diag);
    });
    return diags;
}
Example #2
Source File: spReferencesProvider.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function referencesProvider(
  itemsRepo: ItemsRepository,
  position: Position,
  document: TextDocument,
  context: ReferenceContext,
  token: CancellationToken
): Location[] {
  const items = itemsRepo.getItemFromPosition(document, position);
  if (items.length === 0) {
    return [];
  }

  const references = items
    .filter((e) => e.references !== undefined)
    .map((e) => e.references)
    .filter((e) => e !== undefined)
    .flat();

  if (context.includeDeclaration) {
    references.push(
      ...items.map((e) => locationFromRange(e.filePath, e.range))
    );
  }

  return references;
}
Example #3
Source File: spReferencesProvider.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
/**
 * Callback function for the `searchForReferencesInString` function when searching for local variable references.
 * @param  {{references:Location[];name:string;lineNb:number;uri:URI}} this
 * @param  {RegExpExecArray} match
 * @returns void
 */
function handleReferencesInProvider(
  this: { references: Location[]; name: string; lineNb: number; uri: URI },
  match: RegExpExecArray
): void {
  if (match[0] == this.name) {
    const range = positiveRange(
      this.lineNb,
      match.index,
      match.index + match[0].length
    );
    const location = new Location(this.uri, range);
    this.references.push(location);
  }
}
Example #4
Source File: spUtils.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
/**
 * Returns a new location based on a filePath and a range.
 * @param  {string} filePath  The file's path of the new location.
 * @param  {Range} range      The range of the new location.
 * @returns Location
 */
export function locationFromRange(filePath: string, range: Range): Location {
  return new Location(URI.file(filePath), range);
}
Example #5
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Provide XML Documentation Completion Items for AL Procedure.
     * @param alObject ALObject.
     * @param alProcedure ALProcedure.
     */
    async ProvideALProcedureCompletionItems(alObject: ALObject, alProcedure: ALProcedure) {
        this.AddXmlDocCompletionItem(alProcedure);

        try {
            if ((alObject.ExtensionType === ALObjectExtensionType.Implement) && (alObject.ExtensionObject !== undefined)) {                
                this.AddInheritXmlDocCompletionItem(alObject, alProcedure);

                let inheritObjLocation: Array<Location> | undefined = await ALSyntaxUtil.GetObjectDefinition(ALObjectType.Interface, alObject.ExtensionObject);
                if ((inheritObjLocation === undefined) || (inheritObjLocation.length === 0)) {
                    return;
                }
                await this.AddXmlDocFromInterfaceCompletionItem(inheritObjLocation, alProcedure);
            }
        } catch {
            return;
        }
    }
Example #6
Source File: lexReferences.ts    From yash with MIT License 6 votes vote down vote up
export function doLEXFindReferences(document: TextDocument, position: Position, lexDocument: LexDocument): Location[] {
    const offset = document.offsetAt(position);
    const node = lexDocument.getEmbeddedCode(offset);
    if (node) {
        return [];
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = lexDocument.defines[word] || lexDocument.states[word];
    let location: Location[] = [];
    symbol?.references.forEach(reference => {
        location.push(new Location(document.uri, new Range(document.positionAt(reference[0]), document.positionAt(reference[1]))));
    })
    return location;
}
Example #7
Source File: lexValidation.ts    From yash with MIT License 6 votes vote down vote up
export function doLEXValidation(document: TextDocument, lexDocument: LexDocument): Diagnostic[] {
    const diags: Diagnostic[] = [];
    lexDocument.problems.forEach(problem => {
        const range = new Range(document.positionAt(problem.offset), document.positionAt(problem.end));
        let severity: DiagnosticSeverity = DiagnosticSeverity.Information;
        switch (problem.type) {
            case ProblemType.Error:
                severity = DiagnosticSeverity.Error;
                break;
            case ProblemType.Information:
                severity = DiagnosticSeverity.Information;
                break;
            case ProblemType.Warning:
                severity = DiagnosticSeverity.Warning;
                break;
        }
        const diag = new Diagnostic(range, problem.message, severity);
        if (problem.related) {
            diag.relatedInformation = [new DiagnosticRelatedInformation(
                new Location(document.uri, new Range(document.positionAt(problem.related.offset), document.positionAt(problem.related.end))),
                problem.related.message
            )];
        }
        diags.push(diag);
    });
    return diags;
}
Example #8
Source File: yaccDefinitions.ts    From yash with MIT License 6 votes vote down vote up
export function doYACCFindDefinition(document: TextDocument, position: Position, yaccDocument: YACCDocument): Definition | null {
    const offset = document.offsetAt(position);
    const node = yaccDocument.getEmbeddedNode(offset);
    if (node) {
        return null;
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = yaccDocument.types[word] || yaccDocument.symbols[word] || yaccDocument.tokens[word] || yaccDocument.aliases[`"${word}"`];
    let location: Location | null = null;
    if (symbol) {
        location = new Location(document.uri, new Range(document.positionAt(symbol.definition[0]), document.positionAt(symbol.definition[1])));
    }
    return location;
}
Example #9
Source File: yaccReferences.ts    From yash with MIT License 6 votes vote down vote up
export function doYACCFindReferences(document: TextDocument, position: Position, yaccDocument: YACCDocument): Location[] {
    const offset = document.offsetAt(position);
    const node = yaccDocument.getEmbeddedNode(offset);
    if (node) {
        return [];
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = yaccDocument.types[word] || yaccDocument.symbols[word] || yaccDocument.tokens[word] || yaccDocument.aliases[`"${word}"`];
    let location: Location[] = [];
    symbol?.references.forEach(reference => {
        location.push(new Location(document.uri, new Range(document.positionAt(reference[0]), document.positionAt(reference[1]))));
    })
    symbol?.alias?.references.forEach(reference => {
        location.push(new Location(document.uri, new Range(document.positionAt(reference[0]), document.positionAt(reference[1]))));
    })
    return location;
}
Example #10
Source File: yaccTypeDefinition.ts    From yash with MIT License 6 votes vote down vote up
export function doYACCFindTypeDefinition(document: TextDocument, position: Position, yaccDocument: YACCDocument): Definition | null {
    const offset = document.offsetAt(position);
    const node = yaccDocument.getEmbeddedNode(offset);
    if (node) {
        return null;
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = yaccDocument.symbols[word] || yaccDocument.tokens[word] || yaccDocument.aliases[`"${word}"`];
    let location: Location | null = null;
    if (symbol && symbol.type) {
        const type = yaccDocument.types[symbol.type];
        if (type) {
            location = new Location(document.uri, new Range(document.positionAt(type.definition[0]), document.positionAt(type.definition[1])));
        }
    }
    return location;
}
Example #11
Source File: lexDefinition.ts    From yash with MIT License 6 votes vote down vote up
export function doLEXFindDefinition(document: TextDocument, position: Position, lexDocument: LexDocument): Definition | null {
    const offset = document.offsetAt(position);
    const node = lexDocument.getEmbeddedCode(offset);
    if (node) {
        return null;
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = lexDocument.defines[word] || lexDocument.states[word];
    let location: Location | null = null;
    if (symbol) {
        location = new Location(document.uri, new Range(document.positionAt(symbol.definition[0]), document.positionAt(symbol.definition[1])));
    }
    return location;
}
Example #12
Source File: lexMode.ts    From yash with MIT License 6 votes vote down vote up
export function getLEXMode(lexLanguageService: LEXLanguageService): LanguageMode {
    const cache = CreateDocumentCache<LexDocument>(10, 60, document => lexLanguageService.parseLexDocument(document));
    return {
        getId() {
            return 'lex';
        },
        doValidation(document: TextDocument): Diagnostic[] {
            const lex = cache.get(document);
            return lexLanguageService.doValidation(document, lex);
        },
        doComplete(document: TextDocument, position: Position): CompletionList | CompletionItem[] {
            const lex = cache.get(document);
            return lexLanguageService.doComplete(document, position, lex);
        },
        doHover(document: TextDocument, position: Position): Hover | null {
            const lex = cache.get(document);
            return lexLanguageService.doHover(document, position, lex);
        },
        findDefinition(document: TextDocument, position: Position): Definition | null {
            const lex = cache.get(document);
            return lexLanguageService.findDefinition(document, position, lex);
        },
        findReferences(document: TextDocument, position: Position): Location[] {
            const lex = cache.get(document);
            return lexLanguageService.findReferences(document, position, lex);
        },
        doRename(document: TextDocument, position: Position, newName: string): WorkspaceEdit | null {
            const lex = cache.get(document);
            return lexLanguageService.doRename(document, position, newName, lex);
        },
        onDocumentRemoved(document: TextDocument) {
            cache.onDocumentRemoved(document);
        },
        dispose() {
            cache.dispose();
        }
    };
}
Example #13
Source File: MoveHeader.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Helper for {@link MoveHeaderCommand.updateReferences}
   * Given a {@link Location}, find the respective note.
   * @param location
   * @param engine
   * @returns note
   */
  private getNoteByLocation(
    location: Location,
    engine: IEngineAPIService
  ): NoteProps | undefined {
    const fsPath = location.uri.fsPath;
    const fname = NoteUtils.normalizeFname(path.basename(fsPath));

    const vault = ExtensionProvider.getWSUtils().getVaultFromUri(location.uri);
    const note = NoteUtils.getNoteByFnameFromEngine({
      fname,
      engine,
      vault,
    });
    return note;
  }
Example #14
Source File: DefinitionProvider.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
private async provideForNewNote(
    refAtPos: NonNullable<Awaited<ReturnType<typeof getReferenceAtPosition>>>
  ) {
    const wsRoot = ExtensionProvider.getDWorkspace().wsRoot;
    const config = ExtensionProvider.getEngine().config;
    const noAutoCreateOnDefinition =
      !ConfigUtils.getWorkspace(config).enableAutoCreateOnDefinition;
    if (noAutoCreateOnDefinition) {
      return;
    }
    const out = await new GotoNoteCommand(
      ExtensionProvider.getExtension()
    ).execute({
      qs: refAtPos.ref,
      anchor: refAtPos.anchorStart,
    });
    if (out?.kind !== TargetKind.NOTE) {
      // Wasn't able to create, or not a note file
      return;
    }
    const { note, pos } = out;
    return new Location(
      Uri.file(NoteUtils.getFullPath({ note, wsRoot })),
      pos || new Position(0, 0)
    );
  }
Example #15
Source File: md.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
noteLinks2Locations = (note: NoteProps) => {
  const refs: {
    location: Location;
    matchText: string;
    link: DLink;
  }[] = [];
  const linksMatch = note.links.filter((l) => l.type !== "backlink");
  const fsPath = NoteUtils.getFullPath({
    note,
    wsRoot: ExtensionProvider.getDWorkspace().wsRoot,
  });
  const fileContent = fs.readFileSync(fsPath).toString();
  const fmOffset = getFrontmatterEndingOffsetPosition(fileContent) ?? 0;
  linksMatch.forEach((link) => {
    const startOffset = link.position?.start.offset || 0;
    const lines = fileContent.slice(0, fmOffset + startOffset).split("\n");
    const lineNum = lines.length;

    refs.push({
      location: new vscode.Location(
        vscode.Uri.file(fsPath),
        new vscode.Range(
          new vscode.Position(lineNum, 0),
          new vscode.Position(lineNum + 1, 0)
        )
      ),
      matchText: lines.slice(-1)[0],
      link,
    });
  });
  return refs;
}
Example #16
Source File: macroDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private getMacroDefinition(
    macroName: string,
    currentFilePath: Uri
  ): Definition | undefined {
    const projectRootpath = this.dbtProjectContainer.getProjectRootpath(
      currentFilePath
    );
    if (projectRootpath === undefined) {
      return;
    }
    const macroMap = this.macroToLocationMap.get(projectRootpath.fsPath);
    if (macroMap === undefined) {
      return;
    }
    const location = macroMap.get(macroName);
    if (location) {
      return new Location(
        Uri.file(location.path),
        new Position(location.line, location.character)
      );
    }
    return undefined;
  }
Example #17
Source File: modelDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private getDefinitionFor(
    name: string,
    currentFilePath: Uri
  ): Definition | undefined {
    const projectRootpath = this.dbtProjectContainer.getProjectRootpath(
      currentFilePath
    );
    if (projectRootpath === undefined) {
      return;
    }
    const nodeMap = this.modelToLocationMap.get(projectRootpath.fsPath);
    if (nodeMap === undefined) {
      return;
    }
    const location = nodeMap.get(name);
    if (location) {
      return new Location(Uri.file(location.path), new Range(0, 0, 0, 0));
    }
    return undefined;
  }
Example #18
Source File: sourceDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private getSourceDefinition(
    sourceName: string,
    currentFilePath: Uri,
    tableName: string
  ): Definition | undefined {
    const projectRootpath = this.dbtProjectContainer.getProjectRootpath(
      currentFilePath
    );
    if (projectRootpath === undefined) {
      return;
    }
    const sourceMap = this.sourceMetaMap.get(projectRootpath.fsPath);
    if (sourceMap === undefined) {
      return;
    }
    const location = sourceMap
      .get(sourceName)
      ?.tables.find((table) => table.name === tableName);
    if (location) {
      const sourceFile: string = readFileSync(location.path).toString("utf8");
      const sourceFileLines = sourceFile.split("\n");
      for (let index = 0; index < sourceFileLines.length; index++) {
        const currentLine = sourceFileLines[index];
        if (currentLine.includes(tableName)) {
          return new Location(
            Uri.file(location.path),
            new Position(index, currentLine.indexOf(tableName))
          );
        }
      }
    }
    return undefined;
  }
Example #19
Source File: referenceProvider.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
export function updateReferenceProvider() {
	Global.referenceProviderDisposable?.dispose();

	Global.referenceProviderDisposable = languages.registerReferenceProvider(
		getTodoMdFileDocumentSelector(),
		{
			provideReferences(document, position, context) {
				const range = getWordRangeAtPosition(document, position);
				if (!range) {
					return undefined;
				}
				const word = document.getText(range);
				const parsedWord = parseWord(word, position.line, range.start.character);
				let resultRanges: Range[] = [];
				if (parsedWord.type === 'tags') {
					resultRanges = getAllTagRangesInDocument(parsedWord, position);
				} else if (parsedWord.type === 'project') {
					resultRanges = getAllProjectRangesInDocument(parsedWord, position);
				} else if (parsedWord.type === 'context') {
					resultRanges = getAllContextRangesInDocument(parsedWord, position);
				}
				return resultRanges.map(r => new Location(document.uri, r));
			},
		},
	);
}
Example #20
Source File: client.ts    From vala-vscode with MIT License 6 votes vote down vote up
peekSymbol(_editor: TextEditor, _edit: TextEditorEdit, lspCurrentLocation: lsp.Location, lspTargetLocation: lsp.Location): void {
        let currentLocation = new Location(
            Uri.parse(lspCurrentLocation.uri),
            new Range(
                new Position(lspCurrentLocation.range.start.line, lspCurrentLocation.range.start.character),
                new Position(lspCurrentLocation.range.end.line, lspCurrentLocation.range.end.character)
            )
        );
        let targetLocation = new Location(
            Uri.parse(lspTargetLocation.uri),
            new Range(
                new Position(lspTargetLocation.range.start.line, lspTargetLocation.range.start.character),
                new Position(lspTargetLocation.range.end.line, lspTargetLocation.range.end.character)
            )
        );

        commands.executeCommand(
            'editor.action.peekLocations',
            currentLocation.uri, // anchor uri and position
            currentLocation.range.end,
            [targetLocation], // results (vscode.Location[])
            'peek', // mode ('peek' | 'gotoAndPeek' | 'goto')
            'Nothing found' // <- message
        );
    }
Example #21
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add Completion Item for copying XML Documentation from Interface Procedure.
     * @param inheritObjLocation Location of Interface Object.
     * @param alProcedure AL Procedure to document.
     */
    private async AddXmlDocFromInterfaceCompletionItem(inheritObjLocation: Location[], alProcedure: ALProcedure) {
        try {
            const alLangServer = new ALLangServerProxy();
            const alDefinition = await alLangServer.GetALObjectFromDefinition(inheritObjLocation[0].uri.toString(), inheritObjLocation[0].range.start);
            if ((alDefinition !== undefined) && (alDefinition.ALObject !== null)) {
                let inheritALProcedure: ALProcedure | undefined = alDefinition.ALObject.Procedures?.find(inheritALProcedure => (inheritALProcedure.Code === alProcedure?.Code));
                if (inheritALProcedure !== undefined) {

                    const inheritCompletionItem2: CompletionItem = new CompletionItem(
                        'AL XML Documentation Interface Comment',
                        CompletionItemKind.Text
                    );

                    let snippetText: string = ALDocCommentUtil.GetProcedureDocumentation(inheritALProcedure);

                    const snippet: SnippetString = new SnippetString(snippetText.replace('///', '')); // delete leading '///'. The trigger character is already in the document when the completion provider is triggered.
                    inheritCompletionItem2.insertText = snippet;
                    inheritCompletionItem2.documentation = snippetText;
                    inheritCompletionItem2.detail = 'XML documentation interface comment.';
                    inheritCompletionItem2.sortText = '1';

                    this.alXmlDocCompletionItems.push(inheritCompletionItem2);
                }
            }
        } catch(ex) {
            console.error(`[AddXmlDocFromInterfaceCompletionItem] - ${ex} Please report this error at https://github.com/365businessdev/vscode-alxmldocumentation/issues`);
            return undefined;
        }

    }
Example #22
Source File: spProviders.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
public async provideReferences(
    document: TextDocument,
    position: Position,
    context: ReferenceContext,
    token: CancellationToken
  ): Promise<Location[]> {
    return referencesProvider(
      this.itemsRepository,
      position,
      document,
      context,
      token
    );
  }
Example #23
Source File: ALSyntaxUtil.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Retrieve definition for AL Object.
     * @param alObjectType ALObjectType.
     * @param alObjectName Object Name.
     */
    public static async GetObjectDefinition(alObjectType: ALObjectType, alObjectName: string): Promise<Location[] | undefined> {
        let definition: Array<Location> | undefined = undefined;

        // get current workspace folder
        const wsPath: string = workspace.workspaceFolders![0].uri.fsPath;
        // create temporary al file name
        const tempFileName: Uri = Uri.file(`${wsPath}/__${Guid.create().toString()}__.al`);
        try 
        {
            // create temp AL-file to execute AL Definition Provider.
            fs.writeFileSync(tempFileName.fsPath,
`codeunit 50000 GoToDefinition {
    trigger OnRun()
    var
        object: ${ALObjectType[alObjectType]} "${alObjectName}";
    begin
    end;
}`);

            // execute AL definition provider.
            definition = await commands.executeCommand('vscode.executeDefinitionProvider', tempFileName, new Position(3, `        object: ${ALObjectType[alObjectType]} `.length + 1));
            if ((definition === undefined) || (definition.length === 0)) {
                console.debug(`No definition for ${ALObjectType[alObjectType]} ${alObjectName} has been found.`);
            }
        } finally {
            // delete temp file.
            if (fs.existsSync(tempFileName.fsPath)) {
                fs.unlinkSync(tempFileName.fsPath);
            }
        }

        return definition;
    }
Example #24
Source File: spEnumMemberItem.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
references: Location[];
Example #25
Source File: ALInheritDocDefinitionProvider.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
async provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Location | Location[] | LocationLink[] | null | undefined> {
        if (document.lineAt(position.line).text.trim().startsWith('///')) {
            // if code reference (cref) is found.
            let codeRef: RegExpMatchArray | null = document.lineAt(position.line).text.match(InheritDocRegEx);
            if (codeRef === null) {
                return;
            }

            // get actual AL Object.
            let alObject: ALObject | null = await ALSyntaxUtil.GetALObject(document);
            if ((alObject === null) || (alObject.Uri === undefined)) {
                return;
            }

            // split code reference.
            let codeRefProcedureCode: string = codeRef.groups!['CodeReference'];
            let codeRefObjectName: string|undefined = alObject?.ExtensionObject;
            if (!codeRefObjectName) {
                return;
            }

            let objDefinition: Array<Location> | undefined = await ALSyntaxUtil.GetObjectDefinition(ALObjectType.Interface, codeRefObjectName);
            if (objDefinition === undefined) {
                return;
            }

            if (((document.lineAt(position.line).text.indexOf(codeRefObjectName)) <= position.character) && 
                ((document.lineAt(position.line).text.indexOf(codeRefObjectName) + codeRefObjectName.length) >= position.character)) {
                // build object return definition.
                let definition: Location | undefined = new Location(objDefinition[0].uri, new Range(
                    new Position(alObject.LineNo, 0),
                    new Position(alObject.LineNo, 0)));            

                return definition;
            }

            if ((document.lineAt(position.line).text.indexOf(codeRefObjectName)) < position.character) {
                let interfaceObj: ALObject | undefined = ALObjectCache.ALObjects.find((interfaceObj) => (interfaceObj.Name === codeRefObjectName));
                if (!interfaceObj) {
                    return;
                }

                let alProcedure: ALProcedure | undefined = interfaceObj?.Procedures?.find((alProcedure) => /*(alProcedure.LineNo > position.line) && */(alProcedure.Code === codeRefProcedureCode));
                if (alProcedure === undefined) {
                    return;
                }

                // build return definition.
                let definition: Location | undefined = new Location(objDefinition[0].uri, new Range(
                    new Position(alProcedure.Range!.start.line, alProcedure.Range!.start.character),
                    new Position(alProcedure.Range!.end.line, alProcedure.Range!.end.character)));            

                return definition;
            }
        }
    }
Example #26
Source File: findFileReferences.ts    From language-tools with MIT License 5 votes vote down vote up
/**
 * adopted from https://github.com/microsoft/vscode/blob/5f3e9c120a4407de3e55465588ce788618526eb0/extensions/typescript-language-features/src/languageFeatures/fileReferences.ts
 */
export async function addFindFileReferencesListener(
    getLS: () => LanguageClient,
    context: ExtensionContext
) {
    const disposable = commands.registerCommand('svelte.typescript.findAllFileReferences', handler);

    context.subscriptions.push(disposable);

    async function handler(resource?: Uri) {
        if (!resource) {
            resource = window.activeTextEditor?.document.uri;
        }

        if (!resource || resource.scheme !== 'file') {
            return;
        }

        const document = await workspace.openTextDocument(resource);

        await window.withProgress(
            {
                location: ProgressLocation.Window,
                title: 'Finding file references'
            },
            async (_, token) => {
                const lsLocations = await getLS().sendRequest<LSLocation[] | null>(
                    '$/getFileReferences',
                    document.uri.toString(),
                    token
                );

                if (!lsLocations) {
                    return;
                }

                const config = workspace.getConfiguration('references');
                const existingSetting = config.inspect<string>('preferredLocation');

                await config.update('preferredLocation', 'view');
                try {
                    await commands.executeCommand(
                        'editor.action.showReferences',
                        resource,
                        new Position(0, 0),
                        lsLocations.map(
                            (ref) =>
                                new Location(
                                    Uri.parse(ref.uri),
                                    new Range(
                                        ref.range.start.line,
                                        ref.range.start.character,
                                        ref.range.end.line,
                                        ref.range.end.character
                                    )
                                )
                        )
                    );
                } finally {
                    await config.update(
                        'preferredLocation',
                        existingSetting?.workspaceFolderValue ?? existingSetting?.workspaceValue
                    );
                }
            }
        );
    }
}
Example #27
Source File: ALLangServerProxy.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Perform go-to-definition call.
     * @param docUri URI of the source document.
     * @param pos Position to perform go-to-definition on.
     */
    async ALGoToDefinition(docUri: string, pos: Position) : Promise<Location | undefined> {
        let docPos : Location | undefined = undefined;
        try {
            this.IsALLanguageClient();
            if (!this.langClient) {
                return undefined;
            }

            let launchConfiguration = await this.GetFirstLaunchConfiguration();

            if (launchConfiguration) {
                let docPosTemp : any = await this.langClient.sendRequest<any>('al/gotodefinition', {
                    launchConfiguration : launchConfiguration,
                    textDocumentPositionParams : {
                        textDocument : {
                            uri : docUri.toString()
                        },
                        position : {
                            line : pos.line,
                            character : pos.character
                        }
                    },
                    context : undefined
                }, new CancellationTokenSource().token);

                if (docPosTemp) {
                    docPos = new Location(
                        Uri.parse(docPosTemp.uri),
                        new Range(
                            docPosTemp.range.start.line, 
                            docPosTemp.range.start.character,
                            docPosTemp.range.end.line, 
                            docPosTemp.range.end.character
                            )
                        );                    
                }
            }
        }   
        catch (ex) {
            console.debug(ex.message);
            return undefined;
        }    

        return docPos; 
    }
Example #28
Source File: ALLangServerProxy.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Retrieve AL Object from Language Server.
     * @param docUri Actual Document file path.
     * @param pos Actual Position to retrieve AL Object from.
     */
    async GetALObjectFromDefinition(docUri: string, pos: Position): Promise<{ ALObject: ALObject | null, Position: Position} | undefined> {
        try { 
            if ((!this.IsALLanguageClient()) || (!this.langClient)) {
                throw new Error(`Fatal error: Unable to contact language server.`);
            }     
        
            var __awaiter : any = (this && __awaiter) || function (thisArg: any, _arguments: any, P: PromiseConstructor, generator: { [x: string]: (arg0: any) => any; next: (arg0: any) => any; apply: any; }) {
                function adopt(value: unknown) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
                return new (P || (P = Promise))(function (resolve, reject) {
                    function fulfilled(value: any) { try { step(generator.next(value)); } catch (e) { reject(e); } }
                    function rejected(value: any) { try { step(generator['throw'](value)); } catch (e) { reject(e); } }
                    function step(result: any) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
                    step((generator = generator.apply(thisArg, _arguments || [])).next());
                });
            };

            // Execute AL Go to Definition
            let alDefinition: Location | undefined = await this.ALGoToDefinition(docUri, pos).then((result: any) => __awaiter(this, void 0, void 0, function* () {
                return Promise.resolve(result);
            }));

            if ((!alDefinition) || ((alDefinition.range.start.character === 0) && (alDefinition.range.end.character === 0))) {
                return undefined;
            }

            let alSourceCode: string = '';
            if (alDefinition.uri.scheme === 'al-preview') {      
                // For al-preview try get source code from language server.
                const request = { Uri: alDefinition.uri.toString() };                        
                alSourceCode = await this.langClient.sendRequest('al/previewDocument', request).then((result: any) => __awaiter(this, void 0, void 0, function* () {
                    return Promise.resolve(result.content);
                }));
            } else {
                // If file is available just read from filesystem.
                alSourceCode = fs.readFileSync(alDefinition.uri.fsPath, 'utf8');
            }

            let document = Object.assign({});
            document.getText = () => alSourceCode;
            document.fileName = (alDefinition.uri.scheme === 'al-preview') ? '__symbol__' : alDefinition.uri.fsPath;

            let result: { ALObject: ALObject | null, Position: Position} = {
                ALObject: await ALSyntaxUtil.GetALObject(document),
                Position: alDefinition.range.end
            };

            return result;
        }
        catch(ex) 
        {
            console.error(`[GetALObjectFromDefinition] - ${ex} Please report this error at https://github.com/365businessdev/vscode-alxmldocumentation/issues`);
            return undefined;
        }

    }
Example #29
Source File: spDefineItem.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
references: Location[];