Set selection to a string in codemirror - 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);
}

Related

How to search for and highlight a substring in Codemirror 6?

I'm building a simple code editor to help children learn HTML. One feature I'm trying to add is that when users mouseover their rendered code (in an iframe), the corresponding HTML code in the editor is highlighted. So, for example, if a user mouses-over an image of kittens, the actual code, , would be highlighted in the editor.
Mousing-over the iframe to get the html source for that element is the easy part, which I've done (using document.elementFromPoint(e.clientX, e.clientY in the iframe itself, and posting that up to the parent) - so that's not the part I need help with. The part I can't figure out is how to search for and highlight that string of selected code in the code editor.
I'm using Codemirror 6 for this project, as it seems as it will give me the most flexibility to create such a feature. However, as a Codemirror 6 novice, I'm struggling with the documentation to find out where I should start. It seems like the steps I need to complete to accomplish this are:
Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"').
Highlight that range in the editor.
Can anyone out there give me some advice as to where in the Codemirror 6 API I should look to start implementing this? It seems like it should be easy, but my unfamiliarity with the Codemirror API and the terse documentation is making this difficult.
1. Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"').
You can use SearchCursor class (iterator) to get the character's range where is located the DOM element in your editor.
// the import for SearchCursor class
import {SearchCursor} from "#codemirror/search"
// your editor's view
let main_view = new EditorView({ /* your code */ });
// will create a cursor based on the doc content and the DOM element as a string (outerHTML)
let cursor = new SearchCursor(main_view.state.doc, element.outerHTML);
// will search the first match of the string element.outerHTML in the editor view main_view.state.doc
cursor.next()
// display the range where is located your DOM element in your editor
console.log(cursor.value);
2. Highlight that range in the editor.
As described in the migration documentation here, marked text is replace by decoration. To highlight a range in the editor with codemirror 6, you need to create one decoration and apply it in a dispatch on your view. This decoration need to be provide by an extension that you add in the extensions of your editor view.
// the import for the 3 new classes
import {StateEffect, StateField} from "#codemirror/state"
import {Decoration} from "#codemirror/view"
// code mirror effect that you will use to define the effect you want (the decoration)
const highlight_effect = StateEffect.define();
// define a new field that will be attached to your view state as an extension, update will be called at each editor's change
const highlight_extension = StateField.define({
create() { return Decoration.none },
update(value, transaction) {
value = value.map(transaction.changes)
for (let effect of transaction.effects) {
if (effect.is(highlight_effect)) value = value.update({add: effect.value, sort: true})
}
return value
},
provide: f => EditorView.decorations.from(f)
});
// this is your decoration where you can define the change you want : a css class or directly css attributes
const highlight_decoration = Decoration.mark({
// attributes: {style: "background-color: red"}
class: 'red_back'
});
// your editor's view
let main_view = new EditorView({
extensions: [highlight_extension]
});
// this is where the change takes effect by the dispatch. The of method instanciate the effect. You need to put this code where you want the change to take place
main_view.dispatch({
effects: highlight_effect.of([highlight_decoration.range(cursor.value.from, cursor.value.to)])
});
Hope it will help you to implement what you want ;)
Have a look at #codemirror/search.
Specifically, the source code implementation of Selection Matching may be of use for you to adapt.
It uses Decoration.mark over a range of text.
You can use SearchCursor to iterate over ranges that match your pattern (or RegExpCursor)
Use getSearchCursor, something like this:
var cursor = cmEditor.getSearchCursor(keyword , CodeMirror.Pos(cmEditor.firstLine(), 0), {caseFold: true, multiline: true});
if(cursor.find(false)){ //move to that position.
cmEditor.setSelection(cursor.from(), cursor.to());
cmEditor.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
}
Programmatically search and select a keyword
Take a look at getSearchCursor source code it it give some glow about how it works and its usage.
So use getSearchCursor for finding text and optionally use markText for highlighting text because you can mark text with setSelection method of editor.
Selection Marking Demo
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
styleSelectedText: true
});
editor.markText({line: 6, ch: 26}, {line: 6, ch: 42}, {className: "styled-background"});
And it seem this is what you are looking for:
codemirror: search and highlight multipule words without dialog
RegExpCursor is another option that you can use:
new RegExpCursor(
text: Text,
query: string,
options⁠?: {ignoreCase⁠?: boolean},
from⁠?: number = 0,
to⁠?: number = text.length
)
Sample usage at:
Replacing text between dollar signs for Mathml expression.

Get vscode registerCompletionItemProvider to work in a json file with a `word.` trigger

