How to insert current date time in vscode? - visual-studio-code

Does anyone know of a way that I can insert the current date & time in a visual studio code by snippets?
I have looked docs but did not get any information about it.
I want to create a snippets like this:
title: theFileTitle
date: 2016-08-05 09:44:16

As of Jan 2018 (release 1.20) you can use these new snippet environment variables.
Your example above would look like this:
"File Header": {
"prefix": "header",
"description": "Output a file header with the file name and date",
"body": [
"title: $TM_FILENAME",
"date: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
]
}
Type head, press ctrl+space and it should show snippet menu.

I have created an extension for you that allows to insert formatted date and/or time string - Insert Date String.
Installation
Open Command Palette by pressing F1, type ext install + press Enter and then look for Insert Date String extension.
Usage
To insert current date and/or time at the cursor position you can:
Press ⇧+⌘+I (OS X) or Ctrl+Shift+I (Windows and Linux), or open Command Palette by pressing F1 and type Insert DateTime then press Enter.
Configuration
By default you don't have to set anything. But if you want to change the datetime format, look for insertDateString.format option in user settings.
// Date format to be used.
"insertDateString.format": "YYYY-MM-DD hh:mm:ss",
You can specify any valid ISO 8601 format. There are some examples in readme.
Snippet
Unfortunately you can't use anything more than tab stops or variables in snippets so you'll have to enter the title and date/time manually.
You can define snippets for specific languages. To open a snippet file for editing, open User Snippets under File > Preferences (Code > Preferences on Mac OS X) and select the language for which the snippets should appear.
Following example is for Plain Text files.
After opening a snippet file for Plain Text, add following definition:
{
"File header": {
"prefix": "header",
"body": [
"title: ${title:Enter title}",
"date: ${date:Insert datetime string (⇧⌘I or Ctrl+Shift+I)}"
]
}
}
Now you can open a new plaintext file, enter header and press Tab. Enter your title and use Insert DateTime command to insert current date and/or time.
Idea for a more customizable solution
One could write an extension for inserting such headers. This way some sort of templates with several predefined variables (e.g. date, filename, configurable username/email, etc.) might be used.
Hope this helps!!

if you don't want create a snippet, there is a simple way, using keybindings.
open keybindings.json (Preferences: Open Keyboard Shortcuts (JSON)), and add fellow code to your keybindings.json
[
{
"key": "cmd+k t",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND"
}
}
]
that's all.
now you can use cmd+k t to insert current data time while typing.

You can just use the following variables in your snippets:
$CURRENT_YEAR
$CURRENT_YEAR_SHORT
$CURRENT_MONTH
$CURRENT_DATE
$CURRENT_HOUR
$CURRENT_MINUTE
$CURRENT_SECOND
Links to the official VSCode docs:
date and time in snippets
user defined snippets

The env variable TM_FILENAME will fill the title with the file name automatically.
For example:
"title: ${1:$TM_FILENAME_BASE}"

