How to know what suggestion item is selected in vscode - visual-studio-code

I complete a vscode extension by vscode.languages.registerCompletionItemProvider(selector, new FuncCompletionProvider(),'.')
I want to listen which suggestion is selected. In the image below,when I click the current item I want to get the CompletionItem Info.
I tried to use the resolveCompletionItem function, but before the suggestion is selected resolveCompletionItem was triggered.

I tried to use the resolveCompletionItem function, but before the suggestion is selected resolveCompletionItem was triggered.
It appears this is intentional. Per their docs:
Note that this function is called when completion items are already showing in the UI or when an item has been selected for insertion
'selected' meaning selected in the list, not committed
The recommended way to gain insight on when a CompletionItem is inserted is using the CompletionProvider#command property:
An optional command that is executed after inserting this completion. Note that additional modifications to the current document should be described with the additionalTextEdits-property.
Example usage:
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.languages.registerCompletionItemProvider('html', new MyCompletionProvider),
vscode.commands.registerCommand("doTheThing", () => {
console.log('did the thing!!');
});
);
}
class MyCompletionProvider implements vscode.CompletionItemProvider {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> {
const myHTMLCompletionItem: vscode.CompletionItem = new vscode.CompletionItem("myHTML");
myHTMLCompletionItem.command = {
title: '',
command: 'doTheThing'
};
return new vscode.CompletionList([myHTMLCompletionItem]);
}
}

Related

Update global state after RTK Query loads data

I've noticed a problem with splitting responsibilities in React components based on the fetched data using RTK Query.
Basically, I have two components like HomePage and NavigationComponent.
On HomePage I'd like to fetch the information about the user so that I can modify NavigationComponent accordingly.
What I do inside HomePage:
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
dispatch(setNavigationMode(navMode)); // here I change the default Navigation mode
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
The HomePage is a special Page when the NavigationComponent shouldn't display any options for the not logged in user.
Other pages presents additional Logo and Title on Nav.
React communicates:
Warning: Cannot update a component (NavComponent) while rendering a different component (HomePage). To locate the bad setState() call inside HomePage, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
Not sure what is the right way to follow.
Whether the state should be changed in GetUser query after it is loaded - that doesn't seem to be legit.
problem is dispatch calls every render. Instead you can create a navigationSlice (if you don't have already) and use extraReducers for matching your authorization action like:
extraReducers: (builder) => {
builder.addMatcher(
usersApi.endpoints.login.matchFulfilled,
(state, { payload }) => {
if (payload.user) {
state.navigationMode = "all-options"
}
}
);
}
This way, state.navigationMode will only change when authorization changes
The solution was too obvious. The dispatch should be run in useEffect.
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
// changed lines
useEffect( () => {
dispatch(setNavMode(navMode));
}, [navMode, dispatch]);
// /changed lines
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
Thank you #papa-xvii for the hint with changing the navMode after user login. That solves the second problem I had.
However I cannot accept the answer as it does not solve the problem I described above.

VSCode extension - how to alter file's text

I have an extension that grabs the open file's text and alters it. Once the text is altered, how do I put it back into the file that is displayed in VSCode?
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "myExtension" is now active!');
console.log(process.versions);
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('extension.myExtension', () => {
// The code you place here will be executed every time your command is executed
let activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
let text = activeEditor.document.getText();
getAsyncApi(text).then((textToInsertIntoDoc) => {
let finaldoc = insertTextIntoDoc(text, textToInsertIntoDoc);
// not what I want - just used to see new text
vscode.window.showInformationMessage(textToInsertIntoDoc);
});
});
context.subscriptions.push(disposable);
}
The API you can use here is TextEditor.edit, whose definition is
edit(callback: (editBuilder: TextEditorEdit) => void, options?: { undoStopBefore: boolean; undoStopAfter: boolean; }): Thenable<boolean>;
It asks for a callback as the first parameter and in the callback, you can make edits to the document by visiting editBuilder.
I put a sample extension in https://github.com/Microsoft/vscode-extension-samples/tree/master/document-editing-sample which reverses the content in current selection, which is basically a simple use TextEditor.edit.
This is a revision of the main function in Rebornix's extension sample (included with the set of Microsoft extension samples) that handles the selection issues you raised. It reverses the content of the selection(s) (leaving the selections) or if a selection is empty it will reverse the word under the cursor at that selection without leaving anything selected. It often makes sense to leave a selection, but you can add code to remove selection.
let disposable = vscode.commands.registerCommand('extension.reverseWord', function () {
// Get the active text editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
editor.edit(editBuilder => {
editor.selections.forEach(sel => {
const range = sel.isEmpty ? document.getWordRangeAtPosition(sel.start) || sel : sel;
let word = document.getText(range);
let reversed = word.split('').reverse().join('');
editBuilder.replace(range, reversed);
})
}) // apply the (accumulated) replacement(s) (if multiple cursors/selections)
}
});
Admittedly, while I could remove a single selection by setting .selection to a new empty selection that doesn't seem to work with .selections[i]. But you can make multiple changes without having selections in the first place.
What you don't want to do is make a selection through code just to alter text through code. Users make selections, you don't (unless the end purpose of the function is to make a selection).
I came to this question looking for a way to apply a textEdit[] array (which is normally returned by a provideDocumentRangeFormattingEdits callback function). If you build changes in the array you can apply them to your document in your own function:
const { activeTextEditor } = vscode.window;
if (activeTextEditor) {
const { document } = activeTextEditor;
if (document) {
/*
build your textEdits similarly to the above with insert, delete, replace
but not within an editBuilder arrow function
const textEdits: vscode.TextEdit[] = [];
textEdits.push(vscode.TextEdit.replace(...));
textEdits.push(vscode.TextEdit.insert(...));
*/
const workEdits = new vscode.WorkspaceEdit();
workEdits.set(document.uri, textEdits); // give the edits
vscode.workspace.applyEdit(workEdits); // apply the edits
}
}
So that's another way to apply edits to a document. Even though I got the editBuilder sample to work correctly without selecting text, I have had problems with selections in other cases. WorkspaceEdit doesn't select the changes.
Here is the code snippet that will solve your issue :
activeEditor.edit((selectedText) => {
selectedText.replace(activeEditor.selection, newText);
})
Due to the issues I commented about in the above answer, I ended up writing a quick function that does multi-cursor friendly insert, and if the selection was empty, then it does not leave the inserted text selected afterwards (i.e. it has the same intuitive behavior as if you had pressed CTRL + V, or typed text on the keyboard, etc.)
Invoking it is simple:
// x is the cursor index, it can be safely ignored if you don't need it.
InsertText(x => 'Hello World');
Implementation:
function InsertText(getText: (i:number) => string, i: number = 0, wasEmpty: boolean = false) {
let activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) { return; }
let sels = activeEditor.selections;
if (i > 0 && wasEmpty)
{
sels[i - 1] = new vscode.Selection(sels[i - 1].end, sels[i - 1].end);
activeEditor.selections = sels; // required or the selection updates will be ignored! 😱
}
if (i < 0 || i >= sels.length) { return; }
let isEmpty = sels[i].isEmpty;
activeEditor.edit(edit => edit.replace(sels[i], getText(i))).then(x => {
InsertText(getText, i + 1, isEmpty);
});
}
let strContent = "hello world";
const edit = new vscode.WorkspaceEdit();
edit.insert(YOUR_URI, new vscode.Position(0, 0), strContent);
let success = await vscode.workspace.applyEdit(edit);

