How to stop VS Code forcing me to use braces, otherwise the cursor position goes crazy (PHP, or apply it globally) - visual-studio-code

VS Code
if (1 == 1) // When I hit enter here, the cursor moves to the next line at pos (0)
|
else
return; // When I hit enter here, cursor moves to next line/ pos 4
| // why is the cursor here? why not pos 0?
Visual Studio (this is what I want to happen)
if (1 == 1) // When I hit enter here, the cursor moves to the next line at
| // pos 1 if I'm working with Tabs or pos 4 for spaces)
This is not a problem in VS Code if you use braces like this:
if (1 == 1){
return;
}
However, I don't like to use braces in those scenarios, and if I don't, VS Code naturally makes me end up writing this code which is also bad
if (1 == 1)
return;
I'm trying to get the same behaviour in VS Code. I can't seen to find a setting for this, or an extension. Please help. If I have to make an extension, or update the VS Code source and build it myself, I'm up for that, just please point me to the right direction. This is annoying.

You can create code snippet. F1 "usn" => choose language >>
"if": {
"prefix": "if",
"body": [
"if ($1)",
"\t$2",
"$3"
]
},
"ifelse": {
"prefix": "ifelse",
"body": [
"if ($1)",
"\t$2",
"else",
"\t$3",
"$4"
]
},
Just in case add this to settings.json ctrl+,:
"editor.snippetSuggestions": "top",

Related

Formating Visual Studio Column Jump

I'd like to edit my Visual Studio Code.
When I write my symbols on my keyboard to VSC, they'll get written Column by Column on the current Row.
\ Line of Code + Column.
(Ln , Col )
Extensions: "Select By"
= to jump to a certain column.
However, when i like to jump to 'column 50', it will only jump to the >End of Line.
// Example
// Goal is to get a Hotkey to Jump to Column 50
// Activated Hotkey*
cout << "Hello World:" << endl; // If i use my Hotkey i get to the Column 30, not 50. Picture is enhanced*
/* The end of line is here: 30. */
Question: How can I achieve my Jump
via the given Extension? (Any easy solution would be helpful).
I don't like to use the Ln, Col in Vsc, because clicking on the UI is for me over the time to slow.
I'd like to use f.e. Cmd + M to get to my "middle", So for me column 50.
Hence, i don't like to go to Middle of my current Screenformat.
Additional prefered Question: One way how i like to solve the issue is in C64 Style.
Is there any way to fill out the Visual Studio Code Screen by empty chars?
So as an Preset.
I know, that i can just copy & Paste. Or write an empty script. But that doesn't seem convenient inside the Configuration. I tryed to find that now unsucessfully since 2 weeks..
The reason is for me, that i currently try to code more cleaner.
And to achieve that (I have read many Clean Code Books during school and Github), i just like to try this time an historical approach by setting my own column points/ marks. (Basic C64-menu wise)
Thank you in advance!
Sincerely
Edit: I have enhanced beforehand.
Edit2: I have tryed the Find and Transform Extension pointed by Mark. Thank you for your time!
When i press the given Hotkey, It does marks the previous chars. but it doesn't start at column 50.
It marks at end of line.
I only like to move the cursor to column 50 and surpress the end of line.
does this key binding work
{
"key": "ctrl+i ctrl+m", // or any other key binding
"when": "editorTextFocus",
"command": "moveby.calculation",
"args": {
"charNrEx": "50"
}
}
Or use Ctrl+G and type lineNr:charNr
At the risk of not fully understanding the question, if what you want to do is pad any line to the 50th column with spaces, you can try this approach.
Install the extension Find and Transform
Make this keybinding (or it could be a command):
{
"key": "alt+q", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
// this will select the current line, cursor can start anywhere on line
"preCommands": ["cursorEnd", "cursorHomeSelect", "cursorHomeSelect"],
"replace": [
"$${",
"const str = `${TM_CURRENT_LINE}`;",
"let currentLength = str.length;", // current line length
"if (currentLength >= 49) return str;", // do nothing
// pad to whatever column you want
"else return `${str.padEnd(49, ' ')}`;", // pad with spaces
"}$$"
],
"restrictFind": "line", // only on lines with a cursor
"postCommands": ["cursorRight"] // just cancels the selection
}
}
It'll work on multiple lines too if each line has a cursor on it

How to format selected code using vscode and Prettier?

