Inserting a new text at given cursor position - codemirror

I am working on customizing the codemirror for my new language mode. As part of this new mode implementation, I am writing a new tool bar where user can select some text and say insert. This command should insert the text where user was typing just before clicking on tool bar.
I could not find any API level support to do so. If there is any other way can someone help me out on this?
Basically get the current cursor positio- line number and position at which cursor is currently present. May be a Position object
API for inserting a text, something like insertText("Text", PositionObject)

Here's how I did it:
function insertTextAtCursor(editor, text) {
var doc = editor.getDoc();
var cursor = doc.getCursor();
doc.replaceRange(text, cursor);
}

How about replaceSelection (http://codemirror.net/doc/manual.html#replaceSelection)?
doc.replaceSelection(replacement: string, ?select: string)
Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.

To add the new line at the end -
function updateCodeMirror(data){
var cm = $('.CodeMirror')[0].CodeMirror;
var doc = cm.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
var pos = { // create a new object to avoid mutation of the original selection
line: cursor.line,
ch: line.length - 1 // set the character position to the end of the line
}
doc.replaceRange('\n'+data+'\n', pos); // adds a new line
}
Call function
updateCodeMirror("This is new line");

Improved function that, if selection present, replaces the text, if not, inserts in current cursor position
function insertString(editor,str){
var selection = editor.getSelection();
if(selection.length>0){
editor.replaceSelection(str);
}
else{
var doc = editor.getDoc();
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}
}

You want to use the replaceRange function. Even though the name says "replace", it also serves as "insert" depending on the arguments. From the documentation at the time I write this:
Replace the part of the document between from and to with the given
string. from and to must be {line, ch} objects. to can be left off to
simply insert the string at position from. When origin is given, it
will be passed on to "change" events, and its first letter will be
used to determine whether this change can be merged with previous
history events, in the way described for selection origins.

Final function to insert text at current cursor position in a performant way.
Hope it helps.
function insertStringInTemplate(str)
{
var doc = editor_template.getDoc();
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}

This function is used to insert to the specified position and move the cursor to the end of the inserted text.
function insertToCodeMirror(text) {
const doc = codeMirrorInstance.getDoc();
const cursor = codeMirrorInstance.getCursor();
doc.replaceRange(text, cursor);
codeMirrorInstance.focus();
setTimeout(() => {
cursor.ch += text.length;
codeMirrorInstance.setCursor(cursor);
}, 0);
}

Related

Set cursor location in CompletionItem

I want to add numbers to the sass-indentation extension and I kind of figured out how to that, it would be nice if i could set the cursor location when the suggestion gets triggered, just like you can set the cursor location when you make snippets with $1, is that possible ?
import { CompletionItem, CompletionItemKind } from 'vscode';
const sassSchemaTest = [
{
name: '%',
body: '$1%', // I want the cursor location where the '$' sign is
description: 'test'
}
];
export default sassSchemaTest.map(item => {
const completionItem = new CompletionItem(item.name);
completionItem.insertText = item.body;
completionItem.detail = item.description;
completionItem.kind = CompletionItemKind.Property;
return completionItem;
});
Yes, completion items support the usual snippet syntax. Simply use a vscode.SnippetString for insertText instead of a raw string.
A string or snippet that should be inserted in a document when selecting this completion. When falsy the label is used.
completionItem.insertText = new vscode.SnippetString(item.body);

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

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

Set selection to a string in codemirror

I'm trying to set a text selection in CodeMirror based on a predefined string, similar to a find without prompt (i.e. http://perso.jojaba.fr/codemirror-test/codemirror/demo/search-element.html) except not marking the value, but actually putting a selection on the range (which might be multi line, depending on the predefined string). I can't seem to figure out how to set a selection in this way. Any idea.
well, as it turns out the findNext() offered by searchwithoutdialog.js actually does what I need. effectively it's:
instance.on("change", function (cm, change) {
// other code snipped! //
var str = "my replacement";
var token = cm.getTokenAt(change.from, false);
cm.replaceRange(str, { ch: token.start, line: line }, { ch: token.end, line: line });
CodeMirror.commands.findNext(cm, str);
}

Add ondblClick and click event to Codemirror

I would like to add onDblClick event to codemirror 2. I found that onCursorActivity does not deliverer the event so there is no way for me from this method to filter the events.
How can I implement onDbClick event on Codemirror ?
Thanks in advance.
You can call on method on object returned by CodeMirror:
var cm = CodeMirror.fromTextArea(document.querySelector('textarea'));
cm.on('dblclick', function() {
alert('You double click the editor');
});
You can find the list of all available events in documentation.
Register a handler on the element returned by the getWrapperElement() method. Unless you want to not just detect double-clicks, but also prevent the default (select word under mouse cursor) from occurring... in that case I guess some modification of the core code is needed.
http://jsfiddle.net/yusafkhaliq/NZF53/1/
Since codemirror renders inside the element specified you can add an ondblclick event to the element, like below the highlighter renders without line numbers once double clicked that specific elements will display line numbers
var codeelems = document.getElementsByClassName("code");
for (i = 0; i < codeelems.length; i++) {
(function ($this) {
var value = $this.innerHTML;
$this.innerHTML = "";
var editor = CodeMirror($this, {
value: value,
mode: "text/javascript",
lineNumbers: false
});
$this.ondblclick = function () {
editor.setOption("lineNumbers", true);
}
})(codeelems[i]);
}