Can I define a task for Replace Operation in vscode? - visual-studio-code

I replace every debugger; phrase with "" in my solution some times a day. I thought it could be well if there is a way to define a task for this operation.
Do you know the solution. is there this feature?

You will need a macro extension such as multi-command. It will allow you to chain commands together to run with one keybinding.
In your settings.json:
{
"command": "multiCommand.removeDebugger",
// "interval": 250,
"sequence": [
"workbench.action.findInFiles",
// "toggleSearchRegex", // depending if the default is regex on or off
// and where you want it to end up
"search.action.refreshSearchResults",
"workbench.action.replaceInFiles",
"search.focus.nextInputBox",
"editor.action.clipboardCutAction",
"search.action.replaceAll"
]
},
This will open the "Find In Files" panel. Then it will run the command to actually search for your chosen string across files (which is a necessary step before doing a replace). Then it will move to the "replace input box", clear its contents (since you want to replace "debugger;" with nothing) and run the replace in all files command. VSCode will prompt you if you really want to do it.
In your keybindings.json put some keybinding of your choice, such as:
{
"key": "ctrl+alt+u",
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.removeDebugger" }
},
The only requirement is that you highlight the phrase you want to search for first - in your case debugger;- and then trigger it with Ctrl-Alt-U or whatever.
Here is a demo gif of it working - I slowed it way down so it could seen going through the steps:
. The gif software is wonky on the keystrokes - it is just Ctrl-Alt-U.

I have created a VSCode extension for this task. It registers a command Remove Debugger Statements bound to ctrl+alt+shift+d on windows and ctrl+cmd+shift+d on mac to perform the required action.
Additionally, it also has settings to specify the files/folders to include/exclude while performing the action.

Related

Fold Results in VSCode Search Editor (*not* search explorer)