I have add Prettier in my VScode but I want to format my code only when I highlight my code,
say
let a = [1, 2, 3, 4]; (line1)
let b = [ 1,2 ,3,4]; (line3)
how can I just format line 1 when I highlight line 1 only and the result should be
let a = [1, 2, 3, 4]; (line1)
let b = [ 1,2 ,3,4]; (line3)
thanks
UPDATE:
I know we can format the code in a code block. But what I want to do is
const test = (a, b, c) => { (line 1)
console.log("show a", a); (line 2)
console.log("show b", b); (line 3)
}
If I highlight b, c in line 1 and format it. It only formats the code in line 1 but not 2 and 3
futher update:
this is my vscode shortcut setting
when I highlight like this,
it becomes like that
I dont know the solution yet, but there are some info that may help.
Basically, there are something wrong with the linter. ( https://github.com/prettier/prettier-vscode/issues/137 )
And your may fix it by checking out this https://prettier.io/docs/en/integrating-with-linters.html ,
I dont know how & didnt try. cuz:: [[
looks complicated (download many things) & mess up with the project structure
may not even work
some info I have no knowledge of / incompatible with my understanding
dont know what will happen to my linters
dont know what is the next step
[]
https://github.com/prettier/prettier-vscode/issues/134
[]
No, the issue is with prettier-eslint not supporting range formatting.
...
I would suggest switching to the recommended approach of integrating ESLint and Prettier
https://github.com/prettier/prettier-vscode/issues/137
[]
let Prettier do the formatting and configure the linter to not deal with formatting rules. You can find instructions on how to configure each linter on the Prettier docs site.
...
For details refer to the Prettier documentation.
https://github.com/prettier/prettier-vscode#linter-integration
[]
Linters usually contain not only code quality rules, but also stylistic rules. Most stylistic rules are unnecessary when using Prettier, but worse – they might conflict with Prettier! Use Prettier for code formatting concerns, and linters for code-quality concerns, as outlined in Prettier vs. Linters.
Luckily it’s easy to turn off rules that conflict or are unnecessary with Prettier, by using these pre-made configs:
eslint-config-prettier
stylelint-config-prettier
https://prettier.io/docs/en/integrating-with-linters.html
[]
I would like to format my code with prettier, then apply all eslint fixes. Previously, this could be achieved by setting prettier.eslintIntegration to true. Now, the extension say that this option is [DEPRECTAED] and prettier-eslint should be used instead. However, it's not clear how to use prettier-eslint in vscode.
https://github.com/prettier/prettier-vscode/issues/999
Actually, "format only selected code" is working on my end, I didnt do any fancy extra config.
What you need to pay attention to is the "syntax tree"
-- ie: dont blindly select across the scope (the bracket {}).
#eg::
given
function test() {
let a = [1, 2, 3, 4];
let b = [ 1,2 ,3,4]; // select only this line
return false
}
if you only select::
let b = [ 1,2 ,3,4];
then press ctrl+k, ctrl+f
everything is fine
if you select across the bracket (the } for function scope)::
let b = [ 1,2 ,3,4]; // select only this line
return false
}
then press ctrl+k, ctrl+f
the whole thing in the bracket (the } for function scope) gets formatted
the "syntax tree" in a class is a bit weird.
-- ie: if you select the WHOLE function AA & format it -- codes inside another function BB will also get formatted...
you may need to apply // prettier-ignore somewhere to prevent formatting
prettier-ignore
A JavaScript comment of // prettier-ignore will exclude the next node in the abstract syntax tree from formatting.
https://prettier.io/docs/en/ignore.html
(note, it seems there is no ending tag for // prettier-ignore for Javascript (at current stage of Prettier))
for the meaning of a "syntax tree", see ex below
if you place it above the code line
seems it applies to the item (the code) (-- which is a "syntax tree node") directly below ((empty lines not counted for)) the // prettier-ignore line
-- eg-below: console.log("show a", a);, and ends there.
if you place it behind the code line (inline)
seems it applies to the inline code only
#for_your_case-do_this:
const test = (a, b, c) => {
// prettier-ignore
console.log("show a", a);
// prettier-ignore
console.log("show b", b);
}
// or
const test = (a, b, c) => {
console.log("show a", a); // prettier-ignore
console.log("show b", b); // prettier-ignore
}
Select the code you want to format and press CTRL + SHIFT + P to open the command pallette. Then type in "format" and select format selected code. Or you can select your code and press right click which should bring up a context menu where you can select the option
Select the code or leave the cursor in the row you want to format and press Ctrl + K Ctrl + F.

Is it possible to have a snippet that considers the length of my input?

I would like to define a snippet for comments like
//************
//* foo A1 *
//************
where I enter foo A1 and it would create a line with (6+ len(${1}) asterisks etc. - is that doable and if so, how?
While I am a big proponent of HyperSnips (see
[VSCODE]: Is there a way to insert N times the same characters,
VS Code: how to make a python snippet that after string or expression hitting tab will transform it and
VSCode Advanced Custom Snippets for how to use it),
it is instructive to see how to do this with just the built-in snippet functionality in vscode. Here is a snippet that does what you want:
"Custom Comment": {
"prefix": ["cc2"], // whatever trigger you want, then tab, write your info and tab again
"body": [
"//***${1/./*/g}***",
"//* $1 *",
"//***${1/./*/g}***"
]
},
That just adds 3 asterisks to the beginning and 3 to the end of your added comment, each character of which is replaced by an asterisk as well.
You can use the extension HyperSnips
snippet comment "Comment" A
``rv = '//' + '*'.repeat(t[0].length + 6)``
//* $1 *
``rv = '//' + '*'.repeat(t[0].length + 6)``
endsnippet

VSCode: Extension: folding section based on first blank line found or to the start of the next similar section

How can I make a VSCode extension folding strategy based on the first blank line following a starting folding marker?
## Some section --|
Any text... | (this should fold)
...more text. --|
(blank line)
## Another section (next fold...)
I've tried lots of regex in the language-configuration.json.
"folding": {
"markers": {
"start": "^##",
"end": "^\\s*$"
} },
If I change things to test with something other than a blank (or whitespace) line as the end delimiter it works. Can't use the next start marker to mark the end of the last or it includes it in the fold (I tried look ahead regex, but I think the regex are applied line by line and the matches can't span lines?)
It's similar to the folding needed for Markdown which VSCode handles well (don't know if that's using a more complex method like https://code.visualstudio.com/api/references/vscode-api#FoldingRangeProvider).
Maybe something in the fixes for [folding] should not fold white space after function has something to do with it.
What I learned: 1. the begin and end regex are applied line by line. 2. tmLanguage start/end regex will work on blank lines, but currently language-configuration folding doesn't seem to work on blank lines.
And since blank lines are in this case a hack for ending at the next begin section:
To solve the problem of folding a section to the next similar section I used the FoldingRangeProvider.
disposable = vscode.languages.registerFoldingRangeProvider('myExt', {
provideFoldingRanges(document, context, token) {
//console.log('folding range invoked'); // comes here on every character edit
let sectionStart = 0, FR = [], re = /^## /; // regex to detect start of region
for (let i = 0; i < document.lineCount; i++) {
if (re.test(document.lineAt(i).text)) {
if (sectionStart > 0) {
FR.push(new vscode.FoldingRange(sectionStart, i - 1, vscode.FoldingRangeKind.Region));
}
sectionStart = i;
}
}
if (sectionStart > 0) { FR.push(new vscode.FoldingRange(sectionStart, document.lineCount - 1, vscode.FoldingRangeKind.Region)); }
return FR;
}
});
Set "editor.foldingStrategy": "auto". You can make it more sophisticated to preserve white space between sections.

How can I adjust indentation of my c source code in the entire selected block all at once?

I'd like to adjust indentation of my source code correctly at a time after I select some block of it.
Is there any function or key with which I can do it including parenthesis?
Here is original selected block of sample code I'd like to adjust indentation.
while(1)
{
func1();
if( )
{
func2();
}
}
if( x == 0 )
{
aa = 1;
}
This would be the correctly indented code how I just want to adjust.
while(1)
{
func1();
if( )
{
func2();
}
}
if( x == 0 )
{
aa = 1;
}
Select your code and press C-M-\, which should be bound to indent-region:
C-M-\
Indent all the lines in the region, as though you had typed TAB at the beginning of each line (indent-region).
If a numeric argument is supplied, indent every line in the region to that column number.
I'm using evil mode because I like vim editing keymap.
In my case, block auto indentation can be done by equal(=) key after selecting a code block.
It's very convenient to rearrange block of code in a c-default-style.
(1) install evil package
(2) Insert this code into you emacs init file.
; indentation style for c, c++, java
(setq c-default-style "linux"
c-basic-offset 4)
(3) select block using v and direction key
(4) press '='