Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python or TypeScript to transform text that I select in VSCode

Let's say I select some text in the editor. I would like to define my own Python functions or scripts that:

  1. Take as an input the selected text as a string.
  2. Transform it and return a new string that replaces the selected text back in the editor

Moreover, I would like to ideally register these functions or scripts as a VSCode commands (with a specific commandIDs) that I can define myself and to the command palette in VSCode. By doing so, I can bind them to a shortcut in keybindings.json with specific shortcuts and when clauses.


Is there any built-in functionality in VSCode to do this? If not, what set of steps can I follow to do it?

like image 928
Amelio Vazquez-Reina Avatar asked Nov 26 '19 23:11

Amelio Vazquez-Reina


People also ask

How do I change the selected words in VS Code?

Expand the Search widget to display the Replace text box. When you type text into the Replace text box, you will see a diff display of the pending changes. You can replace across all files from the Replace text box, replace all in one file or replace a single change.

How does Python interpreter choose VS Code?

Select and activate an environment# By default, the Python extension looks for and uses the first Python interpreter it finds in the system path. To select a specific environment, use the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).


2 Answers

Disclaimer: We are the author of vscode-texty extension

Based on OP's suggestion, we have enhanced the vscode-texty to add this support.

Now it supports following capabilities.

  • Select some text and process selection using adhoc script
  • Select some text and process line within selection using adhoc script
  • Custom script can refer to lodash, numeral and moment libraries for easy manipulation of text
  • Save the script as custom command and invoke that command with quick pick options
  • Key bind that custom command for quick execution

One issue (due to limitation of vscode api) is that, custom commands does not appear in the standard command palette. So to invoke via UI, you first invoke command Texty: Process selections using custom command, which shows all available commands as quick pick options, executes the selection.

enter image description here

like image 62
metasync Avatar answered Oct 26 '22 22:10

metasync


It is technically possible, but I'm unaware of any extension that currently supports this idea. You will probably need to write your extension to do this.

like image 42
Brett Cannon Avatar answered Oct 26 '22 23:10

Brett Cannon