Convert a Regular C styled coding file to GNU style coding standards - c

I have a file which I have written in "Regular C style". for example
void foo()
{
if(;;) {
....
} else {
...
}
}
wanted to change this style to GNU style coding using vim or some other plugin
void foo()
{
if(;;)
{
....
}
else
{
....
}
}
Wanted to ask if there can be a quick shortcut to do it so that it detects the loops starting braces and brings it below and indents it by 2 spaces.
Any help is greatly appreciated !

The correct tool for that job is GNU indent, which was created exactly for the purpose of re-indenting existing C code. In particular, you might want to look at the option --gnu-style.

Just a quick answer, probably not the best: you can insert the line breaks, select the whole document and re-indent with:
:1,$s/\v(\S) *\{/\1^M{/g
:1,$s/\v\} *(\S)/}^M\1/g
:1
VG=
Of course, this depends on your vim configuration (the = command, for instance, depends on your definition of equalprg). Moreover, this treats the comments like normal code.

Related

Astyle Incorrectly Formatting Linux Style Braces

According to the Linux kernel coding style, if only one branch of a conditional statement
is a single statement, then braces should be used in both branches. For example:
if (condition) {
do_this();
do_that();
} else {
otherwise();
}
This can be found in Section 3 of the official Linux kernel coding style document.
Astyle's latest release 3.0.1 incorrectly formats conditionals like this. For example, Astyle leaves the following untouched:
if (condition) {
do_this();
do_that();
} else
otherwise();
Is there a known fix for this in Astyle? If not, are current development efforts underway? If not, could someone point me in the right direction to get this fix integrated into the tool.
Astyle option "--style=1tbs" could be used to fix that.

CLion Macro Rearrangement

I use a library called e4c in a C project, which allows try...catch syntax in C. However, CLion rearrange function always messes the indentation.
Is there any way to tell CLion to rearrange code before macro substitution?
edit:
For example, when the following code is rearranged:
try {
} catch (RuntimeException) {
}
It gives:
try {
} catch (RuntimeException) {
}
Because the try catch expand to 2 ifs and a while loop.
It seems that try and catch are macros, so you can find that the formatting is correct after the macros substitution.
You can mention your case in CLion tracker

Format of structs using emacs c code auto-newline

