vscode Nest snippet choices and add tab stops to choices - visual-studio-code

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:

Related

VS Code Snippet - Change position of linked tabstops

I am currently switching from IntelliJ to VS Code for a project and want to take some of my custom live templates with me.
VS Code supports "User Snippets", but I can't get them to work like they do in IntelliJ.
I want to achieve the following output:
console.log('variableName', variableName);
Now the thing is, I want my cursor to start right after the , so I get IntelliSense for auto completion of a defined variable. Then that variable name should be placed in the string.
I am right at the start and know that tabstops with the same ID get the same value:
"console.log variable": {
"scope": "javascript,typescript",
"prefix": "cl",
"body": [
"console.log('${1}', ${1});",
"$0"
],
"description": "console.log variable with name"
}
The problem with this is though, that the first tabstop is the start of the snippet and since I am inside a string I don't get IntelliSense for the variable name.
Is there a way to reverse the tabstop order of linked tabstops or anything similar that helps with the problem at hand?
"Print to console": {
"prefix": "clog",
"body": [
"console.log('${1:variable}', ${1:variable});$0"
],
"description": "Log output to console"
}
Works but you have to press Ctrl+Space to get completion items.

VSCode Intellisense: can we add keywords to an "exclude" list that won't be auto-completed?

I'm writing C code in VSCode with the amazing Tab Out extension that let you tab out of brackets, quotes etc. Together with the automatically added end brackets that VSCode has,I feel very comfortable writing C code when I can just do tab, tab, semi-conlon to end a line. However, every time I try to write self at the end near the ), I can't tab out without it being changed to STDERR_FILENO due to autocompletion.
How can I add a word, such as self, so that Intellisense will not autocomplete it? Is there a list of "excluded" words that I can tell Intellisense to not mess with?
I don't want to turn off any of the autocomplete stuff, I just want some very specific keywords to not be replaced when I tab out of stuff. I also don't want to stop using tab to autocomplete. these features are all very handy.
My current work-around is defining a new code snippet in the C snippet file:
"self": {
"body": "self",
"prefix": "self",
"description": "this is to prevent stupid suggestions for the keyword self"
}
but I consider this an ugly fix so let me know if you can help!

Is there a way to add a blank option with VS Code snippets placeholder choices?

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

Wrap a code block in HTML tags or other arbitrary code

I am not sure what the best way to word this question is. It is possibly why I am on StackOverflow because I cannot find a result on Google. Let me give it a try.
Assume I have the following HTML in my editor:
<li>One</li>
<li>Two</li>
<li>Three</li>
Is there a way to highlight all three of those lines, perhaps (on MacOS) using cmd+L and wrap them conveniently in <ul></ul> tags? Right now my process for doing this includes:
writing out <ul></ul> above the HTML I want to wrap. Hit return for a line break between the two tags I want to embed content between.
select the code block I want to embed between those tags using cmd+L
on MacOS, hit option+Up Arrow Key to move it in between the tags.
This is kind of awkward. Is there a simpler keyboard shortcut to do this, not just for HTML but for any code? It would be great to be able to take code like this:
car.turnLeft()
and simply wrap it in a condition very quickly without following the 3 non-optimal steps above:
if (car.isHeadedWrongDirection()) {
car.turnLeft()
}
The example above is forcefully contrived, but I think it makes the point for what I would like to accomplish in the editor.
The general form for wrapping is to use $TM_SELECTED_TEXT within a snippet. Like
"if wrap": {
"prefix": "*s",
"body": [
"if car.$1()) {",
"\t${TM_SELECTED_TEXT}",
"}"
],
"description": "Wrap selection in if statement"
},
That snippet goes into one of your snippet files, see create a snippet.
Because the snippet trigger, here *s will negate your selection, you will need to trigger the snippet with a keybinding, in keybindings.json:
{
"key": "alt+i", // whatever keybinding you want
"command": "editor.action.insertSnippet",
"args": {
"name": "if wrap" // the name you gave your snippet
},
"when": "editorTextFocus"
},
Now select the text you want to wrap and trigger the keybinding alt+i.
There are other ways to avoid having to select the text first that you want to wrap or to not actually consume the text - if you wanted to add the if wrap below the text for example.

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/