Update
Thanks to json: use default word pattern issue being resolved, vscode's json language server no longer includes the quotes around a word as part of the word, like "someWord" - now that word would be simply someWord.
In my case, as #rioV8 said, I was not explicitly setting the completionItem.range (because I was just going to use the default range). When you do not set your own range vscode uses the range of the word at the cursor in a completion - which used to include the " and that screwed up my completions.
The starting quote " is part of what VSCode considers the current
"word". Consequently, the completion items you return don't match the
current filter string " and are not displayed.
from Custom Extension for JSON Completion Does Not Work in Double Quotes
To fix that, all I needed to do was to explicity set the range like
item.range = new vscode.Range(position, position);
NOW after the linked fix, since the word no longer includes the " I do not (I tested it) need to explcitly set the range and the default range works fine.
I am using this code to try to register a CompletionProvider in my extension. It is essentially the code from the sample completionProvider sample https://github.com/microsoft/vscode-extension-samples/blob/master/completions-sample/src/extension.ts.
I want it triggered by a . as in "launches." in my extension command in keybindings.json ultimately but it is doing nothing in any json file. Nothing happens, no error.
function activate(context) {
loadLaunchSettings(context);
activeContext = context;
const configCompletionProvider = vscode.languages.registerCompletionItemProvider (
{ language: 'json', scheme: 'file' }, // tried scheme: 'untitled' too
{
// eslint-disable-next-line no-unused-vars
provideCompletionItems(document, position, token, context) {
// get all text until the `position` and check if it reads `"launches."`
const linePrefix = document.lineAt(position).text.substr(0, position.character);
if (!linePrefix.endsWith('\"launches.\"')) { // tried without the escapes too
return undefined;
}
return [
new vscode.CompletionItem('log', vscode.CompletionItemKind.Text),
new vscode.CompletionItem('warn', vscode.CompletionItemKind.Text),
new vscode.CompletionItem('error', vscode.CompletionItemKind.Text),
];
}
},
'.' // trigger
);
context.subscriptions.push(configCompletionProvider);
}
In this code:
{
"key": "alt+f",
"command": "launches." <= provider completion options here
},
I couldn't find anything helpful and thought I followed the sample closely but no completion suggestions either on typing "launches." or using Ctrl+Space to trigger intellisense.
I do have this setting:
"editor.quickSuggestions": {
"comments": true,
"other": true,
"strings": true // <===
},
And I tried various alternatives presented here to a similar problem: Custom Extension for JSON Completion Does Not Work in Double Quotes
Based on the answer by Gamma11 about what is a word in JSON, the whole string is considered a word including the " chars.
It works if you adjust the range the completion item should replace, and not look for the current word at the position.
context.subscriptions.push(vscode.languages.registerCompletionItemProvider (
{ language: 'json', scheme: 'file' },
// 'json',
{
// eslint-disable-next-line no-unused-vars
provideCompletionItems(document, position, token, context) {
// get all text until the `position` and check if it reads `"launches.`
const linePrefix = document.lineAt(position).text.substring(0, position.character);
if (!linePrefix.endsWith('"launches.')) {
return undefined;
}
let myitem = (text) => {
let item = new vscode.CompletionItem(text, vscode.CompletionItemKind.Text);
item.range = new vscode.Range(position, position);
return item;
}
return [
myitem('log'),
myitem('warn'),
myitem('error'),
];
}
},
'.' // trigger
));
Edit:
What also works but does not look nice is
return [
new vscode.CompletionItem('"launches.log"', vscode.CompletionItemKind.Text),
new vscode.CompletionItem('"launches.warn"', vscode.CompletionItemKind.Text),
new vscode.CompletionItem('"launches.error"', vscode.CompletionItemKind.Text),
];
Edit:
Just to supply a completion on any . typed I just removed the test (endsWith) of what was in front of the ..
To see if the completion provider is called I place a LogPoint breakpoint on the return with the CompletionItems.
The documentation of the CompletionItem is very terse.
From the doc of CompletionItem:
It is sufficient to create a completion item from just a label. In that case the completion item will replace the word until the cursor with the given label or insertText. Otherwise the given edit is used.
Although they talk about an edit in the main text, the textEdit doc tells you it is deprecated and you need to use insertText and range. But the additionalTextEdits are not deprecated (??)
The range property is not very clear how an inserting and replacing range are used and what effect you can achieve by setting it a certain way.
When omitted, the range of the current word is used as replace-range and as insert-range the start of the current word to the current position is used.
And then part of the problem is that " is part of a word for JSON files. And as Gamma11 has pointed out if you, for some odd reason, add these "'s to the label it works in some cases. Setting the insertText with the same content does not work, probably because the default range is chosen incorrectly.
If you set the range yourself you bypass the strange default behavior.
Because we want to insert new stuff at the position of the cursor just set range to an empty range at the cursor position.
context.subscriptions.push(vscode.languages.registerCompletionItemProvider (
// { language: 'json', scheme: 'file' },
'json',
{
// eslint-disable-next-line no-unused-vars
provideCompletionItems(document, position, token, context) {
let myitem = (text) => {
let item = new vscode.CompletionItem(text, vscode.CompletionItemKind.Text);
item.range = new vscode.Range(position, position);
return item;
}
return [
myitem('howdy1'),
myitem('howdy2'),
myitem('howdy3'),
];
}
},
'.' // trigger
));

Showing a div hidden by default

I have a script that shows/hides a div. This is the code:
$('#container2').toggleClass(localStorage.toggled);
/* Toggle */
$('.bar-toggle').on('click',function(){
//localstorage values are always strings (no booleans)
if (localStorage.toggled != "with_toggle" ) {
$('#container2').toggleClass("with_toggle", true );
localStorage.toggled = "with_toggle";
} else {
$('#container2').toggleClass("with_toggle", false );
localStorage.toggled = "";
}
});
I want to hide the div by default. How can i modify it?
I can think of several answers, as your question is under-specified. Since you included local storage in the first place, I am going to assume that the with_toggle class will cause your div to be shown and that you simply need to apply your default toggled value (null) correctly.
function applyToggle() {
// JS uses "truthy" booleans - "" and null will be interpreted as false,
// and "with_toggle" will be interpreted as true.
$('#container2').toggleClass("with_toggle", localStorage.getItem('toggled'));
}
applyToggle();
/* Toggle */
$('.bar-toggle').on('click', function() {
//localstorage values are always strings (no booleans)
localStorage.setItem('toggled', localStorage.getItem('toggled') ? "" : "with_toggle");
applyToggle();
});
Generally speaking, it is a good idea to separate your model (data) from your view (rendering), as I did above. Spaghetti is hard to maintain.

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

Inserting a new text at given cursor position

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