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

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 '='

Related

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 to stop VS Code forcing me to use braces, otherwise the cursor position goes crazy (PHP, or apply it globally)

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",

C line wrap indentation rules in emacs

I am currently working on a C project with other people where they have decided that the indent style for wrapped lines is to indent 8 spaces, instead of where the opening parenthesis/bracket is, e.g.
if (long cond 1 &&
long cond 2 &&
long cond 3) {
//do stuff
}
instead of
if (long cond 1 &&
long cond 2 &&
long cond 3) {
//do stuff
}
However, emacs defaults to the latter and I don't know how to change it to behave like the former. Anyone know how to do this?
Put this in your .emacs:
(c-set-offset 'arglist-cont-nonempty 8)

How do I get word-based movements in emacs go-mode to not skip over backquoted strings?

If I have code like so:
func main() {
a := `line 1
line 2
line 3
line 4`
fmt.Println(a)
}
doing forward-word or backword-word when the cursor is
in the multi-line string moves to the end or the start
of the string respectively. I'm using go-mode.el v1.3.1
from https://github.com/dominikh/go-mode.el
Similar if the cursor is inside the string and you do
I tried doing
(modify-syntax-entry ?` ".")
in the go-mode-hook but that didn't change the behavior.

When to use "{ }" in C? [K&R Exercise 1.8]

I tried to solve this problem, which is to count the amount of lines, blank spaces, and tabs.
My solution was incorrect because I don't know how to use { }.
main ()
{
int newline;
int tab;
int blank;
int c;
newline = 0;
tab = 0;
blank = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++newline;
if (c == '\t')
++tab;
if (c == 32)
++blank;
printf("lines: %d tabs: %d blanks: %d\n", newline, tab, blank);
}
In my code, only new lines were being counted. Tabs and spaces were never counted.
I know the answer is to add { } around the if statements section. But I only know this because I searched google for the solution.
Perhaps it is just me, but K&R do not really explain when I should use { }.
Can someone explain how I can know to add { } to my above code?
When I read the code, it seems fine without {}. It means I truly don't understand its usage. Why aren't tabs and spaces counted in the above code?
Is there another book on C that you can recommend?
I have no programming experience.
The syntax of a simple if is : if (<condition>) <statement>. The <statement> can be a single statement (as you have in your code) or it can be a block (zero or more statements enclosed in braces). When you have a single statement, it is strictly a question of style whether you surround it with braces—the behavior is the same.
One relatively straightforward "rule of thumb": Look for the semi-colon(s). Referring to your example, starting at the "while", read forward until you see a semi-colon. If you want anything beyond that semi-colon to be executed as part of your while block, you need to wrap it all in curly braces.
Another way to look at it: The semi-colon is a statement terminator. It terminated blank = 0 as your previous statement; it terminates not only the if but also the enclosing while statement. Thus, to execute the following if as part of the while block, you need to enclose the ifs in curly braces.
Oh, and by the way, C and similar languages do not attach syntactic meaning to whitespace. It is at most treated as a separator. Any indentation you choose to apply is for the benefit of the human reader only; it has no significance to the compiler.
Any if/while/for can be followed by a single statement without braces, or any number of statements encapsulated in braces. If you write an if/while/for followed by many statements and no braces, only the first statement falls under the if/while/for. Note that whatever whitespace you use does not matter, it is only for readability.
This is the equivalent of your code if it was written with braces:
while ((c = getchar()) != EOF)
{
if (c == '\n')
{
++newline;
}
}
if (c == '\t')
{
++tab;
}
if (c == 32)
{
++blank;
}
What you want:
while ((c = getchar()) != EOF)
{
if (c == '\n')
{
++newline;
}
if (c == '\t')
{
++tab;
}
if (c == 32)
{
++blank;
}
}
which is equivalent to
while ((c = getchar()) != EOF)
{
if (c == '\n')
++newline;
if (c == '\t')
++tab;
if (c == 32)
++blank;
}
Exclusion of braces serves absolutely no purpose but style. If you are ever in doubt, include the braces.
Braces ({ and }) are used to convert zero or more statements into a single compound statement. Anywhere you wish for a group of statments to be treated as a single statement you should use braces.
For example, a while loop executes a single statement whilst it evaluates to true:
while(some-condition)
statement
Obvious there will be times when you want to execute multiple statements, and this is where you surround them with { and } in order to turn them into a single compound statement.