Is it possible to have a snippet that considers the length of my input? - visual-studio-code

I would like to define a snippet for comments like
//************
//* foo A1 *
//************
where I enter foo A1 and it would create a line with (6+ len(${1}) asterisks etc. - is that doable and if so, how?

While I am a big proponent of HyperSnips (see
[VSCODE]: Is there a way to insert N times the same characters,
VS Code: how to make a python snippet that after string or expression hitting tab will transform it and
VSCode Advanced Custom Snippets for how to use it),
it is instructive to see how to do this with just the built-in snippet functionality in vscode. Here is a snippet that does what you want:
"Custom Comment": {
"prefix": ["cc2"], // whatever trigger you want, then tab, write your info and tab again
"body": [
"//***${1/./*/g}***",
"//* $1 *",
"//***${1/./*/g}***"
]
},
That just adds 3 asterisks to the beginning and 3 to the end of your added comment, each character of which is replaced by an asterisk as well.

You can use the extension HyperSnips
snippet comment "Comment" A
``rv = '//' + '*'.repeat(t[0].length + 6)``
//* $1 *
``rv = '//' + '*'.repeat(t[0].length + 6)``
endsnippet

Related

How do I get a snippet to insert a character only if the user typed something?

I have this snippet.
SELECT 'SELECT * FROM ' + OBJECT_SCHEMA_NAME(o.object_id, DB_ID(${20:})) + '.' + name,
*
FROM ${20/$/./}sys.all_objects o
WHERE name LIKE '%${10:hadr}%'
ORDER BY o.name;
And this is how it works:
When the user types something in the function DB_ID(), I hope the content the user typed appears before sys.all_objects AND append an additional .. It already works like this as it shown in the above gif. However, I also hope if the user types nothing in the function DB_ID(), don't add . before sys.all_objects. Is this possible?
No need to add the : in field 2:
DB_ID(${2})
Use field 2
${2/(.*)/$1${1:+.}/}
capture all the typed text: (.*)
replace it with all the typed text: $1
followed by a . if the typed text is not empty: ${1:+.}
You can use lookbehind to assert that there's something in that field: (?<=.)$. For a minimal example, let's say this is the original snippet:
foo($1); ${1/$/./}bar()
Change it to:
foo($1); ${1/(?<=.)$/./}bar()
If I type something, e.g. x, then press Tab, I get:
foo(x); x.bar()
If I don't type anything then press Tab, I get:
foo(); bar()

How to format selected code using vscode and Prettier?

I have add Prettier in my VScode but I want to format my code only when I highlight my code,
say
let a = [1, 2, 3, 4]; (line1)
let b = [ 1,2 ,3,4]; (line3)
how can I just format line 1 when I highlight line 1 only and the result should be
let a = [1, 2, 3, 4]; (line1)
let b = [ 1,2 ,3,4]; (line3)
thanks
UPDATE:
I know we can format the code in a code block. But what I want to do is
const test = (a, b, c) => { (line 1)
console.log("show a", a); (line 2)
console.log("show b", b); (line 3)
}
If I highlight b, c in line 1 and format it. It only formats the code in line 1 but not 2 and 3
futher update:
this is my vscode shortcut setting
when I highlight like this,
it becomes like that
I dont know the solution yet, but there are some info that may help.
Basically, there are something wrong with the linter. ( https://github.com/prettier/prettier-vscode/issues/137 )
And your may fix it by checking out this https://prettier.io/docs/en/integrating-with-linters.html ,
I dont know how & didnt try. cuz:: [[
looks complicated (download many things) & mess up with the project structure
may not even work
some info I have no knowledge of / incompatible with my understanding
dont know what will happen to my linters
dont know what is the next step
[]
https://github.com/prettier/prettier-vscode/issues/134
[]
No, the issue is with prettier-eslint not supporting range formatting.
...
I would suggest switching to the recommended approach of integrating ESLint and Prettier
https://github.com/prettier/prettier-vscode/issues/137
[]
let Prettier do the formatting and configure the linter to not deal with formatting rules. You can find instructions on how to configure each linter on the Prettier docs site.
...
For details refer to the Prettier documentation.
https://github.com/prettier/prettier-vscode#linter-integration
[]
Linters usually contain not only code quality rules, but also stylistic rules. Most stylistic rules are unnecessary when using Prettier, but worse – they might conflict with Prettier! Use Prettier for code formatting concerns, and linters for code-quality concerns, as outlined in Prettier vs. Linters.
Luckily it’s easy to turn off rules that conflict or are unnecessary with Prettier, by using these pre-made configs:
eslint-config-prettier
stylelint-config-prettier
https://prettier.io/docs/en/integrating-with-linters.html
[]
I would like to format my code with prettier, then apply all eslint fixes. Previously, this could be achieved by setting prettier.eslintIntegration to true. Now, the extension say that this option is [DEPRECTAED] and prettier-eslint should be used instead. However, it's not clear how to use prettier-eslint in vscode.
https://github.com/prettier/prettier-vscode/issues/999
Actually, "format only selected code" is working on my end, I didnt do any fancy extra config.
What you need to pay attention to is the "syntax tree"
-- ie: dont blindly select across the scope (the bracket {}).
#eg::
given
function test() {
let a = [1, 2, 3, 4];
let b = [ 1,2 ,3,4]; // select only this line
return false
}
if you only select::
let b = [ 1,2 ,3,4];
then press ctrl+k, ctrl+f
everything is fine
if you select across the bracket (the } for function scope)::
let b = [ 1,2 ,3,4]; // select only this line
return false
}
then press ctrl+k, ctrl+f
the whole thing in the bracket (the } for function scope) gets formatted
the "syntax tree" in a class is a bit weird.
-- ie: if you select the WHOLE function AA & format it -- codes inside another function BB will also get formatted...
you may need to apply // prettier-ignore somewhere to prevent formatting
prettier-ignore
A JavaScript comment of // prettier-ignore will exclude the next node in the abstract syntax tree from formatting.
https://prettier.io/docs/en/ignore.html
(note, it seems there is no ending tag for // prettier-ignore for Javascript (at current stage of Prettier))
for the meaning of a "syntax tree", see ex below
if you place it above the code line
seems it applies to the item (the code) (-- which is a "syntax tree node") directly below ((empty lines not counted for)) the // prettier-ignore line
-- eg-below: console.log("show a", a);, and ends there.
if you place it behind the code line (inline)
seems it applies to the inline code only
#for_your_case-do_this:
const test = (a, b, c) => {
// prettier-ignore
console.log("show a", a);
// prettier-ignore
console.log("show b", b);
}
// or
const test = (a, b, c) => {
console.log("show a", a); // prettier-ignore
console.log("show b", b); // prettier-ignore
}
Select the code you want to format and press CTRL + SHIFT + P to open the command pallette. Then type in "format" and select format selected code. Or you can select your code and press right click which should bring up a context menu where you can select the option
Select the code or leave the cursor in the row you want to format and press Ctrl + K Ctrl + F.

Modify vscode snippet by regex: TitleCase and SNAKE_CASE

I have two questions for vscode snippets+regex;
I have a pathname like some-component and I need to generate an output like SomeComponent using vscode snippet.
I need to input sendData and return an string like const sendData = createMessage(SEND_DATA);
How can I do this using regex on vscode snippet?
"${TM_DIRECTORY/(.*)/${1:/pascalcase}/g}" you didn't really provide enough info on how you are getting your pathName, so this is just one possibility, perhaps RELATIVE_FILEPATH` works for you.
"$1 = createMessage(${1/(([^A-Z]+)(\\w*))/${2:/upcase}_${3:/upcase}/});"
split the input sendData into 2 capture groups $2 and $3. Upcase them both in the transform.
"sendData": {
"prefix": "cm",
"body": [
"${TM_DIRECTORY/(.*)/${1:/pascalcase}/}",
// simpler form if ONLY two "words" like "sendData"
"$1 = createMessage(${1/(([^A-Z]+)(\\w*))/${2:/upcase}_${3:/upcase}/});",
// for any number of words, like "sendDataTwoThreeFour" use this:
"$1 = createMessage(${1/([a-z]*)([A-Z][a-z]*)/${1:/upcase}${2:+_}${2:/upcase}/g});"
]
}
${1/([a-z]*)([A-Z][a-z]*)/${1:/upcase}${2:+_}${2:/upcase}/g} get the first word "send" into capture group 1 and the other words like "Data" or "Two", etc. into subsequent matches' capture group 2. [So the g flag at the end is very important.]
Upcase group1. Then if there is a group 2 ${2:+_} add _. Then upcase group2.
The only case this will not work on is send with nothing else. It still prints out the all the text just doesn't upcase send if it is by itself. There is probably a way to include that...
Edit: And here it is:
"$1 = createMessage(${1/([a-z]*)([A-Z][a-z]*)|([a-z]+)/${1:/upcase}${3:/upcase}${2:+_}${2:/upcase}/g});"
now a bare send will be put into group 3 and upcased. For the rest of the matches there will not be a group 3 so ${3:/upcase} returns nothing.

Snippet for title in restructured text in vs code

In restructured text, titles are written with equal number of nonalphanumeric 7-bit ASCII
character as the title text. The underline and overline if both used, should be equal and at least as long as title text. From the official docs:
Titles are underlined (or over-
and underlined) with a printing
nonalphanumeric 7-bit ASCII
character. Recommended choices
are "= - ` : ' " ~ ^ _ * + # < >".
The underline/overline must be at
least as long as the title text.
Example of a title
=========================================================
Main titles are written using equals signs over and under
=========================================================
I want to create a VS Code snippet for this. What I could do was only this,
"Title RST": {
"prefix": "title",
"body": [
"="
"$1"
"=\n"
"$0"
],
"description": "Title for restructured text"
}
Is there a way to know the length of the text that will be typed, and correspondingly insert same number of overline and underline =.
In yasnippet in emacs, they do it as:
${1:$(make-string (string-width yas-text) ?\=)}
${1:Title}
${1:$(make-string (string-width yas-text) ?\=)}
$0
Any help how to implement such snippet in VS code? I looked under snippets in restructured text extension for VS Code here but could not find that suits my needs.
"Title RST": {
"prefix": "title",
"body": [
"${1/./=/g}",
"$1",
"${1/./=/g}",
"$0"
],
"description": "Title for restructured text"
},
The transforms ${1/./=/g} just replace every character in your text $1 with a = in the line above and below your text.
You need commas at the end of your snippet entries and there is no need for the newline as another line in the snippet body is already a newline.
When you type your text hit Tab and the transform will be completed.
You asked if was possible to get the over/underlines to show as =s immediately upon typing your title text. But that isn't possible with vscode snippets, a transform is required and that won't happen until the Tab.
It can be done with HyperSnips version (a little more trouble to set up than plain vscode snippets, but not much):
snippet title "Title" A
``rv = '='.repeat(t[0].length)``
$1
``rv = '='.repeat(t[0].length)``
endsnippet

Creating macros in netbeans

I wish to create macro in Netbeans to put block comment over function. I have preference of code formatting over file save. So When I close file it saves code automatically and format it.
Issue is when I create function and comment it. It unformatted my whole block of code like this.
/**
*function abc(){
*var a, b = 50;
*}
*/
I wish to create comment like this. so it keep my coding properly formatted as well.
/*
|
| function abc(){
| var a, b = 50;
| }
|
*/
You can add your own macro by Following this instructions:
Edit->Start Macro Recording
Edit->Stop Macro Recirding
It Will pop-up one Box For Editor Macros->Add Your Choice of Macro Name
In code area add Your custom comment code in " your code "; Like,
Blockquote
"/*
|
| function abc(){
| var a, b = 50;
| }
|
*/"
Assign a Short Cut Key to your Custom Macro.
That's It
Though I couldn't find macro for the same. But I found alternative. Use Ctrl+Shift+R toggle, for multiple line action at same time & add pipeline sign. But it take extra effort for starting and ending comment.