You could also use a tool outside of Code, like for example Texter.
I have configured it to replace [t with [%ds %t], which gives me [9/11/2017 16:30] while I type, regardless of application.

It might be a bit of an overkill but you can check Org Mode extension which has this functionality and more:

You can use this snippet for Vscode, I used to refer to this in my code files.
"file description": {
"prefix": "template",
"body": [
"\"\"\"",
"# _* coding: utf8 *_",
"",
"filename: $TM_FILENAME",
"",
"#author: sounishnath",
"createdAt: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
"\"\"\"",
"",
""
],
"description": "file description"
}

See https://stackoverflow.com/a/74082031/836330 for how to insert the Intl.DateTimeFormat timeStamp with options with a keybinding:
Or see Command Variable extension. It uses the Intl.DateTimeFormat format and can be used in a keybinding like so:
{
"key": "alt+d",
"when": "editorTextFocus",
"command": "extension.commandvariable.dateTimeInEditor",
"args": {
"locale": "en-US",
"options": {
"year": "numeric",
"month": "long",
"weekday": "long",
"day": "2-digit",
"hour12": false,
"hour": "2-digit",
"minute": "2-digit",
"second": "2-digit"
},
"template": "${month} ${day}, (${weekday}), ${year} - ${hour}:${minute}::${second}"
}
},
to produce
March 25, (Wednesday), 2020 - 21:16::49
and many other timestamp versions. See the possibilities at Intl.DateTimeFormat

Related

How do I add extra syntax highlighting to an existing language?

I want to add some extra language features, such as liquid language support inside JavaScript:
var firstName = "<% User.firstName %>";
var lastName = "<% User.firstName %>";
I browsed around a bit and I found this folder in the vscode repository: https://github.com/microsoft/vscode/tree/main/extensions/javascript
It's basically the JavaScript tmLanguage grammar rules, so I had this idea to create a new javascript file format (.pjs) and apply the same tmLanguage file as well as add these new rules:
"pk-liquid-expression": {
"begin": "<%",
"beginCaptures": {
"0": {
"name": "storage.type.primitive.java"
}
},
"end": "%>",
"endCaptures": {
"0": {
"name": "storage.type.primitive.java"
}
},
"name": "storage.type.primitive.java"
},
And this worked, however now my pjs files don't have any of the language features such as errors and warnings.
I think my solution is not very forward-thinking however, so is it possible to just edit the current JavaScript tmLanguage rules and add these new tokens?
Thank you.
One solution is to inject the "liquid language" into the Javascript language definition. Main steps for that is to define a grammar to inject and creating a selector which defines when to inject your grammar:
{
"contributes": {
"grammars": [
{
"path": "./syntaxes/injection.json",
"scopeName": "todo-comment.injection",
"injectTo": ["source.js"]
}
]
}
}
See also: How to properly inject grammar extension in vscode (so it works)?

VS Code Spell Checker

I enabled the VS Code extension, "Code Spell Checker," and it works great. However, I wanted to include words from my custom dictionary file so the words in it aren't flagged as incorrect. I tried the following in my settings.json:
"cSpell.customUserDictionaries": [
"name": "Custom",
"description": "These are words from my custom dictionary.",
"path": "C:\\Users\\Joe\\Documents\\Custom.txt",
"addWords": false
],
But the words in Custom.txt are still marked as incorrect.
How can I configure Code Spell Checker so that it's able to load all the words in Custom.txt and ignore them?
According to their package.json that configuration is expecting a typeof array of objects, so the following should work:
"cSpell.customUserDictionaries": [
{
"name": "Custom",
"description": "My desc",
"path": "C:\\Users\\Joe\\Documents\\Custom.txt",
"addWords": false
}
],
And per their description:
File Format: Each line in the file is considered a dictionary entry

VScode use built-in variables, like $TM_FILENAME_BASE and others, in snippet choices

I have a question about snippets and choices. I would like t0 use variables in choices. Is this possible?
"test": {
"body": ["${1|choice1,choice2,$TM_FILENAME_BASE|}"],
"desciption": "test",
"prefix": "test"
}
Has somebody a solution for me?
Unfortunately, it is impossible to include variables in snippets.
However, there is an alternative.
My example:
"Now": {
"prefix": "NOW",
"body": "${CURRENT_HOUR}:${CURRENT_MINUTE}${1| TODAY, |}",
"description": "Now"
},
"Today's Date": {
"prefix": "TODAY",
"body": [
"$CURRENT_DAY_NAME_SHORT, $CURRENT_MONTH_NAME_SHORT $CURRENT_DATE, $CURRENT_YEAR"
],
"description": "Today's Date"
}
, by which you can expand the "TODAY" snippet by tab once more.
There is an issue filed on this: Support Snippet Variables in Snippet Enums.
Which is now a candidate for the Backlog list - so go and upvote the issue if you would like to see this implemented natively.

Explorer/Context Menus. Is it possible to change folder context depending on a file inside the folder?

So I currently have context menus based off the folder in VScode.
I am wondering if I can do context based on whether the file exists inside the folder. An example being if temp.exe doesn't exist in the folder don't show the context?
Can't seem to find anywhere in the documentation.
Thanks,
Trent
This is for a Vscode extension. I've only tried the ability to get context based on filetype.
"menus": {
"explorer/context":[
{
"when": "explorerResourceIsFolder",
"command": "extension.runApp",
"group": "vm#1"
},
{
"when":"explorerResourceIsFolder",
"command": "extension.provisionApp",
"group": "vm#2"
}
]
}
This in operator for when clauses looks like it is what you were looking for. From the v1.49 Release Notes:
We have added a new in operator for when clauses. This new
operator allows for a dynamic lookup of a context key's value within
another context key's value. For example, if you wanted to add a
context menu command to folders that contain a certain type of file
(or something that can't be statically known), you can now use the
in operator to achieve it.
vscode.executeCommand('setContext', 'ext:supportedFolders', [ 'test', 'foo', 'bar' ]);
// Note in this case (using an object), the value doesn't matter, it is based on the existence of the key in the object
vscode.executeCommand('setContext', 'ext:supportedFolders', { 'test': true, 'foo': 'anything', 'bar': false });
// Note, this assumes you have already defined a command called ext.doSpecial
"menus": {
"explorer/context": [
{
"command": "ext.doSpecial",
"when": "explorerResourceIsFolder && resourceFilename in ext:supportedFolders"
}
]
}
In that example, we are taking the value of resourceFilename (which
is the name of the folder in this case) and checking for its existence
in the value of ext:supportedFolders. If it exists the menu will be
shown.

Filter a snippet by filename or extension, like *.spec.ts and *.spec.js?

I want to add a couple of snippets to use when creating javascript/typescript unit tests but I do not find any way to set the global scope of the snippet to *.spec.ts or *.spec.js
Is this possible? In the documentation they say that the scope is bases on the language identifier but I just see a way to add another extensions to each language there.
You can do this for snippets. In your keybindings.json:
{
"key": "shift+alt+2",
"command": "editor.action.insertSnippet",
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
// with the snippet text directly in the keybinding
"args": {
"snippet": "console.log($1)$0"
}
},
or this keybinding:
{
"key": "shift+alt+2",
"command": "editor.action.insertSnippet",
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
"args": {
"name": "unit tests"
}
}
with this snippet in a snippet file:
"unit tests": {
// "prefix": "", // not used here
"body": [
"console.log($1)$0",
],
The key to limiting the scope of the snippet is this when clause:
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
which as a regular expression would look for a filename ending with .spec.ts or .spec.js (note that you need double escapes before the period). So use the resourceFileName and construct a regex that looks at the end of it.
Now your chosen keybinding will work in a *.spec.ts or *.spec.js file only.
See a when clause acting as a regular expression, in keybindings documentation:
key-value when clause operator
There is a key-value pair operator for when clauses. The expression
key =~ value treats the right hand side as a regular expression to
match against the left hand side. For example, to contribute context
menu items for all Docker files, one could use:
"when": "resourceFilename =~ /docker/"
I found this thanks to this issue: resourceExtname with two dots not working