How do I tweak how VSCode format JavaScript? - visual-studio-code

How do I make Visual Studio Code insert a space after the function keyword, when I autoformat a JavaScript file with Alt+Shift+F?
// How I would like it:
var f = function (a) { ... }
// How VSCode is formatting by default:
var f = function(a) { ... }
I would assume this is possible placing a file in ~/.vscode/extensions/javascript, possibly by making a copy of VSCode's JavaScript.tmLanguage file and making a small change in it, but that's as far as I have gotten for now.

If you are using VS Code's built-in JS/TS formatter, this is controlled by:
"javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true
"typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true
These are the default values.

Related

How to trigger activation of the vscode markdown extension

In my VS Code extension I have some code that uses the built in Markdown extension. I capture a reference to it by registering as a markdown plugin and putting the following code at the end of my extension's activate method.
return {
extendMarkdownIt(mdparam: any) {
return md = mdparam;
}
};
Markdown calls this when it activates.
Generally this is not a problem. Most of the use cases for my extension involve a markdown file already loaded into the active editor, and the loading of this file triggers activation of the markdown extension.
However there are some legitimate use cases in which this is not so.
I need to programmatically trigger activation of the markdown extension. Some of these cases involve having a different kind of file open in the active editor so loading a markdown file into it is not an acceptable option.
Some potential strategies:
Change the language mode. There is a command workbench.action.editor.changeLanguageMode but no documentation. I tried
vscode.commands.executeCommand('workbench.action.editor.changeLanguageMode', 'md');
but this triggers the UI
so I tried a pattern I've seen in the parameters of other commands and added , true. This suppressed the UI but doesn't seem to work.
Load a markdown file into a new editor then close it again. This should work, but it's ugly.
Put something in the contributions section of my extension that changes the activation trigger for the markdown extension so that it is triggered by the other file types on which my extension operates.
Of these options my favourite would be 3 but I don't even know whether this is even possible. Option 1 is hampered by the crappy (in many cases non-existent) documentation for vscode internal commands.
Option 1 it is. If anyone knows how to do option 3 please tell, the solution below is a ghastly hack.
It is possible to trigger activation of the Markdown extension by changing the document language of any open editor to markdown. In the event that there are no open editors a document with the markdown language set can be created in memory and loaded into an editor.
If VS Code is busy loading extensions activation can take several hundred milliseconds so the best thing to do is watch the variable into which markdown-it is captured.
The variable md is a global (global to my extension, not the whole of VS Code) into which a reference is acquired as shown in the question.
let ed = vscode.window.activeTextEditor;
if (ed) {
let lid = ed.document.languageId;
if (lid !== "markdown") {
vscode.languages.setTextDocumentLanguage(ed.document, "markdown").then(
function waitForMd() {
if (md) {
vscode.languages.setTextDocumentLanguage(ed!.document, lid);
} else {
setTimeout(waitForMd, 100);
}
}
);
}
} else {
vscode.workspace.openTextDocument({ language: "markdown" }).then(doc => {
vscode.window.showTextDocument(doc).then(
function waitForMd() {
if (md) {
vscode.commands.executeCommand("workbench.action.closeActiveEditor");
} else {
setTimeout(waitForMd, 100);
}
});
});
}
Once the capture completes we can restore the true language or close the editor as appropriate. To be realistic the second case (no active editor) is unlikely because my own extension won't activate until you load something. At any rate it works stably now. The larger project is progressing nicely.

How to prevent VS Code from putting '{' on new line in C++ formatting?

If I write some code
void function() {
....
}
when I format the entire page using Shift+Alt+F, it becomes
void function()
{
....
}
How do I prevent that initial opening bracket from going to a new line?
Assuming you're using the MS C++ extension, these are the docs you're after. In > short, you'd need to either:
change C_Cpp.clang_format_fallbackStyle to one of: LLVM, Google, Chromium, > Mozilla, WebKit - and see if one matches your preferences.
find/make a custom .clang-format file
see clang-format docs for more details: > https://clang.llvm.org/docs/ClangFormatStyleOptions.html
https://www.reddit.com/r/vscode/comments/9rqj02/prevent_vscode_from_putting_c_curly_braces_on_new/