I'm looking for a way to fold all results in a VSCode search editor. (It's clear how to do this in the search explorer.)
I can easily fold individual results with cmd+opt+[ but I want to fold all of the results. I'd actually like to be able to have that be the default.
You can fold all the results by doing this:
Select all Ctrl+A
Command Palette: Create Manual Folding Range From Selection
That Manual Folding Range command has a default keybinding: Ctrl+K Ctrl+,
You could put those two commands into a macro if you wanted, see the macro extension multi-command.
I don't think there is any way to have the Search Editor default to all folded - unless you put however you open that into the macro as well.
Doing that using multi-command, make this keybinding:
{
"key": "ctrl+w", // whatever keybinding you want
"command": "extension.multiCommand.execute",
"args": {
"interval": 500, // you need some delay to open the editor first
"sequence": [
"search.action.openInEditor",
"editor.action.selectAll",
"editor.createFoldingRangeFromSelection"
]
},
"when": "hasSearchResult && searchViewletFocus"
}
I found the cmd+k, cmd+0 will fold all up to the first line, but then I can open enough to see what I need. Not ideal, but useable.

How to sync search term between tab groups?

It's common for me to have two tab groups open to compare things side-by-side but when I am searching for a term I find it a bit annoying that the search term isn't shared by the two editors. e.g. I ctrl-F3 on a word in the file to the left to start searching, then move over to the file on the right and I'd like to just hit F3 in order to continue searching for the same word, but it has it's own term saved to search for.
I assumed that this would be an option somewhere, but I don't see it in the Text Editor -> Find section of the pref's. Am I just blind and not seeing it or does this option not exist in VS Code?
Update: see https://stackoverflow.com/a/65851872/836330 "Searching only in open editors" might work for you.
I don't think there is an option to tie the find's together between groups like that. But with a macro you could do this fairly easily. Using a macro extension like multi-command put this into your settings:
"multiCommand.commands": [
{
"command": "multiCommand.findAcrossGroups",
"sequence": [
"editor.action.addSelectionToNextFindMatch",
"editor.action.clipboardCopyAction",
"workbench.action.focusNextGroup",
"actions.find",
"editor.action.clipboardPasteAction",
"editor.action.nextSelectionMatchFindAction",
"workbench.action.focusPreviousGroup" // to return to first group
]
}
]
and a keybinding to trigger it (in keybindings.json):
{
"key": "alt+s", // whatever binding you wish
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.findAcrossGroups" },
"when": "editorTextFocus"
}
How you would use this is when you trigger the keybinding, whatever word is under your cursor in group 1 will be transferred to the find widget in group 2 (and focus will return to group 1, don't use the last command "workbench.action.focusPreviousGroup" if you want to use this as you move to the next group. And then F3 works as you expect when you switch to group 2.
One downside to this approach is that it needs to use your clipboard to transfer the word under the cursor, that may not be an issue for you.
I made this to work with two groups primarily, although it really uses next/previous groups so it also works for any two adjoining group. It could be generalizeed to three groups pretty easily - beyond that it would probably be easier to make an extension to work with as many groups as you have open.

VSCode: Store and reopen a group of file tabs so that I reset a specific environment in the future

VSCode remembers the file tabs that are open in my Workspace from the last environment, and so if I close VSCode and re-open, I have the same files opened.
Over a day or two of work, I may switch between 2 or 3 different feature branches while my PR's are going through review.
Each feature branch is usually on a totally different area of the code base, which means, I will want to open different groups of files when working on each branch.
I wonder if there is a way to save snapshots of open tabs so that I can re-reopen in future.
A really nice flow would be to have those files open automatically whilst other files close when VSCode detects a branch change.
Get a "snapshot" of currently opened files.
Save this snapshot somewhere; make it easy to change.
Use the snapshot to open all of its files; close all other files first.
Be able to make multiple snapshots and call each one easily.
(1) is harder than you might think. There are a number of vscode issues about searching only within the currently opened files and the problem remains largely unsolved after a few years for this reason.
Demo: get the relative paths of all opened files (unfortunately the gif creation software did a poor job of capturing all the keystrokes used in all these demos) :
Holy crap, what just happened. One keybinding and they are collected and formatted in a specific way.
A number of things happened. The only way I know of to efficiently get a list of opened files (maybe true even in an extension) is through the "Open Editors" view. So we
(a) focus that Open Editors view,
(b) select the entire list, and fortunately there is a
(c) copyRelativeFilePath command (or copyPath for the full path) that will get them all in a list.
But the list initially looks like:
1.html
simple\\gulpfile.js
test1.txt
which isn't going to do us much good. But it is now on the ClipBoard and there is an extension, Replace Rules that is able to run the Clipboard content through a series of regex's (without modifying the Clipboard content either) and paste the result somewhere. So you will need that extension and a macro extension, here using multi-command to run all the steps. Here is the macro which goes into your settings.json:
"multiCommand.commands": [
{
"command": "multiCommand.getOpenedEditorsForTaskOpenAll",
"interval": 50,
"sequence": [
"workbench.files.action.focusOpenEditorsView",
"list.selectAll",
"copyRelativeFilePath",
// "copyFilePath",
"workbench.action.focusActiveEditorGroup",
{
"command": "replacerules.pasteAndReplace",
"args": {
"ruleName": "Prepare file list for task open"
}
},
"editor.action.formatSelection",
"cancelSelection",
"deleteLeft"
]
}
]
Here is the replacerules rule that is used in the macro:
"replacerules.rules": {
"Prepare file list for task open": {
"find": ["(\\\\)", "^(.+)$"],
"replace": ["\\\\", "\"'$1'\","]
}
}
It just modifies that bare file list into something we can use in a task. Here is a keybinding to run that macro (keybindings.json):
{
"key": "ctrl+shift+i",
"command": "extension.multiCommand.execute",
"args": {
"command": "multiCommand.getOpenedEditorsForTaskOpenAll"
},
}
You should be able to test this already to see if it'll dump the formatted file list to wherever your cursor is in the current text editor.
One way to open up all these files at once is to put them into a task (in tasks.json):
{
"label": "Open snapshot 1",
"command": "code",
"args": [
],
"type": "shell",
"problemMatcher": [],
"dependsOrder": "sequence",
"dependsOn": [ "close all editors" ]
},
{
"label": "close all editors",
"command": "${command:workbench.action.closeAllEditors}",
"type": "shell",
"problemMatcher": []
},
You see the task Open snapshot 1 is dependent on the close all editors task so that happens first. In the Open snapshot 1 the command is code to open all the arg files. Put your cursor in the args array and that is where the properly formatted list of files to open will be written by the macro. Demo:
If you want to update that file list you can just select them and rerun the macro. And you can now set up as many Open snapshot <n> tasks as you want (with whatever labels you want to give them).
Now, to trigger the task we will use a keybinding as well:
{
"key": "alt+s 1",
"command": "workbench.action.tasks.runTask",
"args": "Open snapshot 1"
},
{
"key": "alt+s 2",
"command": "workbench.action.tasks.runTask",
"args": "Open snapshot 2"
},
etc. As noted earlier, running this task will first run the dependent task which closes all currently opened files. If you just wanted to open a batch of files you frequently use without closing the others, just remove the "dependsOn": [ "close all editors" ] option.
Here is a final demo of the task closing the open files and opening the snapshot files (I just changed the file list above a little to make it look different).
Two things to remember:
(1) the Editor > Open Editors: Visible setting must be enable with a number high enough to show all your opened files. The Open Editors can be hidden so you don't have to look at it all the time if you don't want, but it will be opened automatically by the macro - that can't be avoided. You can see it opening in the demos. It can be hidden by its context menu.
(2) The terminal is used, so you see it opening.
It seems like a lot of set-up but the operation is actually pretty simple - just a couple of keybindings to remember.
Try an extension called File Group.
My searching reveled that a lot of people are looking for this option but vsCode does not seem to have any good way to do it. This extension lets you list out the files with full path and associate them to a key shortcut.
Three files below will load by hitting ctrl-alt-1 if you add this to youProject.code-workspace:
"1": {
"files": [
"C:\\temp\\file1.txt",
"C:\\svn\\foo.txt",
"C:\inetpub\wwwroot\iisstart.htm"
]
}
(It is a pain to set up if you are new to vsCode, hopefully it gets developed further.)
This worked for me. But it may have side affects when git does refresh
https://marketplace.visualstudio.com/items?itemName=gkotas.restore-git-branch-tabs
It seems that there is an extension that does the job: Editor Group Minimizer
There's this extension, that seems to kind of work:
Save and Restore Tabs
It seems to get most of the files and maintains the file split, but if I have multiple tabs on multiple groups, sometimes the secondary ones aren't opened.
There's an extension that would save your open tabs and swap them based on your git branch. Seems very useful, but in practice it was a little too intrusive.
Looks like its been abandoned, but there's this fork: Restore Git Branch Tabs Improved Tried it but isn't worked like I remember but maybe I just missed something for setup.

Perform pre-defined Find-Replace-All in VSCode using a keybinding

I can't seem to find a good list of documented commands that can be run from VSCode keybindings.
On the online VSCode documentation, the Commands Guide lists two ways to discover commands:
Browse the keyboard shortcuts
Look through VS Code's built-in
advanced commands api
The commands found for keyboard shortcuts are usually "simple" commands that do not take arguments. The "advanced commands api" seems to be missing some very basic, fundamental commands.
For example, on the VSCode Keybindings page there is a section called "Command Arguments" that has the following example entry:
{ "key": "enter", "command": "type",
"args": { "text": "Hello World" },
"when": "editorTextFocus" }
But I don't see anywhere that the type command is documented. So I assume there are probably several other basic commands like this that exist but I don't know where to find documentation for them.
Anyway, what I am really looking for at the moment is a command that I can run to do a pre-defined search and replace in the current editor, specifying the find text, replacement text, and options... something like below:
{ "key": "ctrl+shift+8",
"command": "findReplaceAll",
"args": {
"findText": "Company(\\w+)",
"replaceText": "User$1"
"options": { "ignoreCase": false, "wholeWord": true, "regex": true }
},
"when": "editorTextFocus" }
But I haven't been able to find any such findReplaceAll command or anything similar in the documentation, but certainly something like this must exist, right?
Thanks!
As #AurSaraf points out, there is new work coming that will allow creating a command (or use in an extension) of a built-in way to find in the current file with preset find/replace and options.
I have commented on the github issues trying to get the args to be consistent with other similar commands to no avail. Here are the current available args in a keybinding:
{
"key": "alt+p",
"command": "editor.actions.findWithArgs",
"args": {
"searchString": "howd\\d", // double-escaped
"replaceString": "qqqq9",
"isRegex": true,
// "regexOverride": 1,
"findInSelection": false,
"matchWholeWord": false,
// "matchCase": false,
// "matchCaseOverride": 0,
"preserveCase": false,
"isCaseSensitive": false
// "preserveCaseOverride": 0,
// "wholeWordOverride": 0
}
}
The commented-out args are not available although intellisense shows that they are - so the command is still a little "rough" - and currently available only in the Insiders Build. Do not rely on the intellisense for the args keys - many of them are mis-named or non-functional at this point.
Also, note that instead of query and replace as used in the workbench.action.findInFiles and in the search.action.openEditor (open a new search editor) keybindings, this command currently uses searchString and replaceString for some reason.
For a powerful extension to do lots of predefined find/replaces or searches/replaces with all arguments, see Find and Transform (which I wrote). In particular with a lot of options for setting the files to include scope filter - like the current file or the last files found in the previous search results to narrow a search to only those files.
There is also a built-in way to do this for finding across files, I don't know if arguments were added after your question or not. In any case, I agree that it is sometimes difficult to discover which commands can take arguments.
Sometimes, intellisense within the keybindings in your command will surface them but not always.
So examining this:
{
"key": "ctrl+shift+f",
"command": "workbench.action.findInFiles",
"args": {
<cursor here> // cursor there and type Ctrl+space
}
}
will show those the available args as in the below example.
{
"key": "ctrl+shift+f",
"command": "workbench.action.findInFiles",
"args": {
"query": "Company(\\w+)", // needs to be double-escaped
"replace": "User$1",
"triggerSearch": true,
"isRegex": true,
// "filesToExclude": "",
// "filesToInclude": "",
"matchWholeWord": true,
"isCaseSensitive": true
}
},
This will perform the search but not do the actual replacement in your files - you will have to trigger replace [all] yourself.
I was looking for an API to do this as an extension writer and it seems one was added less than a month ago (which you could also presumably use to manually define a keybinding, if I understand correctly):
https://github.com/microsoft/vscode/commit/8e96e0b389aedf46423431487190b878d4243edb
Install the extension Replace Rules.
Construct a search-replace in your settings.json (Workspace or User). Read the page about the possibilities.
"replacerules.rules": {
"Replace User": {
"find": "User(\d+)",
"replace": "Player$1"
}
}
In keybindings.json define the following keybinding:
{
"key": "ctrl+shift+alt+u",
"command": "replacerules.runRule",
"when": "editorTextFocus",
"args": { "ruleName": "Replace User"}
}
If you select some text the search-replace will only be performed within the selection.
If you are willing to use tasks.json; a native VS Code concept -- and you have access to a shell like bash (I use Windows with GitBash), or Powershell (builtin to Windows), you can use the power of that shell without a VS Code extension, or any new deployments -- in my case, I use sed command to make file replacements:
{
"label": "find-replace-task-name",
"type": "shell",
"command": "sed -i -E \"s/Company(\\w+)/User\\1/g; s/user/User/g\" \"${file}\""
},
Advantages of using tasks.json with a shell command:
In my case, I want to other developers on my team to use my solution, so I like using the tasks.json because it's stored in the .vscode folder, which we do include in our version control (keybindings.json is not stored in .vscode folder)
I can use my solution on today's version of VSCode (I don't need Insiders build),
I can use my it without installing any VSCode extension.
Because my task relies on a shell, I get the power of a shell and any of its "builtin" commands
In my case, I could use the bash shell and the sed utility, which are powerful, expressive and easy-to-use for file manipulation (including find-replace).
A shell helps me approach this question from a different angle; i.e. "how to find-replace a file, using (bash|Powershell)..." (So you could adapt this approach to Powershell instead of bash, more on that...)
Notice:
I used sed to perform multiple find-replacements (which I needed, the OP of this question did not need - So I chained a replacement of "user"->"User" in my command)
I used the "${file}" variable replacement to pass the filepath to the currently-open-file
And I can associate with a keybinding so it's easier to run the task. Notice the keybinding only works "when":"editorTextFocus", maybe I should add a condition that there is some file open!
{
"key": "ctrl+shift+alt+s",
"when": "editorTextFocus",
"command": "workbench.action.tasks.runTask",
"args": "find-replace-task-name"
}
There are some disadvantages to my approach:
the sed script I write is very dense, and has multiple levels of "escape characters", so it's hard to read/interpret/troubleshoot (compared to an easy-to-read JSON snippet like {"searchString":..., "replaceString":...})
it operates on the file outside of VS Code, so no "Undo" operation it seems like you can "undo" the changes, specifically you would "undo" VS Code's automatic reloading of the file, (VS Code probably recognizes that sed modified the file; but VS Code still lets you "Ctrl+Z" to go back before the modifications)
can't work unless you have a file open
doesn't use the $1 for RegEx replacement, instead uses the "extended regular expressions" flag -E and the syntax \1, etc
etc...

How to Create Custom Key Binded Snippets in VS Code

I am a huge Sublime Text user, and learned ways to improve my productivity using customizations in Sublime text. But as VScode is becoming popular day by day, wanted to check if there is any way which I can bind the shortcut keys to the custom actions.
For example, I select a word ABC in any file in VSCode and hit CTRL+B, and it places my own defined values around it like it should become
<b>ABC</b>
I had created the following snippet in Sublime Text, which when I wrote in Visual Studio Code - keybindings.json nothing worked.
{
"keys": [
"ctrl+b"
],
"command": "insert_snippet",
"args": {
"contents": "<b>${0:$SELECTION}</b>"
}
}
This will work in your keybindings.json:
{
"key": "ctrl+b",
"command": "editor.action.insertSnippet",
"when": "resourceExtname == .html", // this is optional
"args": {
"snippet": "<b>${TM_SELECTED_TEXT}</b>"
}
},
The optional when clause is if you want to limit the snippet's operation to .html files.
More general though is to use the emmet command which is built-in: Emmet: Wrap with Abbreviation in the command palette. Select your text, open the command palette, find that command and trigger it - type b or whatever your element is and it will wrap the selected text with the opening and closing elements.
[Note that there is a command workbench.action.toggleSidebarVisibility already bound to Ctrl-B, but the snippet above version seems to take precedence - meaning you lose the toggleSidebarVisibility keybinding functionality - that may be acceptable to you?]