VSCode How to _enable_ Regex Find by command, rather than "toggle" - visual-studio-code

I want to write a macro to search for a Regex in VSCode.
Examining the different functionalities available in the editor I find toggleFindRegex, (bound to key Alt-R by default) which works well for interactive use.
However, for a macro a "toggle" won't do. The result could be "on" or "off", fifty-fifty random from the macro's point of view.
Ideally I would need an enableFindRegex function, which doesn't seem to exist, or alternatively a way for the macro to detect the current findRegex state before deciding whether to toggle it or not.
So could anybody point me in the right direction on this?

This can be done with a Joyride function
(defn find-with-regex-on []
(let [selection vscode/window.activeTextEditor.selection
document vscode/window.activeTextEditor.document
selectedText (.getText document selection)
regexp-chars (js/RegExp. #"[.?+*^$\\|(){}[\]]" "g")
newline-chars (js/RegExp. #"\n" "g")
escapedText (-> selectedText
(.replace regexp-chars "\\$&")
(.replace newline-chars "\\n?$&"))]
(vscode/commands.executeCommand
"editor.actions.findWithArgs"
#js {:isRegex true
:searchString escapedText})))
And binding a keyboard shortcut to that function:
{
"key": "cmd+ctrl+alt+f",
"command": "joyride.runCode",
"args": "(my-lib/find-with-regex-on)",
},
Here's the full example: https://github.com/BetterThanTomorrow/joyride/blob/master/examples/README.md#find-in-file-with-regexp-toggled-on

You can use this command in a macro since support for its arguments has recently been added:
{
"command": "editor.actions.findWithArgs",
"args": {
// "findInSelection": false,
// "isCaseSensitive": true,
// "matchCaseOverride": 0, // appears to not be implemented
// "preserveCase": true,
// "preserveCaseOverride": 0, // appears to not be implemented
"isRegex": true
// "regexOverride": 1, // appears to not be implemented
// "replaceString": "asdasd",
// "searchString": "qweqwe",
// "matchWholeWord": true,
// "wholeWordOverride": 0 // appears to not be implemented
}
}
This will open the Find Widget with the regex option chosen. Of course, you can utilize the other args if you want - some have not been implemented and intellisense is poorly done on this command in the keybindings - I have indicated which args have not been implemented and/or the correct key names.
----- Previous answer --------------
In v1.46 is the ability to open a new search editor (not the search panel), with various arguments including whether the regex button should be on or off.
See
SearchEditor: Open new editor with args
. So this works:
{
"key": "ctrl+shift+g",
"command": "search.action.openNewEditor",
"args": {
"query": "\\w*",
"regexp": true,
"includes": "${fileDirname}", // restrict to current editor's directory
// "includes": "${file}", // restrict search to current file
"showIncludesExcludes": true,
"contextLines": 3,
},
"when": "editorTextFocus"
},
whether the regex option was previously selected or not. Other arguments available:
{
query: string,
includes: string,
excludes: string,
contextLines: number,
wholeWord: boolean,
caseSensitive: boolean,
regexp: boolean,
useIgnores: boolean,
showIncludesExcludes: boolean,
// triggerSearch: boolean, // to be in v.47
// focusResults: boolean // to be in v.47
}
Prior to triggerSearch and focusResults being added to the Stable version (presumably 1.47) here is a macro that immediately runs the search and focuses the first result:
"multiCommand.commands": [
{
"command": "multiCommand.runSearchEditorwithArguments",
"interval": 200, // needs a small delay so results are loaded before focusing them
"sequence": [
{
"command": "search.action.openNewEditor",
"args": {
"query": "(TODO|NOTE|BUG):",
"regexp": true,
"includes": "${fileDirname}",
"showIncludesExcludes": true,
"contextLines": 3,
}
},
"rerunSearchEditorSearch", // runs the search
"search.action.focusNextSearchResult" // focus first result
]
}
]

Related

How to define a VScode snippet which pastes some texts by running a code

In RStudio, there is a snippet as follows:
snippet ts
`r paste("#", date(), "------------------------------\n")`
It will pastes some texts by running date(),
for example,
# Sat Oct 15 11:04:22 2022 ------------------------------.
How to define this in VScode?
Here is a way to do this in any type of file. You will need this extension (that I wrote), Find and Transform. Make this keybinding (in your keybindings.json):
{
"key": "alt+d",
"command": "findInCurrentFile",
"args": {
"replace": [
"$${",
"const date = new Date();",
"const options = { weekday: 'short', month: 'short', year: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'};",
"let str = `${LINE_COMMENT} ` + new Intl.DateTimeFormat('en-US', options).format(date) + ' ';",
"return str.padEnd(70, '-');", // padEnd with ---, whatever final length you want
"}$$"
],
"restrictFind": "line",
"postCommands": "cancelSelection"
},
// "when": "editorLangId == r"
}
You can use any of the Intl.DateTimeFormat options.
Note the use of ${LINE_COMMENT} at the beginning of the string. That will resolve to the comment style of whichever language you are in at the time. The demo is in an r file.
With extension File Templates you can create a key binding that insert a template with date variables.
Create a date format you want and the template that uses that date format.

How can I mix and match VS Code themes

Is it possible to mix and match themes in VS Code?
I want to keep the background colours of the default "Dark+" theme, but at the same time I want to set the font colors to "One Dark Pro"'s font colors.
I have tried modifying the settings.json file with the following config:
"editor.tokenColorCustomizations": {
"strings": "#98C379",
"functions": "#5AA1DC",
"keywords": "#C477DB",
"numbers": "#D19A66",
"types": "#E5C07B",
"variables": "#E06C75",
"comments": "#7F848E"
}
But it doesn't catch all types.
Is there an easier way to do this? Something like:
editor.fonts: {
>use "dark+";
}
editor.background: {
>use "one-dark-pro";
}

vscode is not respecting editor.quickSuggestions setttings

In vscode, I have the following setttings:
"editor.quickSuggestions": {
"other": true,
"comments": true,
"strings": true
},
"[markdown]": {
"editor.quickSuggestions": {
"other": true,
"comments": true,
"strings": true
},
I am debugging this issue for plugin Markdown Notes.
I believe at some point the settings value for editor.quickSuggestions changed from a boolean to the new mapping. In any case, in a document I have the text:
#draft
#d
And this used to autocomplete the tag text immediately, respecting the quickSuggestions preference.
Now, I don't get an automatic autocomplete, BUT I DO get the correct autocomplete values when I triggerSuggest (⌃Space by default).
So vscode DOES know the correct completion values, but it just will not respect the quickSuggestions settting.
Is there some other new setting I need to toggle to get quickSuggestions working correctly?
Maybe you have
{
"editor.suggestOnTriggerCharacters": true
}
set to false?

Align inline comments to a certain column in VSCode

I'd like to organize the inline comments in VSCode so that they are all positioned in the same column.
From this:
int a = 0; //comment 1
int b = 0; //comment 2
int c = a*b; //comment 3
To this:
int a = 0; //comment 1
int b = 0; //comment 2
int c = a*b; //comment 3
Tried using Better Align Extension but that didn't really work, as it only formats correctly lines that have an equal sign, like something = something. Is there any other way to do this? Thanks in advance.
You can do it with a macro extension like multi-command. You do have to hard-code a rough guess as to how far to the right you want to align the comments. You can't simply measure the furthest and use that - you would need a more involved extension to do that. However, you will have multi-cursors at the end and it is easy to adjust all the comments at once if you don't like where they ended up as in the demo where backspacing and tabbing moves all the comments in alignment.
Demo:
Use some keybinding to trigger the macro:
{
"key": "alt+w", // whatever keybinding you choose
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.alignComments" },
"when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.js/"
},
I made that for .js files but you can modify that for other extensions, like
resourceExtname =~ /\\.(js$|php)/ for .js and .php files.
And in your settings.json the actual macro:
"multiCommand.commands": [
{
"command": "multiCommand.alignComments",
// "interval": 3000,
"sequence": [
"editor.action.insertCursorAtEndOfEachLineSelected",
"cursorHomeSelect",
{
"command": "editor.action.insertSnippet", // pad with lots of spaces's'
"args": {
// so capture group 1 is before the comment, add spaces after it
"snippet": "${TM_SELECTED_TEXT/^([^;]+;)(\\s*)(?=\\/\\/.*)/$1 /g}",
}
},
"cursorHomeSelect",
{
"command": "editor.action.insertSnippet",
"args": {
// keep first 25 characters or wherever you want to align
// and then add the comments
"snippet": "${TM_SELECTED_TEXT/(.{25})(\\s*)(.*)/$1$3/g}",
}
},
// "removeSecondaryCursors" // to exit multi-cursor mode
]
}
]
Just hit Escape to exit multi-cursor mode (or add that command to the end of the macro).
comment-aligner extension does this nicely
to setup a keyboard shortcut add the following to
Preferences: Open Keyboard Shortcuts (JSON)
{ "key": "ctrl+cmd+]",
"command": "extension.commentaligner" }

Plugins HighlightWords in Sublime Text 3 How to configure?

Hello I have downloaded the Plugins HighlightWords to use it with Sublime Text 3 that promises to highlight words using some of the colors. Download it from here:
https://github.com/seanliang/HighlightWords
Could someone help me to change the color of highlighted by default. What I have tried I have not been able to do. This is the file to modify:
{
// The colors to highlight texts are specified by a list of theme scope names,
// and HighlightWords uses this list in circular order.
"colors_by_scope":
[
//"keyword",
//"number",
"string",
"entity.name.class",
"variable.parameter",
"invalid.deprecated",
"invalid",
"support.function"
],
"whole_word": false,
"use_regex": false,
"ignore_case": false,
// Keywords to be always highlighted, clear the list to disable it.
// "keyword" are literally matched, and "color" refers to theme scope names.
// Note that json has some special characters like '\' should be escaped.
"permanent_highlight_keyword_color_mappings":
[
//{"keyword": "TODO", "color": "support.function"},
//{"keyword": "FIXIT", "color": "support.function"},
]
}
You can override default plugin settings in plugin user settings. Goto menu Preferences > PackageSettings > HighlightWords > Settings-User , then add the words and colors you want overriding permanent_highlight_keyword_color_mappings property. Example content:
{
"permanent_highlight_keyword_color_mappings":
[
{"keyword": "stackoverflow", "color": "variable.parameter"},
{"keyword": "sublime", "color": "string"},
{"keyword": "plugin", "color": "invalid.deprecated"},
]
}
Save the file and maybe you need to restart sublime. Result: