Custom code completion to Visual Studio Code? - vscode-extensions

I have a definition (below) file for a JavaScript library.
How can I hook it up to Visual Studio Code code completion?
It has the following format:
{
"!name": "SomeLibrary",
"someMethod" :
{
"!doc" : "Description of some method.",
"!type" : "fn(someParameter: someType) -> someReturnType"
},
"SomeClass" :
{
"!doc" : "Description of some class.",
"someOtherMethod" :
{
"!doc" : "Description of some other method.",
"!type" : "fn(someParameter: someType) -> someReturnType"
}
}
}
Bonus question: What is the name of this format at all?
UPDATE: I found out that I should create a Typescript definition file, but I really don't know how to convert it from this file I have. Is this a standard format at all?

What you want to create is called a snippet:
You can define your own snippets, either global snippets or snippets for a specific language. To open up a snippet file for editing, select User Snippets under File > Preferences (Code > Preferences on macOS) and select the language (by language identifier) for which the snippets should appear or create a new global snippet (New Global Snippets file...).
Since snippets themselves are defined as JSON, your example could get a bit messy, but basically it would look like this:
{
"You Interface Definition": {
"prefix": "idef",
"body": [
"{",
"\t\"!name\": \"<LIBRARY_NAME>\",",
"\t\"<METHOD_NAME>\" : ",
"\t\t{",
"\t\t\"!doc\" : \"<DESCRIPTION>\",",
"\t\t\"!type\" : \"fn(<PARAMETER_NAME>: <PARAMETER_TYPE>) -> <RETURN_TYPE>\"",
"\t\t},",
"\t\"<CLASS_NAME>\" : {",
"\t\t\"!doc\" : \"<DESCRIPTION>\",",
"\t\t\"<METHOD_NAME>\" : {",
"\t\t\t\"!doc\" : \"<DESCRIPTION>\",",
"\t\t\t\"!type\" : \"fn(<PARAMETER_NAME>: <PARAMETER_TYPE>) -> <RETURN_TYPE>\"",
"\t\t}",
"\t}",
"}",
]
},
}
Note that I'm using \t rather than spaces, since that will respect a user's indentation settings
Now, once you type the prefix idef and press Tab the snippet will expand. You can add tab-stops with placeholder text, in case you want to change <DESCRIPTION> or <PARAMETER_NAME>. Here's a simplified example:
\"fn(${1:<PARAMETER_NAME>}: ${2:<PARAMETER_TYPE>}) -> ${3:<RETURN_TYPE>}\""
Note those parts enclosed by curly braces. Once your snippet is expanded you can use Tab to jump between those tab-stops and modify the selected text. The same tab-stop can be repeated multiple times, should you have the need to insert the same text at multiple places.

Related

code style for velocity template files in IntelliJ

Problem
The automatic indents in .vm files don't behave as I want them to. Below I add the auto formatted file and also the formatting I want.
The following code snippet is auto formatted by IntelliJ:
#styleTitle('sample-title')
##styleDescription()
A short description of the component
#end
##styleComponent('/components/molecules/sampleComponent/sampleComponent', {
"headline": 'A headline title',
"alertText": "Alert text example",
"link" : {
"href": "www.stackoverflow.com",
"text": "Click here!"
}
})#end
What I want:
#styleTitle('sample-title')
##styleDescription()
A short description of the component
#end
##styleComponent('/components/molecules/sampleComponent/sampleComponent', {
"headline": 'A headline title',
"alertText": "Alert text example",
"link" : {
"href": "www.stackoverflow.com",
"text": "Click here!"
}
})#end
Question
I couldn't find any additional configuration under IntelliJ IDEA | Preferences | Editor | Code Style | Velocity to adjust indention for different code blocks.
How can I configure the code style manually for a specific file type in IntelliJ and how does such a configuration file look like?

vscode: how to make text after snippet *not* selected?

When a snippet (for whatever language) is triggered, and the cursor is moved to a tab-stop, the area is "selected" (that is, you are still in "snippet mode" where you can go to another tab-stop). But I would like to get out of this "snippet mode" (e.g not having the area selected after tab-stop), because it suppresses intellisense (the selected area after snippet was triggered accepts anything, so it does no longer suggest intellisense function, variables, etc. Is there a settings in vscode to disable this "selection" after snippet is triggered?
If you have only one tabstop you can use $0 to avoid the "selecttion".
But if you have more than one i don't think it's possible.
I don't believe that's possible.
Snippets often have placeholders such as ${1:name} to indicate what's expected in that tab stop.
Take this one for example:
"JS arrow function": {
"prefix": "af",
"body": [
"const ${1:name} = (${2:props}) => {",
"\t$3",
"}"
],
"description": "Create arrow function"
}
Using tab will cycle over $1, $2 and $3, and for $1 and $2 there is a placeholder.
You can omit the placeholders if you want:
"JS arrow function2": {
"prefix": "af2",
"body": [
"const $1 = ($2) => {",
"\t$3",
"}"
],
"description": "Create arrow function"
}
But instellisense won't work until you press escape.
You can add your own snippets globally or per language if you prefer to customise them and avoid placeholders.
See this link for more information.

Supply Test Data into Nightwatch

I tried to supply test data to nightwatch but i don't know how. How to supply any dynamic test data to Nightwatch testing?
I don't want to hardcoded the value into the code. I want to supply it from file.
EDIT:
.setValue('selector', 'DEBBIE A/P EKU')
Since you mentioned it in one of your comments you want to read the values from a file, I recommend you doing it via pseudo-JSON (actually .js). Also a solution I applied in my company.
I have multiple json files which contain certain test data that I didn't want to have in the code. The basic structure of those looks like this:
module.exports = {
WHATEVER_IDENTIFIER_I_WANT: 'Some shiny value'
}
My Page Object contains a line like this:
const STATIC = require('path/to/static/file')
…
.setValue('selector', STATIC.WHATEVER_IDENTIFIER_I_WANT)
And yea, it is not highly sophisticated but it fulfils the purpose.
If you don't want to use module.exports and .js you can still use some node methods to load and parse a JSON. E.g.
fs.readFileSync / fs.readFile (to load the JSON file)
const file = fs.readFileSync('path/to/file')
JSON.parse() (to retrieve a JavaScript Object)
const STATIC = JSON.parse(file)
Hope this is useful for you :)
I've been through the same issue. At the moment my set up is like this:
Raw data are in the excel sheet. I use node.js to convert excel sheet into json file. Then use json data in nightwatch.
Here is the code to read the json file in nightwatch:
module.exports = {
tags: ['loginpage'],
// if not regular size logout button is not visible
'Login' : function (client) {
var credentials;
try{
credentials = require('./path/to/inputJsonData.json');
} catch(err) {
console.log(err);
console.log ('Couldn\'t load the inputJsonData file. Please ensure that ' +
'you have the inputJsonData.json in subfolder ./path/to ' +
'in the same folder as the tests');
process.exit();
}
Here is the code that use data from it:
client
.url(credentials.url)
.waitForElementVisible('body', 1000)
.assert.title('Sign In Home Page')
.login(credentials.username,credentials.password)
// some more steps here
.logout()
.end();
}
};
inputJsonData.json data
{
"url": "http://path/to/my/input/credentials/file",
"username": "yourUserName",
"password": "yourPassword"
}
My problem/question:
How to find the count of elements read into the json object from a file when the file has following format?:
[
{
....
},
{
....
},
.....
{
....
}
]
My failed attempt to get the number of elements: JSON.parse(company).count where company is another json read file like credentials in above code.
Answer: use standard javascript array property length company.length
TheBayOr answered the question concisely regarding the use of files. Just to add that if you don't literally mean a non 'code' file but simply using a different location to store the values then the most common approach is using globals.
You can place an array of values in either your nightwatch.json...
"test_settings" : {
"default" : {
"selenium_port" : 4444,
"selenium_host" : "localhost",
"silent": true,
"globals" : {
"VARIABLE_1" : "i'm a variable",
"VARIABLE_2" : "i'm a variable too"
},
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true,
"acceptSslCerts": true
}
},
"other_environment" : {
"globals" : {
"VARIABLE_1" : "i'm a different variable",
"VARIABLE_2" : "i'm a different variable too"
You can use them in tests with something like....
.url(browser.globals.VARIABLE_1)
Notice in the above you can have sets of globals under different environments. This has the advantage of meaning you can have multiple sets and use the one you want by running nightwatch -e 'my desired environment'.
Similarly this can be achieved by putting your array of data in a globals file e.g. globals.js and referencing it in your 'globals.path'.
If you want to get really into it you can even store your variables in global.js then use the 'fs' library to write the values to a file, then have your tests read from there. I'd recommend a new question if thats what you intend.
Hopefully that adds something :)
In my case I just created a function which read variables , data ,etc
more details here: https://stackoverflow.com/a/64616920/3957754

Sublime Text 3 Key Binding - Using variables

I'm trying to make a key binding to open up my favorite git application with current Sublime Text 3 $project_path folder, but somehow Sublime Text 3 doesn't convert the variables into the actual path.
Below you can find my current keyboard bindings file.
[
{
"keys": ["super+ctrl+alt+g"],
"command": "exec",
"args":
{
"shell_cmd": "open -a Gitbox $project_path"
}
}
]
$project_path doesn't convert into the actual project path... What am I doing wrong? Should I use a "Build System" instead? I looked into build systems but the problem there is that you would have to select a scope of files (for example *.rb) and I want this keyboard shortcut to be valid for all my projects/files.
In textmate2 the same shortcut was easily achieved by creating a new "Command" in the Bundle Editor and assigning a shortcut to it. The command then would be:
#!/usr/bin/ruby
exec "open -a Gitbox '#{ENV['TM_PROJECT_DIRECTORY']}'"
So I'm trying to achieve this same thing in Sublime Text 3 but something is going wrong.
Thanks!
Edit:
In the meantime I've built a generic plugin which gives you the ability to open any external application with an key stroke or via the command palette.
The plugin can be found here: ExternalTools
You can easily install it via the command palette cmd+shift+p
In your case you can go to Preferences / Key Bindings and add the following:
{
"keys": ["super+ctrl+alt+g"],
"command": "external_tools_run",
"args": { "cmd": ["open", "-a", "Gitbox", "$project_path"] }
}
I still down't own a mac so there is a chance that it is not working properly. In this case I would be pleased if you can give me a feedback (see Issues).
Original Answer:
I have spend a few hours searching on the same problem. After all I decided to create a small plugin with my own place holders.
import sublime, sublime_plugin
class RunAppCommand(sublime_plugin.WindowCommand):
def run(self, app_args):
app_args = self.fill_placeholder(app_args)
self.window.run_command("exec", {"cmd": app_args } )
def fill_placeholder(self, args):
res = []
proj_folder = self.get_project_folder()
for arg in args:
arg = arg.replace("$PROJECT_FOLDER", proj_folder)
res.append(arg)
return res
def get_project_folder(self,default=None):
proj_folder = ""
if self.window.project_file_name():
proj = self.window.project_data()
proj_folder_obj = self.get_first(proj["folders"])
if proj_folder_obj:
proj_folder = proj_folder_obj["path"]
elif self.window.folders():
proj_folder = self.get_first(self.window.folders())
if not proj_folder:
sublime.status_message("No project folder located")
return default
return proj_folder
def get_first(self, iterable, default=None):
if iterable:
for item in iterable:
return item
return default
After you have saved the code above to Packages/User/RunApp.py you can make your command work just by adding the following to your Default.sublime-keymap:
{ "keys": ["super+ctrl+alt+g"], "command": "run_app", "args": { "app_args": ["open", "-a", "Gitbox", "$PROJECT_FOLDER"]}}
This may be not the best solution but it works for me.
Also spent some hours searching here - thanks to fboers example i could finally
create a plugin myself.
So here's my solution: exec2 - expands all the sublime-variables as it should be and then forwards it to exec.
Save this as Packages/Exec2/Exec2.py.
import sublime
import sublime_plugin
class Exec2Command(sublime_plugin.WindowCommand):
def run(self, cmd):
new_cmd = [sublime.expand_variables (value, self.window.extract_variables()) for value in cmd]
self.window.run_command("exec", {"cmd": new_cmd } )
Example for the keybinding:
{ "keys": ["ctrl+F7"], "command": "exec2", "args" : { "cmd": ["V:/v4_tools/v4Doccer.exe", "--mdi", "${file}"]} },

To apply semantic principles using Font-awesome and LESS?

I'm trying to use Font-awesome in the same way I do with Bootstrap, in accordance with the semantic principles of web design (not putting billions of non-semantic classes in my HTML tags), using LESS.
It seems that it is impossible : the icon definitions are like that :
.#{fa-css-prefix}-home:before { content: #fa-var-home; }
This isn't a mixin definition but a classical CSS rule build with LESS variables.
So, i'm unable to do this kind of declaration :
.meaning-class-name {
.fa-home;
}
Lessc complain that .fa-home is undefined.
Is it a way to avoid to rot my HTML code ? Is there a way to attribute a class to an other class with less ?
Thanks !
I found that the better solution were to modify font-awesome/less/icons.less and rewrite the declarations according this pattern :
.#{fa-css-prefix}-home { &:before { content: #fa-var-home; } }
It is similar to the glyphicons.less used by Bootstrap.
PS : In Eclipse, this can be done quickly with the find/replace tool :
Find :
\.#\{fa-css-prefix\}-([-0-9a-zA-Z]+):before \{ content: #([-0-9a-zA-Z]+); \}
Replace :
.#{fa-css-prefix}-$1 { &:before { content: #$2; } }
and
Find :
\.#\{fa-css-prefix\}-([-0-9a-zA-Z]+):before,
Replace :
.#{fa-css-prefix}-$1,