Hide/fold/dim arbitrary lines of code by regex (e.g. to hide logging) - c++

There is a lot of logging in my C++ project. The logging is done via a log stream and the log lines have the following format:
APP_LOG_XXX() << ... ;
Those log lines blend with the rest of the code and make it harder to be read.
I want to somehow make these log lines appear in dimmed colors, or even better to hide/fold by a hotkey or click. There are a lot of log lines already, so wrapping them up in #pragma region would take much time (or would require writing a separate script). I wonder if there is an easier way.
(There is a very similar question on SO, but it's about Visual Studio, not Visual Studio Code).

You can use extension Highlight.
Set the color to a version close to your theme background color
Add to your settings.json
"highlight.regexes": {
"(APP_LOG_XXX\\(\\) <<[^;]+;)": {
"regexFlags": "mg",
"decorations": [
{ "color": "#f0f0f0" }
]
}
}
Or you can use the opacity decoration property instead. The following configuration will dim the text while preserving its current syntax highlighting:
"highlight.regexes": {
"(APP_LOG_XXX\\(\\) <<[^;]+;)": {
"regexFlags": "mg",
"decorations": [
{ "opacity": "0.4" }
]
}
}

Related

How to make VSCode indent an if statement without brackets?

I'd like for VSCode to indent automatically indent when I create a newline in the following case:
if(statement)
func();
The default functionality does the following when hitting newline:
if(statement)
func();
This is a longstanding issue in VSCode: https://github.com/microsoft/vscode/issues/43244
I'd appreciate any kind of hack/extension that can accomplish this behavior. There are other instances of indentation getting mangled in the github issue link, but I only really care about this simple case.
Figured out how to do this without installing an extension. There may be a better way that can be done in settings.json but I couldn't find it. You can modify a languages configuration directly from the source, which for me was C:\Program Files\Microsoft VS Code\resources\app\extensions\cpp\language-configuration.json. There is a guide for these files settings. I added the following to my c++ language configuration:
"onEnterRules": [
{
"beforeText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
"action": {
"indent": "indent"
}
},
{
"beforeText": "(?=)",
"previousLineText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
"action": {
"indent": "outdent"
}
}
]
This works, but unfortunately the official c++ vscode extension C/C++ for Visual Studio Code breaks it for some reason.
Below was my initial method of doing this, which breaks too many things to be useful.
"indentationRules": {
"increaseIndentPattern": "^\\s*if\\(.*\\)\\s*$",
"decreaseIndentPattern": "(?!)"
}
The field decreaseIndentPattern must be set (here the regex will never capture anything), otherwise it ignores the indentationRules field (I guess they never tested whether just one would be set?) Note that these edits need to be done with administrative privleges, and I found VSCode pretty convenient for making them. Also these changes do not take effect until VSCode is closed.
So as it turns out I've run into the same issues mentioned in this PR: https://github.com/microsoft/vscode/pull/115454. This fix breaks too much other vscode indentation behavior, such as deindenting after the first properly indented line in if statements.

The Prettier Extension is not correcting inconsistent formatting of code

I have downloaded some exercise files to learn how to use Javascript. I am using Visual Studio Code as the editor and can open the exercise javascript files in the editor. I have installed the extensions Prettier - Code Formatter and ESlint and Live Server and npm-install and advised in the course video. The ESlint extension seems to work ok i.e. when I remove some of the code, errors in the code are underscored and when I move the mouse over the error a pop-up indicates what is missing. However, in the code below I removed the opening and closing brackets around the word 'update' and indented the line which begins with the word 'main.' and remove the semi colon which should follow the first bracket. However, the Prettier extension does not correct these amends, as the video advised it should and I received the error ["ERROR" - 14:55:15] Prettier could not be loaded. See previous logs for more information.
const updateBackpack = (update) => {
let main = document.querySelector("main"); // main is an element
main.innerHTML = markup(backpack);
console.info(update);
};
Do you know why Prettier is not working and how I can get it to work. Please bear in mind I am new to coding and Javascript.
Thanks,
Clive
I think you have the exact same problem as me, while following the exact same course as me :D!
First install prettier, using :
npm i prettier -g
Then configure the VS code to pick that downloaded package.
Here is what I did : Search for 'Prettier Path' in settings > select 'Edit in settings.json' and add the following config :
{
"editor.minimap.enabled": false,
"editor.fontSize": 12,
"editor.formatOnSave": true,
"editor.tabSize": 2,
"liveServer.settings.donotShowInfoMsg": true,
"editor.wordWrap": "on",
"emmet.triggerExpansionOnTab": true,
"emmet.showSuggestionsAsSnippets": true,
"editor.snippetSuggestions": "top",
"[javascript]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": true
},
"workbench.colorTheme": "Monokai",
"window.zoomLevel": 0,
"editor.columnSelection": false,
"explorer.compactFolders": false,
"typescript.updateImportsOnFileMove.enabled": "always",
"javascript.updateImportsOnFileMove.enabled": "always",
"liveServer.settings.donotVerifyTags": true,
"prettier.prettierPath": "/usr/local/lib/node_modules/prettier"
}
Make sure prettier is installed at the given path : "prettier.prettierPath": "/usr/local/lib/node_modules/prettier"
You can make prettier the default also by uncommenting the code : "editor.defaultFormatter": "esbenp.prettier-vscode"
It has my custom settings of visuals, so review those and then set, for beginners try pasting as-is!

