Align inline comments to a certain column in VSCode - visual-studio-code

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" }

Related

VSCode settings : colorize custom tags that start with the "x-" prefix

I want to write a vscode setting in which tags ( inside .vue file ) that start with the prefix x- will be colored green.
tags like <x-component></x-component> and <x-lorem></x-lorem>
is it possible? and how
i tried this
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": "entity.name.tag.x-*",
"settings": {
"foreground": "#00ff00"
}
}
]
},
and it not works
Unfortunately, it seems that this is not possible without installing the plugin
I used the Highlight plugin mentioned by #rioV8
it works
this is my config :
"highlight.regexes": {
"(<[^>]*x-[^>]*>)": { // A regex will be created from this string, don't forget to double escape it
"decorations": [ // Decoration options to apply to the capturing groups
{ "color": "#7ac379" }, // Decoration options to apply to the first capturing group, in this case "//<-x:"
]
}
}

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

how to make a custom comment style in vscode

I got a source code commented like below.
// //------------------------------------------------------------------------------
// //======================= Variable Declaration =================================
Is there any way to make a comment like the above in vs code.
I only got single and multiline comments.
But I want the above custom style.
You can make a snippet to do that. In one of your snippets files:
"Variable Declaration Comment": {
"prefix": "_gc", // whatever trigger you want
"body": [
"$LINE_COMMENT $LINE_COMMENT------------------------------------------------------------------------------",
"$LINE_COMMENT $LINE_COMMENT======================= ${TM_SELECTED_TEXT} =================================$0",
],
"description": "Insert a Variable Declaration comment header"
}
That will use whatever the line comment style is for the type of file you are in: $LINE_COMMENT.
You could set that to a keybinding like this (in your keybindings.json file):
{
"key": "alt+q", // whatever keybinding you want
"command": "editor.action.insertSnippet",
"args": {
"name": "Variable Declaration Comment"
},
"when": "editorTextFocus"
}
If you want to get fancy and see how to build other custom comment blocks, you can do this with an extension I wrote, Find and Transform. Use this keybinding in your keybindings.json:
{
"key": "alt+f", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
"replace": [
"$${",
"const lineLength = 80;", // how long you want the block
// what is the length of the comment characters in this language
"const commentCharsLength = 2 * (`${LINE_COMMENT}`.length) + 1;", // + 1 for the space between comment markers
// select the text you want to wrap first
"const selectionLength = `${selectedText}`.length;",
"const gapLength = 1;", // the spaces around the text
"let str = `${LINE_COMMENT} ${LINE_COMMENT}` + '-'.padEnd(lineLength - commentCharsLength, '-') + `\n`;",
"const totalSpacers = lineLength - commentCharsLength - selectionLength - (2 * gapLength);",
"const beforeSelectionLength = totalSpacers/2 - commentCharsLength/2;",
"const afterSelectionLength = totalSpacers/2 + commentCharsLength/2;",
// ${LINE_COMMENT} in backticks to treat as a string
"str += `${LINE_COMMENT} ${LINE_COMMENT}` + '='.padEnd(beforeSelectionLength, '=') + ` `;",
"if (selectionLength %2 === 0) str += `${selectedText} ` + '='.padEnd(afterSelectionLength, '=');",
"if (selectionLength %2 === 1) str += `${selectedText} ` + '='.padEnd(afterSelectionLength+1, '=');",
"return str;",
"}$$"
],
"restrictFind": "line",
// "postCommands": "cancelSelection"
},
// "when": "editorLangId == javascript"
}
As you can see, you can write javascript in a keybinding (or setting).
You can use the extension HyperSnips
Define the following snippet in the all.hsnips file
snippet comment "Comment Section"
// //------------------------------------------------------------------------------
// //``s = '='.repeat((78-(t[0].length + 2))/2); rv = s;`` $1 ``rv = '='.repeat(78-(t[0].length + 2 + s.length));``
endsnippet
If you type comment and select the snippet with Tab you can type the text and the === strings adjust to keep the text centered.
You can also cut some text - start the snippet - and paste the text.

VSCode How to _enable_ Regex Find by command, rather than "toggle"

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
]
}
]