clang-format multiple BasedOnStyle for multiple Language - llvm

In the clang-format documentation, you can set the default options for clang-format by creating a file named .clang-format.
And the syntax provided in the doc is as follows:
---
# We'll use defaults from the LLVM style, but with 4 columns indentation.
BasedOnStyle: LLVM
IndentWidth: 4
---
Language: Cpp
# Force pointers to the type for C++.
DerivePointerAlignment: false
PointerAlignment: Left
---
Language: JavaScript
# Use 100 columns for JS.
ColumnLimit: 100
---
Language: Proto
# Don't format .proto files.
DisableFormat: true
---
Language: CSharp
# Use 100 columns for C#.
ColumnLimit: 100
...
However, when I try applying BasedOnStyle variable to individual Language as below:
Language: C
BasedOnStyle: LLVM
Language: Cpp
BasedOnStyle: LLVM
Language: Java
BasedOnStyle: Google
Language: JavaScript
BasedOnStyle: Google
it does not seem to work.
The question is
Is it possible to use different BasedOnStyle for different languages?
If so, how can I do that?

It seems that the BasedOnStyle only defines styles for Language: Cpp.
This can be shown by the following command:
clang-format -style=llvm -dump-config
The above command outputs styles that succeed Language: Cpp. The same goes for other values of BasedOnStyle.
So if BasedOnStyle is succeeded by Language key and a value other than Cpp, clang-format will fail.
Hence, it is not possible to apply different predefined styles (LLVM, Google, etc.) to different languages.

Related

Is there a better way to set C++ format options in VS Code instead of packing them into one long string?

I am using Clang C++ on macOS in VS Code and I have overridden some C++ formatting options in 'settings.json' file. I am able to set some things from the Settings UI, but for more detailed settings I have added the following entry in 'settings.json':
"C_Cpp.clang_format_fallbackStyle": "{ EmptyLineBeforeAccessModifier: Never, AllowShortCaseLabelsOnASingleLine: true, ConstructorInitializerIndentWidth: 2, ColumnLimit: 120, PointerAlignment: Left, AllowShortIfStatementsOnASingleLine: true, SpaceAfterTemplateKeyword: false, AlignOperands: false, ContinuationIndentWidth: 2 }"
I found descriptions of these settings at Clang Format Style Options
It seems to work properly and my C++ files get nicely reformatted when I hit Alt-F, but I was wondering if there was a nicer way to specify the settings instead of using one long string in settings.json.
For example, it would be nice if I could specify each format setting on a different line or split up the string somehow into multiple lines. I don't think splitting a string into multiple lines can be done in regular JSON files, but perhaps VS code has a way?
I'm not sure if it's relevant, but I have set 'C_Cpp: Clang_format_fallback Style' to 'Google' in the Setting UI.
Any suggestions would be greatly appreciated.
Based on a comment from Frank I tried using .clang-format file and after some messing around I got it to work. I first tried putting .clang-format inside the .vscode directory in my project, but that didn't work. After reading move about clang format I moved the file to my home directory (note the file format for .clang-format is YAML instead of JSON) since it needs to be in the same directory or a parent directory of the file being formatted.
I don't think it was required, but I also ended up running brew install clang-format since I couldn't find it in my path. Once that was installed I ran clang-format -style google -dump-config>~/.clang-format and then made the overrides I wanted.
I was able to remove the long fallback string from settings.json and VS Code is still formatting nicely using my style overrides in my new .clang-format file.

clang-format: Use custom style if file doesn't exist

I want to format code using a custom style if .clang-format doesn't exist. Is there any way to do so?
I used --fallback-style but it fails.
clang-format -i --style=file --fallback-style="{BasedOnStyle: google, IndentWidth: 4, ColumnLimit: 100}" a.cpp
It raises an error:
Invalid fallback style "{BasedOnStyle: google, IndentWidth: 4, ColumnLimit: 100}
I doubt there is a command line option to use another style if .clang_format file doesn't exist.
The option -fallback-style does work only with predefined styles, which are llvm, chromium, mozilla, google, webkit, gnu, microsoft. Also there is none to skip formatiing. You can use -fallback-style=google for example.
However I would suggest other ways. Here is how clang-format finds files:
it checks for .clang-format and _clang-format files in all directories from the one which contains a file you want to format, then the parent of this directory, then the parent of this, and so on to the root directory. So there are two options:
Manually check if configuration file for clang-format exists.
Put your custom fallback style in root or home directory, so that clang-format finds your file in case it can't find it in a project

Format If-else on Different Line in C++ VSCode

