How to format Blazor code correctly in VS code? [duplicate] - visual-studio-code

Anyone have a good solution for formatting Razor files inside of VSCode? I've tried making it work with prettify-vscode and beautify. But in both cases it can't tell that cshtml files. I don't want to change my razor to html as I'll lose a lot of the razor-ness.

You can introduce them as HTML files (File -> Preferences -> Settings) without any 3rd party extensions:
{
"editor.formatOnSave": true,
"emmet.includeLanguages": {
"aspnetcorerazor": "html"
},
"files.associations": {
"*.cshtml": "html"
}
}
Update: v1.17.0 of C# for Visual Studio Code add-on added preview Razor (cshtml) language service with support for C# completions and diagnostics.

There is an extension that we can switch between Language Modes by shortcuts quickly: changeLanguageMode.change
I use these shortcuts for js, html, and cshtml:
{
"key":"ctrl+k j",
"command":"changeLanguageMode.change",
"args": {
"languageId":"javascript"
}
},
{
"key":"ctrl+k h",
"command":"changeLanguageMode.change",
"args": {
"languageId":"html"
}
},
{
"key":"ctrl+k k",
"command":"changeLanguageMode.change",
"args": {
"languageId":"aspnetcorerazor"
}
}
To open keybindings.json and add these shortcuts:
open up the control palette with CTRL +SHIFT + P and select Preferences: Open Keyboard Shortcuts File.
Then use Ctrl + K, Ctrl + F to Format Selection only.