I have recently started using emacs for editing C source, and have been using the auto-newline feature of cc-mode (c-toggle-auto-newline). This works well for constructs like functions and if/else statements, but seems to act strangely when a closing brace should be followed by a semi-colon.
Using auto-newline in GNU Emacs 23.3 I get:
struct foo
{
int x;
}
;
char int[2] =
{
0, 1
}
;
I would like to instead get:
struct foo {
int x;
};
char int[2] = { 0, 1 };
How can I get the closing semi-colon to remain on the same line as the closing brace?
I don't think you can go around this problem with auto newline on. It's not a greatly thought-through feature, it simply inserts newlines after certain characters (;, {, etc.). But seriously, how hard is it to press and enter key? Any automation is always error-prone.
You can customize the "cleanup" behavior when auto-newline is turned on. This is controlled by the contents of the c-cleanup-list variable. (View help for this within Emacs by entering C-h v c-cleanup-list.
Specifically, adding defun-close-semi to c-cleanup-list will solve your problem.
If you're already defining a custom style within your ~/.emacs file, then you can probably figure out how to do this. Otherwise, the easiest way to change this setting is via Customize. In the help buffer (displayed when you ran C-h v c-cleanup-list), the last line will have a link to customize this variable.

CppUTest not working

I am trying to rewrite some legacy C code and would like to have some tests in place before actually starting the rewrite. FOr this I took a look at CppUTest and tried a sample application consisting of a header file chrtostr.h, an implementation file chrtostr.c and a test file called test_chrtostr.c which contents is listed bellow:
#include <CppUTest/CommandLineTestRunner.h>
#include "chrtostr.h"
TEST_GROUP(chrtostr)
{
}
TEST(chrtostr, test_chrtostr)
{
CHECK_EQUAL(chrtostr('n'), "sfsdfds");
}
int main(int ac, char **av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}
And the corresponding Makefile.am:
AUTOMAKE_OPTIONS = foreign
CPPUTEST_HOME = ./cpputest
CFLAGS = -g -Wall -I$(CPPUTEST_HOME)/include
LDFLAGS = -L$(CPPUTEST_HOME)/lib -lCppUTest
bin_PROGRAMS = chrtostr test_chrtostr
chrtostr_SOURCES = chrtostr.c chrtostr.h main.c
test_chrtostr_SOURCES = test_chrtostr.c
The issue is that each time I try to run make I get the following traceback which doesn't actually help me too much: http://pastebin.com/BK9ts3vk
You should probably start by getting one of the demos going. You could see how CppUTest is intended to be used with C. My book, Test-Driven Development for Embedded C, will help you get started too. The first few chapters use a C-Only test harness. Later examples use CppUTest (I'm one of the authors of CppUTest). I also describe the advantages of a C++ test harness for C.
James
p.s. - for more information on CppUTest, look at CppUTest.org
That test driver is written in C++. You'll need to compile that as C++, so rename your file to .cpp and make sure g++ is called to drive the compile/link (rather than gcc).
Unfortunately, the "HelloWorld" example in CppUTest is undocumented and while the Appendix in "Test Driven Development for Embedded C" lists only 11 condition checks, I am finding that there are a lot more undocumented helper functions (all pretty much undocumented). I wouldn't recommend CppuTest unless you are trying to understand the concepts of TDD.
I would look for more of a commercial product or you are going to pick up a lot of bad TDD habits or get really frustrated and just move on.
I was just looking at this again. There were a few problems with your code. C++ errors don't always help clear them up.
I added comment before the things i fixed.
#include "CppUTest/TestHarness.h"
//The test file is c++. YOu have to tell it when you are linking to C code
extern "C"
{
#include "chrtostr.h"
}
//A test group needs to have a ';' after it. Under the hood, this macro
//create a base class for the test cases of the same name
TEST_GROUP(Chrtostr)
{
};
//CHECK_EQUAL uses ==. STRCMP_EQUAL actually compares c-strings
TEST(Chrtostr, wrong)
{
STRCMP_EQUAL(chrtostr('n'), "sfsdfds");
}

How can I autoformat/indent C code in vim?

When I copy code from another file, the formatting is messed up, like this:
fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}
How can I autoformat this code in vim?
Try the following keystrokes:
gg=G
Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.
I like to use the program Artistic Style. According to their website:
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2) to if ( x<2 ) if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.
In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:
autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb
so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.
The options I have for astyle, -T4pb, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.
Here's a demo. Before astyle:
int main(){if(x<2){x=3;}}
float test()
{
if(x<2)
x=3;
}
After astyle (gggqG):
int main()
{
if (x < 2)
{
x = 3;
}
}
float test()
{
if (x < 2)
x = 3;
}
The builtin command for properly indenting the code has already been mentioned (gg=G). If you want to beautify the code, you'll need to use an external application like indent. Since % denotes the current file in ex mode, you can use it like this:
:!indent %
I find that clang-format works well.
There are some example keybindings in the clang documentation
I prefer to use the equalprg binding in vim. This allows you to invoke clang-format with G=gg or other = indent options.
Just put the following in your .vimrc file:
autocmd FileType c,cpp setlocal equalprg=clang-format
The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/vim-autoformat/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.
I like indent as mentioned above, but most often I want to format only a small section of the file that I'm working on. Since indent can take code from stdin, its really simple:
Select the block of code you want to format with V or the like.
Format by typing :!indent.
astyle takes stdin too, so you can use the same trick there.
I wanted to add, that in order to prevent it from being messed up in the first place you can type :set paste before pasting. After pasting, you can type :set nopaste for things like js-beautify and indenting to work again.
Maybe you can try the followings
$indent -kr -i8 *.c
Hope it's useful for you!
Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.
For a good overview and demo of many of the options mentioned here, #Gavin-Freeborn has a great video on YouTube:
https://www.youtube.com/watch?v=tM_uIwSucPU
It covers some Vim plugins as well as built-in capabilities such as =, gq, and formatprg.

Resources