Updating CodeLens in a VS Code Extension

When using VS Code, certain language extensions can provide codelens that display reference counts above functions, variables, and other symbols. Check it out here.

I've recently taken on a project and one of my first tasks is to restructure it. In doing so, I'd like to pull references into local or external without having to constantly "show all references".

After going through the extension API example and exploring the API further, I experimented with building a few extensions to gain more knowledge about how they function. While I can insert a codelens with customized data, I'm encountering an issue now. It doesn't appear that there's a way to access existing codelenses or the information used in generating the "i references".

Another discovery I made during this process is that the language defines the symbols, yet there seems to be no way to iterate over them either. Although I could re-parse everything and create my own codelens analysis, this approach would be more time-consuming than manually checking the scope. Additionally, it feels overly complicated.

I was hoping for an event that triggers when a codelens is created or modified, allowing me to retrieve that codelens information. However, it appears that the codelens events are handled internally and not accessible to me.

My ideal scenario would involve retrieving two pieces of information:

  1. Retrieve the number referenced as "i references"
  2. Determine the line to which it corresponds

Is this feasible within the API's scope or beyond its capabilities? Although I am prepared to rewrite my parsing code, the fact remains that there's already a mechanism in place generating this information, which I'd prefer to tap into.

Answer №1

After much searching, I finally uncovered the solution to my query. Specifically, the predefined commands. It appears that there are commands available for obtaining document symbols and executing reference providers, which I have encapsulated into two functions here:

async function getSymbols(document: TextDocument): Promise<SymbolInformation[]>
{
    return await commands.executeCommand<SymbolInformation[]>('vscode.executeDocumentSymbolProvider', 
                                                                document.uri) || [];
}

async function getReferences(location: Location): Promise<Location[]>
{
    return await commands.executeCommand<Location[]>('vscode.executeReferenceProvider',
                                                    location.uri,
                                                    new Position(
                                                        location.range.start.line,
                                                        location.range.start.character)) || [];
}

Subsequently, I link these two functions in a separate call based on specific conditions.

While this may not be precisely what I initially intended (to retrieve the codelens return value), it enables me to leverage existing functionality without starting from scratch.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The function of splitting 'a' is not available within the context of 'r' (angular.js:263

Although I comprehend the error message, I have not implemented any split functions in my application. The error seems to be originating from the angular.js file itself and is something that has only surfaced recently. I am curious to know if anyone else i ...

What is the best method to merge two arrays into a single array of objects?

Is it possible to utilize an ngFor directive instead of duplicating the <table> element twice? (Note: I considered consolidating all items into objects within a single array for mapping purposes (each object containing a variable, label, and value) ...

Using NextJS's API routes to implement Spotify's authorization flow results in a CORS error

I am currently in the process of setting up the login flow within NextJS by referring to the guidelines provided in the Spotify SDK API Tutorial. This involves utilizing NextJS's api routes. To handle this, I've created two handlers: api/login.t ...

How can we enforce that only a certain type of ReactElement is allowed to be passed as props to a Component in TypeScript?

eslint and vscode seem to have trouble detecting validation errors when passing incompatible ReactElement types. Despite searching through documentation and examples, I haven't been able to find a solution that works. // Footer.tsx export interface ...

GraphQL Query Fails to Save Result - Constantly Returns undefined

After running a query and logging the result, I encountered an issue where the result is always "undefined" when trying to work with it further (as shown in the second logging). It seems like I might be overlooking something obvious here. Any help would ...

typescript create object with immutable property already set

Can you create an object literal in JavaScript and define its interface with read-only properties simultaneously? For instance let obj = { readonly prop1: 'hello', readonly prop2: 'world' } ...

Create a placeholder for an item without the need for a specific function

Here is my current setup: sandbox.stub(rp, 'get').resolves(successResponse) This method provides a custom response when this line of code is executed: return await rp.get(url, options) However, I'm interested in achieving something like ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

What is the best way to display user data exclusively in Angular?

How can I ensure that users only have access to their own information rather than the entire database? I attempted to use an if-else statement to filter out the data I need, as shown in the example below, but it was unsuccessful. custom-history.component ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

What methods should I employ to effectively test a custom icon function?

I've written a function that creates a Leaflet icon with specified properties: createIcon( url, retinaUrl: string = null, height: number = 20, width: number = 20 ): Icon { const icon: Icon = L.icon({ iconUrl: url, ico ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

Adjust the CSS styling of an element in real-time

I am trying to dynamically set the background image for the ion-content element. How can I achieve this? If it were a CSS class, I could simply use [class]="cssClassName" and change the class name in the TypeScript file. But in this case, how can I accompl ...

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

Expand the size of the imported gltf model within Three.js

After successfully loading a 3d model with a gltf extension using the GLTFLoader in Three.js, I encountered a new challenge. I needed to adjust the dimensions of the model dynamically when the window is resized, based on the values of window.innerWidth and ...

What is the method to define a function that strictly accepts a value of type T only if IsSomething<T> evaluates to true?

In my system, there is a complex generic type called IsUnique<T> that evaluates to either true or false based on the input type T: type IsUnique<T> = (/* ... */) ? true : false; Now I am looking to develop a function that takes an unique value ...

Facing the dreaded "ECONNREFUSED" error when trying to connect NodeJS and InfluxDb

I'm encountering an issue when trying to connect to my InfluxDB instance running in a Docker container. To get the InfluxDB image, I used the following command: docker pull influxdb:2.4.0 When I run it locally using Docker Desktop, everything works ...

Issue Encountered with @Input() in TypeScript

I'm currently working on developing an app with Angular 4 and encountered an error message when using @Input('inputProducts') products: Product[]; The specific error I received reads: [tslint] In the class "ProductListComponent", the di ...

Retrieve a targeted section of state from the store with @ngrx when incorporating a smart component in a recursive manner

As a newcomer to ngrx, I've come across a perplexing issue that has me stumped. Essentially, I have a ListComponent that displays an array of ListItemComponents retrieved from a ngrx store. @Component({ ... template: ` <list-item *ngFor= ...