Variable lookup extension in Visual Studio Code

I am looking at some code where some of the variables are really obscure. For example,
h582=30
where h582 might mean temperature. I have a dictionary that tells me what each variable means. Is there any existing feature or would it be possible to extend visual studio code easily to show me the meaning of each variable on mouse hover?
I would recommend using find/replace on the workspace to rewrite the variables to their readable names (I would go crazy trying to read code like that).
But if you can't do that and want to see the real name when you hover the variable, you could write a vscode extension for this. It would not be too hard - you just need to implement a hover provider which would check the name of the token under the cursor, look it up in the dictionary, and return the result. Example:
vscode.languages.registerHoverProvider('javascript', {
provideHover(document, position, token) {
const hoveredWord = document.getText(document.getWordRangeAtPosition(position));
const mappedWord = dictionary[hoveredWord]
if (mappedWord) {
return new Hover(mappedWord);
} else {
return null;
}
}
});
See the docs here: https://code.visualstudio.com/docs/extensionAPI/vscode-api#_languages

Set language of a text document in a VSCode extension

I have a Visual Studio Code extension where I try to open a
virtual editor:
vscode.workspace.openTextDocument(vscode.Uri.parse(previewSchema + ":" + path))
context.subscriptions.push(extractHibernateLogCommand, vscode.Disposable.from(
vscode.workspace.registerTextDocumentContentProvider(previewSchema, hibernateExtractorProvider)
));
Those documents are always language:plain-text. Is it possible to change this programmatically to "SQL" to have the correct highlighting?
Full code
Since VSCode 1.28 (September 2018), it's also possible to set the language mode for a document after it has been created using languages.setTextDocumentLanguage():
Set (and change) the language that is associated with the given document.
Note that calling this function will trigger the onDidCloseTextDocument event followed by the onDidOpenTextDocument event.
Here's a simple example that opens a document containing {} and sets the language to JSON:
vscode.workspace.openTextDocument({content: "{}"}).then(document => {
vscode.window.showTextDocument(document);
vscode.languages.setTextDocumentLanguage(document, "json");
});
I found a solution by myself:
let options: Object = {
content: string,
language: "sql"
};
vscode.workspace.openTextDocument(options).then(doc => {
vscode.window.showTextDocument(doc, vscode.ViewColumn.One);
}, err => {
vscode.window.showErrorMessage(err);
});
A solution when using TextDocumentContentProvider seems not to be possible.
The commit with my change
Open the Command Palette (View->Command Palette)
run "Configure language specific settings"
In the Select Language drop down there should be a setting for SQL

adding syntax highlighting to Jupyter notebook cell magic

I'm trying to figure out how to activate CodeMirror syntax highlighting for a CodeMirror-supported language (cypher) within a cell for a custom Jupyter cell magic (%%mymagic). The magic isn't associated with a special kernel - it just runs Python commands that process the string entered into the cell that I want to highlight. From what I can tell, this ostensibly can be done using something like
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})
within the class that implements the magic.
I can't seem to get this to work, however; no change in highlighting occurs when I enter stuff in a cell that starts with %%mymagic. Is the above approach accurate? Does 'magic_cypher' need to have a specific format? Does the magic need to somehow specify the MIME type CodeMirror associates with the desired highlighting language? I'm using notebook 5.0.0, jupyter_core 4.3.0, and python 2.7.13.
The following code works for SQL when placed in ~/.jupyter/custom/custom.js with notebook 5.x:
require(['notebook/js/codecell'], function(codecell) {
codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
Jupyter.notebook.events.one('kernel_ready.Kernel', function(){
Jupyter.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
});
Credit goes to Thomas K for this info!
The case where I've been successful doing this was in adding SQL highlighting for the %%sql magic. I did this by adding the following to ~/.jupyter/custom/custom.js. The first line adds the mode to the Codemirror configuration, the rest apply the style to any existing cells in the workbook that need it (later cells will get styled appropriately as they are created). I haven't been successful in having it happen when the magic is installed, although I expect that it is possible.
IPython.CodeCell.config_defaults.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
IPython.notebook.events.one('kernel_ready.Kernel', function(){
IPython.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});