Version 1.15.0 of vscode seems to aggressively change the indenting of access modifiers in C++ code, despite disabling autoIndent and formatOnType.
When I enter this:
class Foo
{
public:
Foo();
};
It gets reformatted as soon as I hit enter after typing "public:", to this:
class Foo
{
public:
Foo();
};
In my user settings I have "editor.autoIndent" and "editor.formatOnType" set to false. I also have "C_Cpp.formatting" in the C++ extension set to "Disabled".
Is there some way to control this behavior?
Have you tried to set this option to false?
"C_Cpp.clang_format_formatOnSave": false,
Edited
Also take a look at this option:
editor.formatOnSave
I found a way to do this by modifying the language configuration file for C++. It is located in the Microsoft VS Code directory here: resources/app/extension/cpp/language-configuration.json.
I removed the items in the "increaseIndentPattern" and "decreaseIndentPattern" that were related to access modifiers.
This works, but editing the file directly seems like a bad idea.
Related
When autocompleting a class in C++ on VS code, it will print private first and public second. I would like to change the defaults to the opposite but I cannot find where to access these settings. Is there a key you can set in the c_cpp_properties.json file maybe?
Alright, so I thought that CLang-format had a setting like the one you asked for. I looked through the link above's documentation (which I know fairly well) for a rule that organizes the access modifiers, but there doesn't seem to be one. I also poked around VS Code, and to no ones supprise, VS Code didn't have anything worth mentioning either.
There is Good Option that Might Work for You Though.
This solution is called VS Code Snippets. The snippets are what you are using when you click the suggestion that auto completes. The template that creates the class is defined in the Snippet cpp.json document, or if you downloaded a snippets extension for C++ they might live their. Either way, you can just write your own "C++ Class Snippet",and use that. The snippet will be auto completed in what ever manner you define it. Here is one I wrote, to demonstrate what you can do:
FYI: You are already using snippets each time you use an auto-completion, your just using snippets that someone else wrote.
IMO, VSCode has the best support, by far, for writing auto completions.
"C++ Class Snippet (public first) #JCSB": {
"prefix": "class",
"body":[
"class ${0:Name} {",
"\npublic:",
"\n ${1:publicMember}", // PUBLIC MEMBERS
"\n ${2:publicMember}",
"\n ${3:publicMember}",
"\nprivate:",
"\n ${4:privateMember}", // PRIVATE MEMBERS
"\n ${5:privateMember}",
"\n ${6:privateMember}",
"\nprotected:",
"\n ${7:protectedMember}", // PROTECTED MEMBERS
"\n};"
],
"description": "(#JCSB) C++ class w/ public access modifier placed first."
}
The class has 4 Place holders ($0, $1, $2 & $3).
$0: "choose class name"
$1: "Set your public members"
$2: "Set your private members"
$3: "Author your methods."
You can move from one placeholder to the next using the Tab key.
HELPFULL LINKS:
Official Snippets Documentation
You should read about Emmets as well at the link below:
Read about configuring the "V.S. Code Intellisense Extension". This page will tell you how to configure it, which is an advanced topic with information that is capable of changing the way you look at V.S. Code & how you use its tools & features.
One Last Tip:
Add the following configurations to your settings.json file to make sure your snippets take priority over suggestions and built-in snippets in the suggestions-widget. Quick suggestions is a suggested word, or syntax that intellisense puts at the top. Those who write there own snippets often find it useful to prioritize their snippets over the quick suggestions.
// #file "settings.json"
{
"editor.snippetSuggestions": "inline",
"editor.suggest.showSnippets": true,
"editor.suggest.snippetsPreventQuickSuggestions": true,
}
I'm contributing to an open issue regarding keybindings and custom editors. More specifically, if one were to edit a Markdown file in the standard .md text editor then hit CMD+S, not only does VSCode save the edits on the open file, but it also toggles to the Markdown's preview mode.
Right now, I have a custom editor save command in the works, and the constructor/keybindings is as follows (in TypeScript):
(new class SaveCustomEditorCommand extends Command {
public static readonly ID = 'editor.action.customEditor.save';
constructor() {
super({
id: SaveCustomEditorCommand.ID,
precondition: CONTEXT_HAS_CUSTOM_EDITORS,
kbOpts: {
primary: KeyMod.CtrlCmd | KeyCode.KEY_S,
weight: KeybindingWeight.EditorContrib
}
});
}
... // fully implemented runCommand function
}).register();
As the command is, hitting CMD+S simply saves the changes and nothing more. However, if I were to change the KeyCode from KEY_S to KEY_Y (since CMD+Y isn't an already existing keybinding command), the save-to-preview command works as intended. Setting the weight property inside kbOpts to higher enums does not change anything.
I'm certain that somewhere in VSCode source, the File/Save CMD+S command takes total precedence, but given that my command should be running only under the precondition that the context has custom editors, I was wondering if I can somehow force my "Save and Preview" command to run instead of the simple, universal "Save" command.
Any pointers or guidance would be much appreciated; this is my first contribution to anything open-source!
If keeping CMD+Y is the more feasible course of action for a "Save and Preview" keybinding, then that works for me, but I would like to least try with CMD+S if possible.
For my extension I need to know when a cut/copy/paste happens and be able to get the text associated with those operations. I can probably get the text from the editor if I know when they happen.
I cannot find a listener for these operations. I suppose I can look for ctrl-x, ctrl-c, and ctrl-v keyboard inputs but some users may use the edit menu and not use the keyboard.
Is there a way to be notified when these operations happen either from the keyboard or the edit menu?
Original asker here...
I came up with a solution that involves overriding the default cut/copy/paste actions in the editor. Here is the code for 'copy' in extension.js (I am using js not ts):
//override the editor.action.clipboardCopyAction with our own
var clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction);
context.subscriptions.push(clipboardCopyDisposable);
/*
* Function that overrides the default copy behavior. We get the selection and use it, dispose of this registered
* command (returning to the default editor.action.clipboardCopyAction), invoke the default one, and then re-register it after the default completes
*/
function overriddenClipboardCopyAction(textEditor, edit, params) {
//debug
console.log("---COPY TEST---");
//use the selected text that is being copied here
getCurrentSelectionEvents(); //not shown for brevity
//dispose of the overridden editor.action.clipboardCopyAction- back to default copy behavior
clipboardCopyDisposable.dispose();
//execute the default editor.action.clipboardCopyAction to copy
vscode.commands.executeCommand("editor.action.clipboardCopyAction").then(function(){
console.log("After Copy");
//add the overridden editor.action.clipboardCopyAction back
clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction);
context.subscriptions.push(clipboardCopyDisposable);
});
}
This definitely doesn't feel like the best solution... however it does seem to work. Any comments/suggestions? Are there any issues that repeatedly registering and unregistering will cause?
There is no api to access the clipboard directly but some extensions override the default copy and paste shortcuts to customize the copy paste behavior. Here are two examples:
https://github.com/aefernandes/vscode-clipboard-history-extension/blob/master/src/clipboard.ts
https://github.com/stef-levesque/vscode-multiclip/blob/master/src/extension.ts
As you note, that approach will not work when copying using the context menu however. For supporting that as well, you could try intercepting the editor.action.clipboardCopyAction command. See how the Vim extension intercepts the type command for an example of this: https://github.com/VSCodeVim/Vim/blob/aa8d9549ac0d31b393a9346788f9a9a93187c222/extension.ts#L208
There is a proposed api in v1.68 for intercepting and modifying pastes. Since it is proposed for now you can only test it in the Insiders Build.
See copy/paste proposed extension api:
The new documentPaste API proposal lets extensions hook into copy
and paste inside text editors. This can be used to modify the text
that is inserted on paste. Your extension can also store metadata when
text copy and use this metadata when pasting (for example for bringing
along imports when pasting between two code files).
The document paste extension
sample
shows this API in action: <-long code example in the release notes->
Here is the actual (brief) api: proposed documentPaste api
See also using a proposed api
I need to ignore .history folder from intellisense.
Now it looks like this when I start typing Focus:
As you can see intellisense will offer me every Identical class found in .history folder and this is very very confusing (and find correct one).
I try find something in vscode settings, and on editor site but no success.
.history folder is ignored from git, display in explorer, and tslint:
"files.exclude": {
"**/.history": true ...
},
"files.watcherExclude": {
"**/.history/**": true ...
},
"tslint.exclude": ["**/.history/**"] ...
How to achieve ignore .history from intellisense?
Next part is based on the answer from Matt
An important assumption:
Visual Studio Code itself does not contain automatic import and you need an extension for it.
Solution:
I am using extension Auto Import (steoates.autoimport) which contains the setting autoimport.filesToScan. I changed default value from "**/*.{ts,tsx}" to "{src,e2e,node_modules}/**/*.{ts,tsx}" and now everything work as I expected.
Those suggestions are coming whatever extension you have installed that is providing auto-import functionality. Please check to see if that extension has its own exclude setting that you also need to configure
In your settings.json, you could add this:
"autoimport.filesToScan": "./index.{ts,tsx} ./App.{ts,tsx} ./src/**.*.{ts,tsx}"
Or, if you prefer:
"autoimport.filesToScan": "./{index,App,src/**}.{ts,tsx}"
Is there any shortcut that will allow me to auto generate my typescript imports? Like hitting ctrl+space next to the type name and having the import declaration placed at the top of the file. If not, what about intellisense for filling out the module reference path so that I wont have to do it manually? I would really love to use vscode but having to do manual imports for typescript is killing me.
There are rumors of making it support tsconfig.json (well, better than rumors). This will allow us to be able to use all files for our references.
Your feature would be to create an auto import of all commonly used 3rd party libs into the typings. Perhaps auto scan the files and create a list of ones to go gather. Wouldn't it be fine to just have a quick way to add several of these using tsd directly from Code (interactively)?
I believe the plugin called "TypeScript Importer" does exactly what You mean: https://marketplace.visualstudio.com/items?itemName=pmneo.tsimporter .
Automatically searches for TypeScript definitions in workspace files and provides all known symbols as completion item to allow code completion.
With it You can truly use Ctrl+Space to choose what exactly You would like to be imported.
You can find and install it from Ctrl+Shift+X menu or just by pasting ext install tsimporter in Quick Open menu opened with Ctrl+P.
I know a solution for Visual Studio (not Visual Studio Code, I'm using the 2015 Community edition, which is free), but it needs some setup and coding -- however, I find the results to be adequate.
Basically, in Visual Studio, when using the Web-Essentials extension, .ts files can be dragged into the active document to automatically generate a relative reference path comment:
/// <reference path="lib/foo.ts" />
With which of course we might as well wipe it, because it's an import statement we need, not a reference comment.
For this reason, I recently wrote the following command snippet for Visual Commander, but it should be easily adaptable to other use casese as well. With Visual Commander, your drag the needed imports into the open document, then run the following macro:
using EnvDTE;
using EnvDTE80;
using System.Text.RegularExpressions;
public class C : VisualCommanderExt.ICommand
{
// Called by Visual Commander extension.
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
TextDocument doc = (TextDocument)(DTE.ActiveDocument.Object("TextDocument"));
var p = doc.StartPoint.CreateEditPoint();
string s = p.GetText(doc.EndPoint);
p.ReplaceText(doc.EndPoint, this.ReplaceReferences(s), (int)vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers);
}
// Converts "reference" syntax to "ES6 import" syntax.
private string ReplaceReferences(string text)
{
string pattern = "\\/\\/\\/ *<reference *path *= *\"([^\"]*)(?:\\.ts)\" *\\/>";
var regex = new Regex(pattern);
var matches = Regex.Matches(text, pattern);
return Regex.Replace(text, pattern, "import {} from \"./$1\";");
}
}
When running this snippet, all reference comments in the active document will be replaced with import statements. The above example is converted to:
import {} from "./lib/foo";
This has just been released in version 1.18.
From the release notes:
Auto Import for JavaScript and TypeScript
Speed up your coding with auto imports for JavaScript and TypeScript. The suggestion list now includes all exported symbols in the current project. Just start typing:
If you choose one of the suggestion from another file or module, VS Code will automatically add an import for it. In this example, VS Code adds an import for Hercules to the top of the file:
Auto imports requires TypeScript 2.6+. You can disable auto imports by setting "typescript.autoImportSuggestions.enabled": false.
The files attributes in the tsconfig.json file allows you to set your reference imports in your whole project. It is supported with Visual Studio Code, but please note that if you're using a specific build chain (such as tsify/browserify) it might not work when compiling your project.