Is there a way to add a blank option with VS Code snippets placeholder choices? - visual-studio-code

I am trying to create a snippet that gives me choices for optional attributes. I have used this approach in the past where I just put a blank space as a choice in the placeholder. That works when there is only one option between other parts of the snippet but like in the following example if I wanted to skip both placeholders (optional attributes on the adorn) there would be multiple spaces in the generated code which I would have to delete manually.
"Adorn":
"prefix": ["adorn"],
"body": [
"<%= adorn${1| , color: :blue, color: :white|}${2| , inline: true|} do |a| %>",
"\t$0",
"\t<%= a.adornment %>",
"\t\t",
"\t<% end %>",
"<% end %>"
],
"description": "An adorn"
},
From what I can see in the documentation it doesn't seem possible to do what I want using placeholders and choices. I thought I could use a variable and just have it resolve to empty string but the grammar doesn't seem to allow for that.
Is there any other way to accomplish what I am trying to do?

You can use some unicode characters in snippets, so I tried backspace (did not work) but \u200B which is a "zero-width space" does. So you can do this in your choices:
{1|\u200B, color: :blue, color: :white|}${2|\u200B, inline: true|}
and if you choose the blanks (i.e., the \u200B's) a zero-width space will be inserted. And you get what you want - no spaces to be deleted.
But I leave it to you to see if there are any parsing or other problems with having that character in your code. Maybe it is or isn't a problem in your language. See the open issue (which I found after posting this answer initially) https://github.com/microsoft/vscode/issues/34368 ("Allow "empty" as a choice in snippets
") where the zero-width space option is warned against and may cause problems - so test it. It doesn't look like there is any other option but a regular space which you have tried.
I tried "null" \u0000 and it wasn't recognized by vscode.

if a blank space is all you need, then all is needed is an '$1' that the placeholder.
but first let's see if you have errthing
First
at the root of yow project you need a new dir call .vscode
in side yow dir add a new file NOTE name is very important yow new file's must have this pattern any.code-snippets
in side yow new file add this
{
// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
"Print to console": {
"scope": "javascript,typescript",
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}
}
To finish I recommend you to remove the scope attribute. and do not use the file for more than one language, bcuz if you do so it may not work at all.

The best way to get an empty value for a placeholder with choices is to add a choice of 1 character and remove this with Delete or Backspace (depending where the cursor is, it differs for the 2 placeholders) and then TAB to the next placeholder.
To get the choice list for placeholder 2 press TAB when you are at placeholder 2.
Watch the location of the separating spaces, they are at the end of the choice.
"Adorn": {
"prefix": ["adorn"],
"body": [
"<%= adorn ${1|e,color: :blue ,color: :white |}${2|e,inline: true |}do |a| %>",
"\t$0",
"\t<%= a.adornment %>",
"\t\t",
"\t<% end %>",
"<% end %>"
],
"description": "An adorn"
}

Related

How can I more easily replace a selection of text with an equal number of space characters?

I'm doing a lot of text editing right now that involves replacing spans of text with spaces (same number of spaces as number of replaced characters). It would be easier and more efficient if I could somehow highlight/select the text to replace, and then replace it all with blank spaces instead of first deleting the text and then manually refilling the spaces, tabs or newlines, especially during moments where I want to be precise.
For example:
This is my example sentence.
I decide I want to select 'my example' and delete it, like this:
This is sentence.
Instead of having it go like this:
This is sentence.
Is there an easier way to do this?
This is also easy with this extension, Find and Transform (disclaimer: I wrote it). Here is a keybinding that would work (in your keybindings.json):
{
"key": "alt+q", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
"replace": [ "$${ return `$1`.replace(/./g, ' '); }$$" ],
"isRegex": true,
"restrictFind": "selections",
"postCommands": "cancelSelection" // if you had multiple selections and wanted to clear them
}
}
"restrictFind": "selections" will only work within selections, as many as you want. If you had repetitive text in the document, you could omit this argument and it will find the selected text wherever it occurs in the document and replace it.
The $1 referred to is the selected text.
What you can do is switch your editor find mode to regex, and put "[^\s]" in the find input, and then " " (space) in the replace input. Then select the text you want to replace with spaces and either click the "Find in Selection" button or use the keyboard shortcut (Ex. alt+l). Then click "Replace All" or use the keyboard shortcut (Ex. ctrl+alt+enter).
This will replace each instance of any non-whitespace character in the selection with a space character.
If you don't want to preserve the types of whitespace characters (Ex. keeping tab characters as tab characters), just put "." in the find input field instead of "[^\s]".
You can use the extension Regex Text Generator
Add this to your settings.json
"regexTextGen.predefined": {
"Replace with spaces": {
"originalTextRegex": "(?g)(.)",
"generatorRegex": " {S}"
}
}
Select the text you want to replace, multi cursor is supported.
Execute command: Generate text based on Regular Expression (regex)
Select the predefined: Replace with spaces
Press Enter 2 times.
You are able to preview the replacement and Escape if needed when you are allowed to edit the generator expression.
You can create a key binding for this if you need to do it a lot. See the extension page for an example.

use dollar sign in a vscode snippet regex

I am trying to make a vs code php snippet which generate this line from the $code placeholder input:
Utils::getLogger.debug("code", ["code" => $code])
The regex I use for this is /(\$?)(.*)/ (I am interested in the second capture group to get the variable name).
This is my snippet code :
"log debug": {
"prefix": ["log debug", "debug"],
"body": ["Utils::getLogger.debug(\"${1/(^\\$?)(.*)/$2/}\", [\"${1/(^\\$?)(.*)/$2/}\" => ${1:variable}])"],
"description": "Quick variable debug."
},
The problem is that it doesn't replace the dollar sign from my input. If I give $variable as placeholder, it generates Utils::getLogger.debug("$variable", ["$variable" => $variable]).
I got it working for a charater different than the dollar sign, for example a comma or another letter and also I got it working using TM_SELECTED_TEXT variable and selecting my variable before.
I suspect that it is a conflict with vs code php variable name autocompletion in vscode as if I copy my variable then call the snippet and paste the variable inside the placeholder (instead of typing it), it also works.
I was tempted to post this as an issue on vscode github but maybe am doing something wrong here.
ps: I know that is can also type in the variable name without the $ and add it in the replacement regex, but you know how developpers can be...
This works:
"body": ["Utils::getLogger.debug(\"${2:${1/\\$?(.*)/$1/}}\", [\"$2\" => ${1:variable}])"],
Note that since you are reusing the first transform, I set it to a placeholder ${2} by wrapping it like so:
${2:${1/\\$?(.*)/$1/}}
Now you can reuse that $2 placeholder wherever you want the result of the same transform - as in \"$2\" =>.
Thanks to https://stackoverflow.com/a/66449064/836330 for that usage.
After discussions and further testing, I think there is nothing wrong with the snippet code and it is a "conflict" with php variable autocompletion.
There are some optimisations in the answers that are interesting tho.
For information, I finally took the solution to enter the variable name without the $ and add it in the transform.
"log debug quick": {
"prefix": ["log debug quick", "debug quick"],
"body": ["Utils::getLogger.debug(\"${1:variable}\", [\"${1}\" => \\$${1}]);"],
"description": "Quick variable debug."
},
Note that the original method works with the TM_SELECTED_TEXT variable (as the autocompletion does not happen), so the folowing is working :
"log debug selection": {
"prefix": ["log debug selection", "debug selection"],
"body": ["Utils::getLogger.debug(\"${1:${TM_SELECTED_TEXT/^\\$?(.*)/$1/}}\", [\"${1}\" => $TM_SELECTED_TEXT]);"],
"description": "Quick variable debug."
},
Note that I optimized the snippet with both #Mark and #rioV8 suggestions

VSC - is it possible to read snippets from multiple files?

if there is a file called javascript.json --> then every .js file reads its content when u using VSC.
I would like to not only read snippets from javascript.json but from javascript2.json as well when editing a js file in vsc. (or any other random name, the main thing is to read snippets for javascript from multiple json files)
Is there a way to do this?
You can have additional snippet files in your workspace .vscode directory.
The file has the extension: .code-snippets
You can limit the language for a snippet by using the scope attribute.
{
// Place your test workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
"Print to console": {
"scope": "javascript,typescript",
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}
}

vscode Nest snippet choices and add tab stops to choices

I want to do something like that in my snippets for visual studio code:
"V.G.${1|BLOCK_NR,MASS_MM,MASS_360,I,J,K,R,FEEDRATE,FEEDRATE_SCALE,MERR[${2}]|}"
So after choose the option MERR[] I will see the cursor inside the brackets.
and how i have to manage sub choices like:
"V.G.${1|choice${2|subchoiceA,subchoiceB|},choice, choice......}"
If I choose MERR[] Option I will jump into [Cursor should be here]. How can i handle this?
Here is a workaround to your subchoiceA/B question because you cannot have anything except plain text as choices - no tabstops or subchoices, etc. Your example:
V.G.${1|choice${2|subchoiceA,subchoiceB|},choice, choice......}"
This can be achieved however with 2 snippets:
"choices with subchoices": {
"prefix": "_choices", // whatever prefix you want
"body": [
"V.G.${1|choice1, _subchoices,choice2,choice3|}"
],
"description": "variables in a choice element"
},
"my subchoice list": {
"prefix": "_subchoices", // this prefix must be what you used in the main snippet
// as your subchoice option
"body": [ "${1|subchoiceA,subchoiceB|}" ],
"description": "subChoices"
},
What happens is that when you choose the subchoices option in the main snippet it will see it as the prefix for the second snippet - that is pretty neat. But it will not do so until you trigger that recognition with Ctrl+Space the usual intellisense trigger and then tab to select the second snippet.
It is only one or two extra keystrokes to get subchoices working inside of a parent choice element when otherwise it can't be done at all.
The only issue is that your second prefix - here subchoices cannot be a continuation of another string with no spaces otherwise it won't be recognized as a standalone snippet prefix by vscode. That is why I added the space before subchoices in the main snippet since your example has "V.G.${1....} with no space before the option would be inserted.
Here is a demo:

