Is there a way to remove trigger characters in vscode api completion function?

I am developing a vscode extension that requires custom completion for json files. I would like to know if it is possible to hide the trigger character when using autocompletions.

Let me explain further :

Imagine the trigger character is '.' In your json file, you type '.' and it suggests a list of predefined items. When I press tab or enter, the usual behavior would display .item (where item is the selected item upon pressing enter) Is there a way to only show 'item' and remove the trigger character '.'?

This is the snippet of code I have so far:

context.subscriptions.push(languages.registerCompletionItemProvider (
            { language: 'json', scheme: 'file' },
            // 'json',
            {
                provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext) {
        
                let myitem = (text:string) => {
                    let item = new CompletionItem(text, CompletionItemKind.Text);
                    item.range = new Range(position, position);
                    return item;
                };

                const linePrefix = document.lineAt(position).text.substring(0, position.character);
                if (linePrefix.match(/name/g)) {
                    return [
                        myitem('log'),
                        myitem('warn'),
                        myitem('error'),
                        ];
                } else {
                    return undefined;
                }
            }
            },
            '?' // trigger
        ));

Answer №1

Generally, the trigger characters would be automatically removed. However, in the case of a non-word character like ? in JSON files, Visual Studio Code returns undefined when trying to get the wordRangeAtPosition(position), causing it not to replace the trigger character.

To address this issue, you can manually obtain the wordRangeAtPosition() using a custom regex that includes ? and then use that range in the CompletionItem.range.

After experimenting unsuccessfully with setting the range to include and replace the ?, I discovered a different successful approach, as mentioned in this link.

You can try adding the following code to your CompletionItems:

let myitem = (text) => {
    let item = new vscode.CompletionItem(text, vscode.CompletionItemKind.Text);
    
    const rangeToRemove = new vscode.Range(position.line, position.character-1, position.line, position.character);
    item.additionalTextEdits = [vscode.TextEdit.delete(rangeToRemove)];
    
    return item;
};

In my testing, the line below is not necessary since the default will be used:

item.range = new Range(position, position);

(I included the non-typescript version with vscode. for general usage.)

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: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

Developing a union type to guarantee every value in the `enum` is accounted for

My code includes an enum that lists operations (which cannot be altered): enum OpType { OpA = 0, OpB = 1, } In addition, there are object types defined to hold data required for each operation: type A = { readonly opType: OpType.OpA; readonly foo: ...

An issue has been detected with the width attribute in Typescript when using

I have a question regarding the TypeScript error related to the width property. I've created a component called ProgressBar where I'm using Stitches for styling. However, TypeScript is throwing an error even when I specify the type as ANY. impor ...

A guide to iterating over an array and displaying individual elements in Vue

In my application, there is a small form where users can add a date with multiple start and end times which are then stored in an array. This process can be repeated as many times as needed. Here is how the array structure looks: datesFinal: {meetingName: ...

React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to ...

Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required. export type Recommendation = { id?: string, name: string, type?: string, tt: string, isin?: string, issuer: string, quantity?: nu ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Unable to retrieve func from PropTypes

Struggling to understand why this specific import, among others, is not functioning properly: import * as React from 'react'; import TextField from '@material-ui/core/TextField'; import * as PropTypes from 'prop-types'; impor ...

Finding the solution to the perplexing issue with Generic in TypeScript

I recently encountered a TypeScript function that utilizes Generics. function task<T>(builder: (props: { propsA: number }, option: T) => void) { return { run: (option: T) => {}, } } However, when I actually use this function, the Gener ...

The "rest" variable is automatically assigned the type of "any" because it lacks a specified type and is used within its own initializer

Attempting to set up a private route using react router 4 and Typescript. Check out the code I'm working with: type CustomRouteProps<T> = T & { component: any, authRequired: boolean }; function PrivateRoute({ component: Component, authRequ ...

Typescript does not process and compile files located within a specified directory

Recently, I embarked on a small TypeScript project and took the time to create the tsconfig.json configuration file. { "compilerOptions": { "target": "es5", "module": "commonjs", "sourceMap": true }, "files": [ "./typings/index.d.ts" ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

An endless cascade of dots appears as the list items are being rendered

Struggling to display intricately nested list elements, Take a look at the JSON configuration below: listItems = { "text": "root", "children": [{ "text": "Level 1", "children": [{ "text": "Level 2", "children": [{ "text": ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

Utilizing Ionic 2 with Typescript for executing forEach operations

I am in the process of migrating my AngularJS application to Angular 2. In my AngularJS controller, I had a JSON array that I was iterating through to display data in an accordion list. Now, I need to implement the same functionality in my Angular 2 compon ...