How to set the Visual Studio Code find widget to 'Use Regular Expression' when it is not and to turn it off when it is using it - from an extension

I am working on a Visual Studio Code extension that opens the find widget, clipboard content is pasted into it to be searched for in the current document. At times the search string is a regular expression, other times it is not. Is it possible to set the find to search using the regular expression when the search string contains one, and to turn off the regular expression when not needed? All I have found is a command to blindly toggle the regular expression usage without knowing what it presently is set to. Here is the code section for my extension - this works, but the user needs to set or unset the regular expression usage:
case "GotoCode": {
// Calc Helper: Goto [i.e.find] this code.
// We keep the Find Widget open.
let editor = vscode.window.activeTextEditor;
if (!editor) { return; }
vscode.commands.executeCommand("actions.find").then(res => {
vscode.commands.executeCommand("editor.action.clipboardPasteAction");
}, err => {
vscode.window.showErrorMessage(`ERROR: ${err.message}`);
});
break;
}
Thank You!

Can I programmatically collapse/expand all preprocessor blocks of a certain name in Visual Studio 2012?

My current project has a lot of debug preprocessor blocks scattered throughout the code. These are intentionally named differently to the system _DEBUG and NDEBUG macros, so I have a lot of this:
// Some code here
#ifdef PROJNAME_DEBUG
//unit tests, assumption testing, etc.
#endif
// code continues
These blocks sometimes get rather large, and their presence can sometimes inhibit code readability. In Visual Studio 2012 I can easily collapse these, but it would be nice to automatically have all of them collapsed, allowing me to expand them if I want to see what's in there. However, as I also have a bunch of header guards I don't want to collapse all preprocessor blocks, only the #ifdef PROJNAME_DEBUG ones.
Can I do this?
This is the most easiest scenario you can achive it, I think.
You should create an Add-In first in C#. (in VS 2013 they become deprecated :( )
In the OnConnection method you should add your command:
public void OnConnection( object application, ext_ConnectMode connectMode, object addInInst, ref Array custom )
{
_applicationObject = (DTE2)application;
if (connectMode == ext_ConnectMode.ext_cm_AfterStartup || connectMode == ext_ConnectMode.ext_cm_Startup)
{
Commands2 commands = (Commands2)_applicationObject.Commands;
try
{
//Add a command to the Commands collection:
Command command = commands.AddNamedCommand2(_addInInstance, "MyAddinMenuBar", "MyAddinMenuBar", "Executes the command for MyAddinMenuBar", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
}
catch (System.ArgumentException)
{
//If we are here, bla, bla... (Auto generated)
}
}
}
Note: you can find how parameters are act at the reference of AddNamedCommand2
The template created version would be also fine, but naturaly it worth to name your command properly.
After that you need to add your logic to Exec method:
public void Exec( string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled )
{
handled = false;
if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if (commandName == "MyAddinMenuBar.Connect.MyAddinMenuBar")
{
List<string> args = (varIn as string).Split(' ').ToList();
TextSelection ts;
ts = (TextSelection)_applicationObject.ActiveDocument.Selection;
EditPoint ep = (ts.ActivePoint).CreateEditPoint();
ep.StartOfDocument();
do
{
string actualLine = ep.GetLines(ep.Line, ep.Line + 1);
if (args.TrueForAll(filter => actualLine.Contains(filter)))
{
_applicationObject.ExecuteCommand("Edit.GoTo", ep.Line.ToString());
_applicationObject.ExecuteCommand("Edit.ToggleOutliningExpansion");
}
ep.LineDown();
} while (!ep.AtEndOfDocument);
handled = true;
return;
}
}
}
Note: Name you given to the command is checked in exec.
Than you can build.
Deployment of Add-In can happen through an [ProjectName].AddIn file in ..\Documents\Visaul Studio 20[XY]\AddIns\. (Created by the template, you should copy if you move the Add-In elsewhere)
You should place your Add-In assembly where the Assembly element of the mentioned file you set to point. To change version you should modify the text in Version element.
After you deployed and started Studio, you should activate the Add-In in the manager in Toolsmenu.
You need to expand all collapsable section in your code file (CTRL+M+L with C# IDE settigs).
This is required because I found only a way to invert the state of collapsion. If you find better command, you can change it.
Next you should activate Command Window to use the the created command.
Now only you need to type your commands name, like this:
MyAddinMenuBar.Connect.MyAddinMenuBar #ifdef PROJNAME_DEBUG
Hopefully magic will happen.
This solution is independent of language of code you edit so pretty multifunctional.

How do I write a very simple Visual Studio debugger visualizer?

I'm trying to write an 'autoexp.dat'-based visualizer for a string type. I've scaled-back my ambitions to attempting to write a visualizer for a really simple test type that contains a null-terminated string field:
namespace thizz { namespace izz {
class MyType {
const char* _ptr;
public:
MyType(const char* ptr) : _ptr(ptr) {}
};
}
}
This is my stab at a visualiser, but it has no effect on how Visual Studio (2010) displays an instance of this type:
thizz::izz::MyType
{
preview ([$e._ptr,s])
}
(That's going at the top of the [Visualizers] section in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\autoexp.dat).
Watching an instance of this type:
thizz::izz::MyType t("testing testing");
Just displays
t | {_ptr=0x0f56a6fc "testing testing" } | thizz::izz::MyType
in the Watch window.
To get an even more versatile viewer try changing to use this:
thizz::izz::MyType {
preview ( #( [$e._ptr,s] ) )
stringview ( #( [$e._ptr,sb] ) )
}
this will also give the magnifying glass icon which will open a larger text view window in the case that you have a longer string. It'll also give you the option of rendering as HTML or XML.
Note that as well as the format of the file being sensitive to whitespace, I've also found that you can't use a colon in the string otherwise it generates parse errors.
The debugger visualisers are incredibly powerful, though the syntax can be quite bewildering. As general advice I would suggest creating some entries first in the [AutoExpand] section to summarise the data types that you are most interested in, and then if you have custom containers then copy and adapt the examples for vector, list, etc, which will give you the largest return for the investment in your time.
I can't give a categorical reason why my original 'code' in autoexp.dat was not working, but I found that the same code worked when all the whitespace was removed.
I then tried re-adding whitespace and found that keeping the initial open brace on the first line was necessary to keep the definition working.