How to prevent "."(dot) from cancelling autocomplete in Sublime Text 2?

I have defined some keywords for a proprietary language I use at work:
{ "match": "\\b(util.tickettimelimit|util.user_ip|util.server_name|util.today)\\b",
"name": "keyword.source.GTX2",
"comment": "Tags"
}
I also have a completion file:
{
"scope": "source.GTX2",
"completions":
[
"util.server_name",
"util.tickettimelimit",
"util.today",
"util.user_ip"
]
}
When I start typing "util" I see the correct autocomplete options:
But as soon as I enter the "."(dot) autocomplete options go away:
Is there a way to change this behavior? I just want the keywords to be trated as a whole thing and ignore the dots.
Thanks!
I've looked everywhere I can, and it seems the auto-complete code is embedded within the executable itself (at least on Windows, I haven't checked my Mac yet), and not in one of the numerous external .py files scattered around, so I can't even see the parameters for how auto-completion is performed. I looked through the default Packages/Default/Preferences.sublime-settings file and while there are several options relating to auto-complete, there are none relating to what we're looking for. While looking through the Default (Windows).sublime-keymap file in the same directory, I tried adding the following:
{ "keys": ["."], "command": "hide_auto_complete", "context":
[
{ "key": "auto_complete_visible", "operator": "equal", "operand": false }
]
},
but alas it didn't work. There are a number of auto_complete commands there, and while this looked the most promising I haven't tried the rest.
I haven't exhaustively looked through the source and config files for the nifty SublimeCodeIntel plugin (also available through Package Control), so it's possible you might be able to find an option there. You'd probably have to completely disable the built-in auto-complete functionality first, so it doesn't override SCI.
So, I guess for now there's not much you can do. You can always leave a feature request and see if it makes it into Sublime Text 3, or search/open a thread on the Sublime Text Forum and see if anyone else has any suggestions. Good luck!
What I think #Ashish is alluding to is the word_separators setting. You will want to create a syntax specific preference (Preferences -> Settings - More -> Syntax Specific - User). Create a word_separators entry with the dot removed (Copy from the default preferences as the base). This will give you the behavior you want but there are some things to note. The dot, obviously, will not be treated as a word separator, which will change some behavior.
I'll use java as an example. If I had a variable foo, with some method bar, I could enter foo.b and bar would be shown as a completion. Without the dot as a separator, you will not see this.
Another example, perhaps easier to understand is when selecting words. If you use ctrl/cmd + d to select the word, it selects words, bound by word separators. So if I had foo.ba|r, where the | represents the cursor position and used ctrl/cmd+d it would select bar. With the dot removed as a word separator, foo.bar would be selected.
Let me know if I can clarify anything.
It's a little late but I hope this can help, create a new plugin and add this code:
import re
myObjects = {"util": ["server", "tickettimelimit", "today", "user_ip"]}
class CustomAutocomplete(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
if not view.match_selector(0, "source.GTX2"):
return
if prefix == "":
# get the last word in the current line
currentposition = view.sel()[0].begin()
currentline = view.full_line(currentposition)
text = view.substr(currentline)
words = re.findall("\w+", text)
lastword = words[-1]
if lastword in myObjects.keys():
# return a list of tuples, it represents snippets
# the first element is the trigger and the second one
# is the content
return [(x, x) for x in myObjects[lastword]]
return []
And add the next key in the user settings:
"auto_complete_triggers":
[
{
"characters": ".",
"selector": "source.GTX2"
}
]
Don't press . (dot) else you will need to type at least one character after dot so list can appear again. Using Brackets or Dot tells Sublime Text 2 that user has completed typing.
example: if I type for then sublime will show dropdown list but if I type for( list will disappear.
Click on Preferences > Settings - User, then copy and paste the following
// Characters that are considered to separate words – does not include periods.
// Place comma at the end of the line if there are multiple keybindings.
"word_separators": "/\\()\"‘-:,;~!##$%^&*|+=[]{}`~?"
From this webpage:
http://tomschenkjr.net/using-sublime-text-2-for-r/