Ionic3 Action Sheet with Variable Inputs

I need to create an action sheet or some other kind of alert which displays options to a user and saves the option they clicked in a variable. However, the options displayed to the user need to be retrieved from Firestore and are different for each user (each user also may have a different number of options).
I’ve been able to display these options in an action sheet, but I’m struggling to get the value of the option they clicked.
Below is my code for the function so far. The list of options retrieved from Firestore is saved in an array called ‘options’.
categorizeProblem(){
this.action = this.actionCtrl.create({
title: "What sort of problem did this student have?",
})
this.options.forEach(option => {
var button = {
text: option,
value: //option name
handler: (data)=> {
//Need to get the value/name of the option clicked and save this in a variable
}
}
this.action.addButton(button);
})
this.action.present();
}
I would really appreciate if someone could help me with this or suggest an alternate way to do this.
Thanks in advance!
You can use the text property as your identifier. And then your handler should use the old function syntax so you will have the value of handler's this.
Might sound confusing but here's the code, that should demonstrate my point clearly.
presentActionSheet() {
var self = this;
let options = [
"Option1",
"Option2",
"Option3"
];
let actionSheet = this.actionSheetCtrl.create({
title: 'Categories',
});
options.forEach(option => {
actionSheet.addButton({
text: option,
handler: function() {
self.selectedOption = this.text;
}
})
});
actionSheet.present();
}
Here's the running code.

How to remove selection after replace in vscode API

while creating an extension for vscode I got stuck in selection, now the problem is when I replace some range of textEditor through an api it replaces that range as well as make that range selected. For snippets this is a good idea but my extension requirement is not to select replaced text, I searched in api but did't find anything related to remove text selection (Selection occurs when the document is empty)
editor.edit((editBuilder)=>{ //editor is an object of active text editor
editBuilder.replace(textRange,text) // text = 'dummydummydummy'
}) //after this I got the following output
editor.edit(builder => {
builder.replace(selection, newStr);
})
// The edit call returns a promise. When that resolves you can set
// the selection otherwise you interfere with the edit itself.
// So use "then" to sure edit call is done;
.then(success => {
console.log("success:", success);
// Change the selection: start and end position of the new
// selection is same, so it is not to select replaced text;
var postion = editor.selection.end;
editor.selection = new vscode.Selection(postion, postion);
});
I believe that this is happening because the edit is being applied within the current selection. edit returns a promise that is resolved when the edit is applied, and you can use this to set the selection after the edit is successful:
editor.edit((editBuilder) => {
editBuilder.replace(textRange, text)
}).then(success => {
if (success) {
// make selection empty
editor.selection.active = editor.selection.anchor
}
})
let editor = vscode.window.activeTextEditor;
let selection = editor.selection;
editor.edit(builder => {
builder.replace(selection, newStr);
});
see: TextEditorEdit API Doc

kendo ui cancel treeview drop

i have a TreeView that once the user drops the item to the desired position, it displays a dialog box and asks for confirmation, if the user selects cancel, how would i also cancel the placement of the item so it goes back to its original position? my current code is below but isnt working:
var newDiv = $(document.createElement('div'));
newDiv.html('Are you sure you want to move the item: ' + title);
newDiv.dialog( {
autoOpen: true,
width: 600,
buttons: {
"Save": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
e.setValid = false;
}
}
});
I have also tried doing the same kind of code on the dragend event and using e.preventDefault(); with no more luck
The drop event handler provides the setValid function, which can prevent the drop from occurring. For example:
function onDrop(e) {
e.setValid(confirm('Do you wish to move this item here?'));
}
$("#treeView").kendoTreeView({
// ...
dragAndDrop: true,
drop: onDrop
});
I've written a fiddle which demonstrates how this works.
Did you try to use the drop event and call prevent default there if the condition is not satisfied?