How Do I stop VSCode from auto-filling unnecessary words on save? - visual-studio-code

I'm running this code and every time I save, it adds 3 other words that I didn't want to be added.
useEffect(() => {
const fuse = new Fuse(slideRows, { keys: ['data.description', 'data.title', 'data.genre'] });
const results = fuse.search(searchTerm).map(({ item }) => item);
if (slideRows.length > 0 && searchTerm.length > 3 && results.length > 0) {
setSlideRows(results);
} else {
setSlideRows(slides[category]);
}
}, [category, searchTerm, slideRows, slides])
The last line of code I only one one word searchTerm but vs code keeps auto filling the array with the other 3 words.
Is there a setting to prevent this or how do I solve this issue?

because of this it will create infinite loop.you can disable eslint plugging and try if you are using that.because this will do auto filling.

Related

Problem understanding VSCode extension for code completion

I am trying to have language support in VSCode for an assembler targeting a programmable ASIC.
So far I have only the TextMate grammar and I am now trying to understand how to implement a language server.
I am learning from
https://github.com/Microsoft/vscode-extension-samples/tree/master/lsp-sample
and have come so far as to have my environment up for debugging.
Where I am struggling is that I do not understand how the completion mechanism is done in the example.
What I see when debugging is that as soon the first letter (word boundary) is an:
j or J a small text popup with a string JavaScript(J highlighted) and details shows so I can select without typing
t or T the same but for TypeScript(T highlighted)
s or S gives a list of the both previous popups(S highlighted on both) and arrow up/down for selection
The only code covering this, as I understand it, is this section in the server.ts file
// This handler provides the initial list of the completion items.
connection.onCompletion(
(_textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
// The pass parameter contains the position of the text document in
// which code complete got requested. For the example we ignore this
// info and always provide the same completion items.
return [
{
label: 'TypeScript',
kind: CompletionItemKind.Text,
data: 1
},
{
label: 'JavaScript',
kind: CompletionItemKind.Text,
data: 2
}
];
}
);
// This handler resolves additional information for the item selected in
// the completion list.
connection.onCompletionResolve(
(item: CompletionItem): CompletionItem => {
if (item.data === 1) {
item.detail = 'TypeScript details';
item.documentation = 'TypeScript documentation';
} else if (item.data === 2) {
item.detail = 'JavaScript details';
item.documentation = 'JavaScript documentation';
}
return item;
}
);
I have tested with more labels and it appears as the Completionparser checks for capital letters in the labels.
Added 2 more labels, 'TwoMore' and 'JetBrain' and they behaved in the same way, e.g. m/M or b/B also gave a popup.
What is not obvious is why this is so?

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);

Bootstrap tour backdrop blinking between steps

There is an annoying effect in v0.12.0 of Bootstrap tour when activating backdrop.
It works, but once you click next step, backdrops disapears for a moment and appears again doing a blink.
Anyone has a way to deactivate this behavior or a fix for this?
This is the last version... and it is 1 year old by now.
Well I did something that worked.
In the "hidestep" function I changed the condition, removing the last or statement:
if (step.backdrop) {
next_step = (iNext != null) && _this.getStep(iNext);
if (!next_step || !next_step.backdrop /*|| next_step.backdropElement !== step.backdropElement*/) {
_this._hideOverlayElement(step);
}
}
So it ends:
if (step.backdrop) {
next_step = (iNext != null) && _this.getStep(iNext);
if (!next_step || !next_step.backdrop ) {
_this._hideOverlayElement(step);
}
}

Pressing enter key creates a blank span in tinymce editor

I am using tinyMCE editor in one of my project. When I press enter key inside the equation box,I want to reload the contents of the editor.It works well now but the problem I am facing here is an empty span with class AM that is automatically created on pressing enter key.The tinymce function for reloading the contents is :
tinyMCE.execCommand("mceRepaint");
I have made a javascript functin for this which is given below :
function loadlistener() {
//console.log('load');
$("#elm1_ifr").contents().keydown(function (event) {
//console.log('key');
var code = (event.keyCode ? event.keyCode : event.which);
//console.log(code);
if (code == 13 && amedit) {
tinyMCE.execCommand("mceRepaint");
tinyMCE.activeEditor.focus();
}
});
var p_parent = $("#elm1_ifr").contents().find("p");
setInterval(function () {
if (p_parent.find('span').length && p_parent.find('span')) {
amedit = true;
} else {
amedit = false;
}
}, 200)
};
So my question is how to prevent the creation of this empty span when enter key is pressed.
You can check it live Here
Pleas inspect the html so you can understand my question more clearly.

forced_root_block option in TinyMCE

I am trying to implement a custom WYSIWYG editor using a contenteditable <div>.
One of the major issues I am facing is the inconsistent way browsers handle ENTER keystroke (linebreaks). Chrome inserts <div>, Firefox inserts <br> and IE inserts <p>. I was taking a look at TinyMCE and it has a configuration option called forced_root_block. Setting forced_root_block to div actually works across all major browser. Does someone know how forced_root_block option in TinyMCE is able to achieve it across browsers ?
In the tinymce source (/tiny_mce/classs/dom/DomParser.js) you will find the following:
rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
whiteSpaceElements = schema.getWhiteSpaceElements();
startWhiteSpaceRegExp = /^[ \t\r\n]+/;
endWhiteSpaceRegExp = /[ \t\r\n]+$/;
allWhiteSpaceRegExp = /[ \t\r\n]+/g;
function addRootBlocks() {
var node = rootNode.firstChild, next, rootBlockNode;
while (node) {
next = node.next;
if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) {
if (!rootBlockNode) {
// Create a new root block element
rootBlockNode = createNode(rootBlockName, 1);
rootNode.insert(rootBlockNode, node);
rootBlockNode.append(node);
} else
rootBlockNode.append(node);
} else {
rootBlockNode = null;
}
node = next;
};
};
This obviously takes care of creating root block elements.
I am 99% sure that tinymce handles the 'ENTER' keystroke itself and stops the propagation/ default browser command.