I want to build an extension that edits all the links in a file in the editor. If should be something like this
BEFORE:
<img src="assets/images/avatars/avatar-1.jpg" alt="">
<link rel="stylesheet" href="assets/css/icons.css">
<link rel="stylesheet" href="assets/css/uikit.css">
<link rel="stylesheet" href="assets/css/style.css">
AFTER:
<img src="{% static 'assets/images/avatars/avatar-1.jpg' %}" alt="">
<link rel="stylesheet" href="{% static 'assets/css/icons.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/uikit.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/style.css' %}">
This is the code of my extension.js file so far
const vscode = require('vscode');
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
let disposable = vscode.commands.registerCommand('auto-django.autoDjango', function () {
const editor = vscode.window.activeTextEditor
const selection = editor.selection
const text = editor.document.getText(selection)
var regexp = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/g;
var match = regexp.exec(text);
var src = match[1];
const newText = `{% static '${src}' %}`
editor.edit(builder => builder.replace(selection, newText))
});
context.subscriptions.push(disposable);
}
And all this code does is that it takes the first image src link and changes it to the edited link, that is good, but it also replaces it with the whole text in the editor.
But what i want to do is that it should just replace with each of the links in the editor.
Any help will be appreciated. Thanks
First thing I see:
editor.document.getText(some Range) takes a Range not a Selection - that is why it is returning all the document text - it does that when the argument is invalid.
editor.document.getText(new vscode.Range(selection.start, selection.end))
should get you the text of the selection.