Firstly: open file setting.json, which is in .vscode folder, then add next block:
{
"editor.formatOnSave": true,
"emmet.includeLanguages": {
"razor": "html"
},
"files.associations": {
"*.cshtml": "html"
}
Sometimes is necessary restart vscode
Finally: in the file to format Ctrl + k , Ctrl + f

Related

VS Code Markdown Bold Shortcut Not Working

Usually, cmd + b or ctrl + b (in Windows) will make the selected text bold in a Markdown file but that's not working. How can I fix it?
By default, cmd + b is the keyboard shortcut for toggling sidebar visibility. To change it, add the following block of code in the keybindings.json file:
{
"key": "cmd+b",
"scope": "markdown",
"command":"editor.action.insertSnippet",
"when":"editorTextFocus && editorLangId == 'markdown'",
"args":{
"snippet":"**$TM_SELECTED_TEXT**$0"
}
}

Is there a way to enable intellisense autocomplete in quotes without using key binding (Ctrl + Space) in Visual Studio Code

I want to develop an extension for Visual Studio Code.
I'v registered a CompletionItemProvider for typescript, when I'm trying to write in quotes the auto completion does not work.
For example I have this code:
function buildProvider(language : vscode.DocumentSelector, label : string, text : string | vscode.CompletionItemLabel){
return vscode.languages.registerCompletionItemProvider('typescript', {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext) {
const simpleCompletion = new vscode.CompletionItem('', vscode.CompletionItemKind.Text);
simpleCompletion.label = label;
simpleCompletion.insertText = text.toString();
return [
simpleCompletion,
];
}
});
}
If I write in typescript the auto completion work:
Auto completion works
If I write in quotes it doesn't work without using Ctrl + Space.
Auto completion does not works
What can I do to enable the auto completion in quotes?
That behaviour, not working in strings, is probably a result of the setting:
editor.quickSuggestions.
Try setting it like this:
"editor.quickSuggestions": {
"other": true,
"comments": false,
"strings": true // this is the key setting, default is false3
}
That will fix it for you or anyone with the same "strings": true setting.
You can change a user's default settings in an extension like this in your `package.json - beware they may not like you changing their settings!!:
> #### Configuration Defaults Overrides
>
>
> You can now override defaults of other registered configurations
> through `configurationDefaults` contribution point in `package.json`.
> For example, the following snippet overrides the default behavior of
> `files.autoSave` setting to auto save files on focus change.
```jsonc
"contributes": {
"configurationDefaults": { // applies to all languages
"files.autoSave": "onFocusChange"
}
}
Note: Configurations with application or machine scopes cannot be
overridden.
From https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_63.md#configuration-defaults-overrides

How can vscode print (or paste) all open file paths to a new file in the editor?

In vscode Ctrl+Tab displays open files, but how can vscode print (or paste) the same 'all open file paths' to a new file in the editor?
If you have this setting set to a high enough number to show all your open files:
Editor > Open Editors: Visible
then you can select all the files from the Open Editors viewlet (with Ctrl+A for instance) in the Explorer, right-click and choose Copy Path or Copy Relative Path and then paste it yourself into a new file. Demo:
For how to automatically send selected (modify the variable for clipboard text) to a new file see my answer at https://stackoverflow.com/a/57612004/836330. I suppose the whole thing might be made into a macro.
Here is the macro. Using a macro extension like multi-command put this into your settings.json:
"multiCommand.commands": [
{
"command": "multiCommand.getOpenFilePaths",
"sequence": [
"workbench.files.action.focusOpenEditorsView",
"list.selectAll",
"copyFilePath", // full paths
// "copyRelativeFilePath", // relative paths
"workbench.action.files.newUntitledFile",
"editor.action.clipboardPasteAction",
// prompt for save immediately?
// "workbench.action.files.saveAs",
]
}
]
and some keybinding to trigger that macro:
{
"key": "alt+o", // whatever keybinding you wish
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.getOpenFilePaths" },
},
The Open Editors viewlet can be collapsed if you wish when you trigger the macro and it still works. Demo:
[Adding another answer because the first was long and very different.]
Here is a simpler way to print a list of the currently open files to a newly created file. It does not require that the Open Editors view be visible. It uses newer extension api to access the tabs currently open.
It uses an extension (I wrote), Find and Transform. In this extension, you can use the vscode extension api. Make this keybinding (in your keybindings.json) (it could also be made into a command accessible from the Command Palette):
{
"key": "alt+q", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
"replace": [
"$${",
"let str = '';",
"const groups = vscode.window.tabGroups.all;", // if multiple editor groups
"groups.map((group, index) => {",
"str += 'Group ' + (index+1) + '\\n';",
"group.tabs.map(tab => {",
"if (tab.input instanceof vscode.TabInputText) str += '\\t' + tab.input.uri.fsPath + '\\n';",
// the above prints the full path, use below if you only want the tab file label only
// "str += tab.label + '\\n';",
"});",
"str += '\\n';",
"});",
"vscode.env.clipboard.writeText( str );",
"return '';",
"}$$"
],
// open a new file and paste to it
"postCommands": ["workbench.action.files.newUntitledFile", "editor.action.clipboardPasteAction"]
},
}
To open a save file dialog use this "postCommands" entry.
"postCommands": [
"workbench.action.files.newUntitledFile",
"editor.action.clipboardPasteAction",
"workbench.action.files.save"
]

Create New Macro (Shortcut) to Copy Paste and Execute Code in the Integrated Terminal

The Problem
An operation I do a lot is to highlight/select code on the editors and then paste it on the integrated terminal to execute it. While I got pretty fast at using Ctrl + c, Ctrl + backtick, Ctrl + Shift + v and Enter, it's very annoying and repetitive. Is there a way to configure a macro or shortcut for this?
A Solution (failed) Attempt
This Github thread and this StackOverflow Question show how to create a shortcut to toggle between different Integrated Terminals. I would like for something similar to happen in my case (I used Ctrl + Shift + u in the example below), e.g.:
[
{
"key" : "ctrl+shift+k",
"command" : "workbench.action.terminal.focusNext"
},
{
"key" : "ctrl+shift+j",
"command" : "workbench.action.terminal.focusPrevious"
},
{
"key" : "ctrl+shift+u",
"command" : "ctrl+c+ctrl+`+ctrl+shift+v+enter"
},
]
Without VS Code Extensions
There is a command : workbench.action.terminal.runSelectedText which does what you want already and is not bound to any keychord by default.
[Just to see the sendSequence command]:
If you don't go another route, this keybinding will run the selected text in the terminal:
{
"key": "alt+t",
"command": "workbench.action.terminal.sendSequence",
"args": {
"text": "${selectedText}\u000D"
}
},
The \u000D is a return.
** [Added by Phillippe] :::
With a VS Code Extension (Macro Sequence Configurations)
VS Code currently doesn't allow concatenating shortcuts, so, if you want to execute the code on the Integrated Terminal and focus on it, you will have to install a macro extension.
There are several options for this. However, the suggested one is to use the multi-command (don't go for first results like macros, some of them are very outdated).
To create the shortcut mentioned above, create a sequence of commands in your settings.json file:
"multiCommand.commands": [ // Copy Paste to the Integrated Terminal and also Focus on it
{
"command": "multiCommand.copyPasteTerminalAndFocus",
"sequence": [
{
"command" : "workbench.action.terminal.sendSequence",
"args" : {"text" : "${selectedText}\u000D"}
},
"workbench.action.terminal.focus"
]
},
]
And then create a shortcut for it in the keybindings.json file:
{
"key": "alt+y",
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.copyPasteTerminalAndFocus" }
},

How do I contribute a command to the VS Code explorer title bar or command palette that is only active when my webview is focused?

I'm writing an extension that uses VS Code's webview api. My extension also registers a refresh preview command that updates the webview's content. How can I make it so that:
The refresh preview command only shows up in the command palette when my webview is focused?
The refresh preview command shows in the webview's editor title bar?
First, create a custom context key that tracks when your webview is focused. Use VS Code's setContext command to make this context key track when your webview is focused:
const myWebview = ...;
// Make the context key track when one of your webviews is focused
myWebview.onDidChangeViewState(({ webviewPanel }) => {
vscode.commands.executeCommand('setContext',
'myWebviewFocused',
webviewPanel.active);
});
Then use your context key in the when clauses of your extension's menus contribution point
For a command with the id myExtension.refreshPreview, to ensure that command only shows up in the command palette when your webview is focused, use the following contribution:
{
"contributes": {
"menus": {
"commandPalette": [
{
"command": "myExtension.refreshPreview",
"when": "myWebviewFocused",
}
]
}
}
}
For adding a command (possible with icon) to the editor title bar of your webview, use the editor/title contribution point:
{
"contributes": {
"menus": {
"editor/title": [
{
"command": "myExtension.refreshPreview",
"when": "myWebviewFocused",
}
]
}
}
}
Check out VS Code's built-in markdown extension for a more advanced example of this.