I'm using the C++ Extension for VSCode (Visual Studio Code).
This format's my code when I save my C++ file. But the format results in if-statement and curly braces on same lines rather than on the new line.(I have already set format Curly Braces on Same Line)
C++ VSCode Formatted
if(...){
//...
}else if(...)
//...
}else{
//...
}
What I Want C++ VSCode Formatted Code to Look Like
if(...){
//...
}
else if(...){
//...
}
else{
//...
}
How can I make If-else in C++ format on the differernt line in Visual Studio Code?
You need to have C/C++ extension(just check if you have it). Original
1st idea
Go File-> Preferences -> Settings
Search for C_Cpp.clang_format_fallbackStyle
Click Edit, Copy to Settings
Change from "Visual Studio" to "{ BasedOnStyle: Google, IndentWidth: 4 }"
(Change from "Visual Studio" to "LLVM", "Google" or "WebKit")
Something like this:
"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}"
Also check documentation: here and another one
2nd idea
Install C# FixFormat extension
View > Extension
Search "C# FixFormat"
Install
Shift + Alt + F
If it complains about multiple formatters, then press the Configure button and select C# FixFormat.
It is possible to go back to having open braces on a new line by going to File > Preferences > Settings. Then scroll down to Extensions, C# FixFormat configuration and uncheck Style > Braces: On Same Line
The VS Code extension uses a program called clang-format to format your code. You can change how clang-format behaves by placing a .clang-format file in your project root and double-checking that the default style is 'file' in VS Code's settings. The setting is C_Cpp: Clang_format_style.
Here is a minimal .clang-format that gets as close to your desired output as clang-format allows.
BreakBeforeBraces: Stroustrup
IndentWidth: 4
SpaceBeforeParens: Never
It cannot remove the space before the opening brace, but I'm personally on clang-format's side on that decision. You will naturally want to peruse the documentation, https://clang.llvm.org/docs/ClangFormatStyleOptions.html, to see all the options available to you.

Clang-format not using .clang-format file ubuntu (no errors)

I have a .clang-format in my project directory that houses my .cpp files and my build directory. From my terminal I cd into my project folder and run clang-format -style=file -i *.cpp. Here's my .clang-format file.
Language: Cpp
ColumnLimit: 0
BreakBeforeBraces: GNU
BreakConstructorInitializers: AfterColon
Cpp11BracedListStyle: true
IndentCaseLabels: true
NamespaceIndentation: All
IndentWidth: 4
TabWidth: 4
UseTab: Never
DerivePointerAlignment: false
PointerAlignment: Left
IncludeBlocks: Regroup
I'm testing the functionality by changing BreakBeforeBraces and nothing changes. It seems to be using a fallback formatting. What's going on? Is there a way to see what clang-format is actually doing?
When using -style=file, clang-format for each input file will try to find the .clang-format file located in the closest parent directory of the input file. When the standard input is used, the search is started from the current directory.
You can use the command below to see the actual config used in the running directory
clang-format -style=file -dump-config

Google c style settings for gnu indent?

I am using google c indent style for Emacs (google-c-style.el) and Vim(google.vim).
But since I have some existing code that is not this style and I hope I can change it. I find there is a tool called GNU indent that can do such thing automatically and it provides some common style settings on this page, however there is no for Google c indent style. SO is there equivalent for it as well?
(I tried the Linux and Berkley style and feel that they are by no means satisfactory for me)
For the record, there is an alternate solution for those who are interested in Clang and LLVM.
clang-format definitely can help format existing source code easily and efficiently. It has explicit builtin support for 5 format, namely LLVM(default), Google, Chromium, Mozilla, WebKit.
The simples way to format a file with Google style is:
clang-format -style=Google -i filename
Where -i means inplace modification, you may try without this option to preview the changes.
To batch format existing C/C++ code we can simply use the command like:
find . -name "*.cc" | xargs clang-format -style=Google -i
Apart from the listed 5 formats, there are actually other styles like GNU(added on revision 197138; it's a pity that the document is not synced).
Note that clang-format accepts rc like files named .clang-format or _clang-format in a project, the simplest way to add such a configuration file(as said in clang-format's official tutorial page) is to dump the configuration of an existing format like:
clang-format -style=Google -dump-config >.clang-format
Also you might also use BasedOnStyle option so a configuration file might look like:
---
BasedOnStyle: Chromium
PointerBindsToType: false
ObjCSpaceAfterProperty: true
...
Use .clang-format or _clang-format as keywords to search on Github and there are other samples; or you might refer to this site to help build one.
There are also integrations for IDEs/Editors such as Visual Studio(in directory clang-format-vs), Sublime, Emacs, Vim(all in directory clang-format).
Another 3 tips:
For Emacs integration(clang-format.el), personally I think it's better to bind key for clang-format-buffer rather than clang-format-region.
For Mac OSX homebrew installation, use brew install --with-clang, --with-lld, --with-python --HEAD llvm can get clang-format support and its integration files are in $(brew --cache)/llvm--clang--svn-HEAD/tools/clang-format(bonus: there is even a git-clang-format there!!).
There are other fabulous tools inside clang-extra-tools such as clang-modernize(which is used to "automatically convert C++ code written against old standards to use features of the newest C++ standard where appropriate"), really worthy of having a try!
A brief reading of the google coding style shows that it is mostly K&R coding style, except with 2 space indentation (including case statements), 80 column lines, and no tabs. So, the following options should accomplish that:
-kr -ci2 -cli2 -i2 -l80 -nut
Start with that. You may have to tweak the resulting code. C++ support, in particular, is weak for indent.
Legend:
-kr: K&R style
-ci2: Continuation indent, the lines following the first line of a multi-line code statement get indented by 2 spaces
-cli2: Case label indent, case labels are indented 2 spaces in from the switch
-i2: Indentation, 2 spaces
-l80: Length, 80 columns
-nut: No tabs
As an alternative, you may consider executing emacs in batch mode to apply indentation on your code for you. Briefly:
Create a file called emacs-format-file with the contents:
(defun emacs-format-function ()
"Format the whole buffer."
(c-set-style "Google")
(indent-region (point-min) (point-max) nil)
(untabify (point-min) (point-max))
(save-buffer))
Execute the following command from the shell:
emacs -batch your_source_file.c \
-l emacs-format-file -f emacs-format-function