Giter Site home page Giter Site logo

rhysd / vim-clang-format Goto Github PK

View Code? Open in Web Editor NEW
1.1K 28.0 117.0 221 KB

Vim plugin for clang-format, a formatter for C, C++, Obj-C, Java, JavaScript, and so on.

Home Page: http://clang.llvm.org/docs/ClangFormat.html

Ruby 2.55% Shell 0.32% C++ 2.72% JavaScript 0.22% Vim Script 94.20%
vim clang clang-format vim-plugin formatter

vim-clang-format's Introduction

Format your C family code

CI

This plugin formats your code with specific coding style using clang-format.

Automatic formatting is provided for the following languages by default:

  • C
  • C++
  • Objective-C
  • JavaScript
  • Java
  • TypeScript
  • Protobuf
  • Cuda
  • Vala

Screenshot

Screenshot

Requirements

  • clang-format command (3.4 or later), which is bundled in Clang extra tools
  • vim-operator-user(highly recommended)
  • vimproc.vim(recommended in Windows)

Installation

Copy plugin, doc and autoload directories into your ~/.vim or use :packadd in Vim8. Or please use your favorite plugin manager to install this plugin. I recommend latter.

Usage

:ClangFormat command is available. If you use it in normal mode, the whole code will be formatted. If you use it in visual mode, the selected code will be formatted. It is more convenient to map :ClangFormat to your favorite key mapping in normal mode and visual mode.

If you install vim-operator-user in advance, you can also map <Plug>(operator-clang-format) to your favorite key bind.

:ClangFormatAutoToggle command toggles the auto formatting on buffer write. :ClangFormatAutoEnable command enables the auto formatting on buffer write. Useful for automatically enabling the auto format through a vimrc. :ClangFormatAutoDisable turns it off.

What is the difference from clang-format.py?

clang-format.py is Python script to use clang-format from Vim, which is installed with clang-format. The usage is here. Against clang-format.py, vim-clang-format has below advantages.

  • Style options are highly customizable in .vimrc. clang-format.py requires .clang-format file to customize a style.
  • vim-clang-format provides an operator mapping.
  • vim-clang-format doesn't need python interface.

In short, vim-clang-format has better Vim integration than clang-format.py.

Customization

You can customize formatting using some variables.

  • g:clang_format#code_style

g:clang_format#code_style is a base style. llvm, google, chromium, mozilla is supported. The default value is google.

  • g:clang_format#style_options

Coding style options as dictionary.

An example is below:

let g:clang_format#style_options = {
            \ "AccessModifierOffset" : -4,
            \ "AllowShortIfStatementsOnASingleLine" : "true",
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "Standard" : "C++11",
            \ "BreakBeforeBraces" : "Stroustrup"}

For config information, execute clang-format -dump-config command.

  • g:clang_format#command

Name of clang-format. If the name of command is not clang-format or you want to specify a command by absolute path, set this variable. Default value is clang-format.

  • g:clang_format#extra_args

You can specify more extra options in g:clang_format#extra_args as String or List of String.

  • g:clang_format#detect_style_file

When this variable's value is 1, vim-clang-format automatically detects the style file like .clang-format or _clang-format and applies the style to formatting.

  • g:clang_format#auto_format

When the value is 1, a current buffer is automatically formatted on saving the buffer. Formatting is executed on BufWritePre event.

  • g:clang_format#auto_format_on_insert_leave

When the value is 1, inserted lines are automatically formatted on leaving insert mode. Formatting is executed on InsertLeave event.

  • g:clang_format#auto_formatexpr

When the value is 1, formatexpr option is set by vim-clang-format automatically in C, C++ and ObjC codes. Vim's format mappings (e.g. gq) get to use clang-format to format. This option is not comptabile with Vim's textwidth feature. You must set textwidth to 0 when the formatexpr is set.

  • g:clang_format#auto_filetypes

List of file types to which g:clang_format#auto_format, g:clang_format#auto_format_on_insert_leave, and g:clang_format#auto_formatexpr should be applied. The default value is ["c", "cpp", "objc", "java", "javascript", "typescript", "proto", "arduino"].

  • g:clang_format#enable_fallback_style

When the value is 0, -fallback-style=none option is added on executing clang-format command. It means that vim-clang-format does nothing when .clang-format is not found. The default value is 1.

Vimrc Example

let g:clang_format#style_options = {
            \ "AccessModifierOffset" : -4,
            \ "AllowShortIfStatementsOnASingleLine" : "true",
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "Standard" : "C++11"}

" map to <Leader>cf in C++ code
autocmd FileType c,cpp,objc nnoremap <buffer><Leader>cf :<C-u>ClangFormat<CR>
autocmd FileType c,cpp,objc vnoremap <buffer><Leader>cf :ClangFormat<CR>
" if you install vim-operator-user
autocmd FileType c,cpp,objc map <buffer><Leader>x <Plug>(operator-clang-format)
" Toggle auto formatting:
nmap <Leader>C :ClangFormatAutoToggle<CR>

Auto-enabling auto-formatting

autocmd FileType c ClangFormatAutoEnable

For More Information

$ clang-format -help
$ clang-format -dump-config

clang-format's documentation and API documentation is useful in some cases. In particular, the following link is useful to know the information of a key and its value of a style setting. CLANG-FORMAT STYLE OPTIONS

License

The MIT License (MIT)

Copyright (c) 2013-2021 rhysd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

vim-clang-format's People

Contributors

0xc0ffee avatar bbchung avatar beyondmarc avatar calebegg avatar dryvnt avatar enderwillsaveus avatar expipiplus1 avatar hia3 avatar jakalope avatar jreybert avatar kinote avatar mhaehnel avatar mkrawiec avatar peplin avatar pl-energid avatar randrej avatar rhysd avatar sean-der avatar shaac avatar wilhelmtell avatar xy24 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vim-clang-format's Issues

Support Javascript

Running ClangFormat currently results in a reformatted file with the following message on top of it:

Can't find usable .clang-format, using LLVM style
Configuration file(s) do(es) not support C++: /home/richy/Projects/architrave/ArchAssets/.clang-format

Would it be possible to just enable Javascrip files as well?

problem with g:clang_format#auto_formatexpr

I have the following in my init.vim:

let g:clang_format#command = '/usr/local/Cellar/llvm/3.8.1/bin/clang-format'
let g:clang_format#code_style = "llvm"
let g:clang_format#auto_formatexpr = 1

and I am using:
NVIM v0.1.5-405-g00fc216
Build type: Release

I do not have the vim-operator-user plugin installed.

When using gql or Vgq (in a .cpp file) the inbuilt formatter is used.
:set formatexpr? gives formatexpr=

If I use :setl formatexpr=clang_format#replace(v:lnum,v:lnum+v:count-1) then the gq commands work as expected.
I am not sure how to call clang_format#is_invalid(), but running call clang_format#is_invalid() gives no response.

Inconsistent behavior from binary clang-format tool when formating multiline function arguments (exceeding column limit)

clang-format version 3.8
my only setting in .vimrc is let g:clang_format#command = "/usr/local/opt/llvm/bin/clang-format"

Test file belowing:

void func(long long arg, ...) {
}

void func2(char *s, ...) {
}

int main(int argc, char *argv[]) {
  func(1, 489237987483294792, 238942983, 3294873294, 5, 45435435, 652, 92340,
                       545, 324, 489237987483294793);
  // arguments not aligned
  func2("very_long_arg_1", "very_long_arg_2", "very_long_arg_3",
"very_very_long_arg1", "very_very_long_arg2");
  return 0;
}

clang-format tool generated:

CC@/tmp $ /usr/local/opt/llvm/bin/clang-format -style=google test.c
void func(long long arg, ...) {}

void func2(char *s, ...) {}

int main(int argc, char *argv[]) {
  func(1, 489237987483294792, 238942983, 3294873294, 5, 45435435, 652, 92340,
       545, 324, 489237987483294793);

  func2("very_long_arg_1", "very_long_arg_2", "very_long_arg_3",
        "very_very_long_arg1", "very_very_long_arg2");  // here the arguments is aligned
  return 0;
}

vim-clang-format generated (using Google style, same with vim-clang-format's):

void func(long long arg, ...) {
} // short function not in one line

void func2(char *s, ...) {
}

int main(int argc, char *argv[]) {
  func(1, 489237987483294792, 238942983, 3294873294, 5, 45435435, 652, 92340,
       545, 324, 489237987483294793);

  func2("very_long_arg_1", "very_long_arg_2", "very_long_arg_3",
    "very_very_long_arg1", "very_very_long_arg2"); // not aligned
  return 0;
}

So, here are the problems:
Why vim-clang-format's behavior is different from what clang-format binary tool does?
(same when you generating a .clang-format file in the project directory.)

By the way, could you please make vim-clang-format detect a "global" .clang-format config file, for instance in $HOME directory.

Error on Windows

I've been using this plugin on linux happily for months, thanks. However I'm sometimes required to do development on Windows at work.

I have clang-format on my path but am getting the following error message in Windows gvim 7.4.

screenshot from 2014-10-27 16 52 44

I tried installing Shougo/vimproc.vim as advised in the documentation but got the same error.

Any idea what would be causing this issue?

Last commits screwed up input

Since the last bunch of commits the system has become unstable on clangformat 3.4 3.5 on linux. I had to revert to an earlier commit 009df09 to get a working system again. Hope this helps

There is no indentation in "{}" in "if {} else{}"

What's wrong with my .vimrc?

let g:clang_format#style_options = { 
            \ "Standard" : "C++11",
            \ "IndentWidth" : 4,
            \ "AccessModifierOffset" : -2,
            \ "ColumnLimit" : 0 }

Output of clang-format from command-line

#include <iostream>

using std::cout;
using std::cin;
using std::cerr;
using std::endl;

int main() {
  int i = 1, j = 2;
  if (i < j) {
    i = 2;
  } else {
    j = 3;
  }
  return 0;
}

Output from ClangFormat in vim

#include <iostream>

using std::cout;
using std::cin;
using std::cerr;
using std::endl;

int main() {
    int i = 1, j = 2;
    if (i < j) {
    i = 2;
    } else {
    j = 3;
    }   
    return 0;
}

clang-format 3.4 doesn't seem to work

I'm getting the following error message when I try to run :ClangFormat using clang-format-3.4

:ClangFormat
ClangFormat                   ClangFormatEchoFormattedCode
Error detected while processing function clang_format#replace..<SNR>118_error_message:
line    1:
clang-format has failed to format.

Load the clang configuration from a file

Instead of writing the clang-format configuration in our vim config directly, could it be possible to load it from a clang-format config file. Sometimes we also want to run clang-format from the command line (using a config file then). Currently, if we want to modify the style options, we have to modify it in both places.

project local clang-format

hello again. I have a project local clang format file, and some formatting options set in my vimrc like indentation size. It seems to me, that my global vimrc config overrides, what is defined in my project local .clang-format config file. Shouldn't this be the other way round. The project settings should be more important to my project and language independent vimrc configurations.

EDIT: the problem that I have at the moment is, that on the command line clang-format and within vim the result is different, and I don't know why.

Is it possible to allow one line empty structs formatting?

I would like to be able to automatically format the following code

template <typename Cond, typename... Conds>
struct and_<Cond, Conds...>
    : std::conditional<Cond::value, and_<Conds...>, std::false_type>::type
{
};

into this:

template <typename Cond, typename... Conds>
struct and_<Cond, Conds...>
    : std::conditional<Cond::value, and_<Conds...>, std::false_type>::type {};

regardless of my class settings brace wrapping config or anything else.

As I can see a lot of options like AllowShortBlocksOnASingleLine, AllowShortFunctionsOnASingleLine or AllowShortIfStatementsOnASingleLine I would love to see something like AllowShortClassDefinitionsOnASingleLine (or similarly named).

Is there are already such possibility in vim-clang-format ( or clang-format itself) ?

Cursor position not preserved in multiple windows

With auto_format, if I have the same file open in multiple windows and I write the file...

  • In the active window, the cursor is preserved, and the window centers on the cursor.
  • In all other windows, the cursor jumps to the beginning of the file.

This is very annoying if you have many windows open at different places in a large file and you save the file, and you forgot to disable vim-clang-format 😬

Not sure how difficult it would be to implement cursor persistence for all buffers?

.clang_format style file not used

I have a costume .clang-format file in my home directory. When I run vim-clang-format in gVim, it formats the code without my costume settings, although I set
let g:clang_format#detect_style_file = 1

in my vimrc. Does the plugin conflict with other plugins? What could be the problem?

How to specify BraceWrapping when BreakBeforeBraces is set to Custom?

I am having issues trying to specify BraceWrapping with BreakBeforeBraces is set to Custom.

I have tried the following config:

let g:clang_format#style_options = { 
            \ "AccessModifierOffset" : -2, 
            \ "BreakBeforeBraces" : "Custom",
            \ "BraceWrapping" : [ 
            \ { "AfterControlStatement" : "true"},
            \ { "AfterClass " : "true"}
            \ ],                                                                                                                                                                                       
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "UseTab" : "Never",
            \ "Standard" : "C++11",
            \ "ColumnLimit" : 100,
            \ "BinPackParameters" : "false",
            \ "AllowShortBlocksOnASingleLine" : "true",
            \ "AllowShortIfStatementsOnASingleLine" : "true",
            \ "AllowShortLoopsOnASingleLine " : "true",
            \ "AllowShortFunctionsOnASingleLine" : "All",
            \ "AlignConsecutiveAssignments " : "true"
            \ }

but I get the following error inside vim:

Error detected while processing function clang_format#replace[10]..clang_format#format[3]..<SNR>109_make_style_options[1]..<SNR>109_build_extra_options:
line    9:
E730: using List as a String
clang-format -version
clang-format version 3.8.0-2ubuntu1 (tags/RELEASE_380/final)

Cursor jumps to top of file during formatting

When I run :ClangFormat the cursor jumps to top of the file and then jumps back down to where it was before. In this process the current visible buffer gets adjusted because the jump back puts the cursor in the middle of the visible area.

Is it possible to avoid this jump at all?

format of source code removes all marks

ClangFormat of the entire source code removes all marks.

steps to reproduce in normal mode:

:ClangFormat                   //format to make sure the next call does nothing
mm                             //set the mark m
:marks                         //you see the mark m now
:ClangFormat                   //does nothing now
:marks                         //now the mark is gone

実行に失敗する

MacVim Kaoriyaで実行するとエラーになってしまいました。
clangは公式サイトのビルド済みを使用しました。

.vimrcでの設定は
let g:clang_format#command = '/Users/BaB/Downloads/clang/bin/clang-format'

augroup clang-format-setting
    autocmd!
    autocmd FileType c,cpp map <buffer><Leader>x <Plug>(operator-clang-format)
augroup END

です。

整形しようとしたコードは
https://github.com/YoshihiroIto/vim-icondrag/blob/master/internal/icondrag/Core.cpp
です。

コード全体や関数1つをビジュアル選択して実行しました。

how to install it?

Hi, I have installed clang-format 3.6 and vimproc.vim, but I still have no idea with how to install it to my vim, I am using Ubuntu 14.04?

@rhysd No one dare to write one more sentence on how to install?

AlwaysBreakTemplateDeclarations does more than documented

Documentation states If true, always break after the template<...> of a template declaration.

So, I expect to see, for example, the following result:

template <class T>
inline constexpr T sqr(const T& x) { return x * x; }

However, clang-format produces this even with AllowShortFunctionsOnASingleLine and AllowShortBlocksOnASingleLine set to true:

template <class T>
inline constexpr T sqr(const T& x) {
    return x * x;
}

There should be a way to achieve the code in the first sample.

clang-format fails to format

New user of the plugin here.

Somehow the plugin fails to format the code. Tried to trace down the problem but couldn't find it. The following errors occur in the respective scenarios:

  • When a file is formatted automatically on buffer write
    clang-format-buffer-write

  • When a piece of code is selected in visual mode and :ClangFormat is manually executed
    clang-format-visual

The used software stack is:

  • gvim
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Nov 24 2016 16:44:48)
Included patches: 1-1689
Extra patches: 8.0.0056
  • clang-format-4.0 (installed from the official LLVM packages, hence the problem is not a duplicate of #7);
    Moreover, clang-format is symlinked to clang-format-4.0 so clang_format#command is correctly configured.
  • Ubuntu 16.04

It doesn't matter what kind of source file is selected for formatting, it's always failing.
When directly executing clang-format from the shell, everything works just fine.
I am loading the formatting options from a .clang-format configuration file:

BasedOnStyle: LLVM
IndentWidth: 2
ColumnLimit: 0
---
Language: Cpp
Standard: Cpp11
DerivePointerAlignment: false
AlignConsecutiveAssignments: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AlignEscapedNewlinesLeft: true

FixNamespaceComments: true
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 1
SpaceBeforeAssignmentOperators: true
SpacesBeforeTrailingComments: 3
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SortIncludes: false

Hence these are the only custom settings in my .vimrc:

let g:clang_format#auto_format=1 " enable autoformatting on buffer write
let g:clang_format#detect_style_file=1 " detect and load .clang-format file automatically
let g:clang_format#auto_format_on_insert_leave=1

:ClangFormat always folds code when run

Is there a way to run the formatter without triggering automatic code folding? Presumably this happens because I have vim setup to fold code when opening a C++ file and :ClangFormat reopens the file after it has done its thing. It would be great if vim-clang-format had some way to disable this so as to avoid having to drill down through a bunch of folds.

Why does my clang-format defaults to LLVM instead of Google format

I placed autoload, doc and plugin in the .vim folder. Then in .vimrc I do autocmd FileType cpp ClangFormatAutoEnable.

Then I do clang-format -dump-config. It says #BasedOnStyle: LLVM.

The problem: I was excepting the default to be google. But it turns out to be llvm. Then I also did
let g:clang_format#code_style = "google" .. this also did not helped.

I was trying to make google format but it is always defaulting to llvm.

Error when formatting empty file

I am getting an error when executing ClangFormat in Vim on an empty file.

Error detected while processing function clang_format#replace..clang_format#format..<SNR>30_system: 
line    8: 
E677: Error writing temp file

I get this error when the target buffer has exactly one empty line, and when the buffer has exactly two empty lines. I do not get the error when the buffer has three or more empty lines, nor when the buffer has at least one non-empty line.

Here's an example file that causes the error:

foo.hpp



This file does not cause the error:

bar.hpp




Also, when I run ClangFormat on a file with multiple blank lines, each format will remove one of those lines. So 4 blank lines goes to 3 blank lines, 3 blank lines goes to 2 blank lines, 2 blank lines results in an error.

clang-format on the target file from the shell works correctly, and preserves the correct number of blank lines.

$ clang-format --version
LLVM (http://llvm.org/):
  LLVM version 3.4.2
  Optimized build.
  Built Dec  7 2015 (09:37:36).
  Default target: x86_64-redhat-linux-gnu
  Host CPU: corei7-avx


$ clang-format -dump-config
---
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
ColumnLimit:     0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
DerivePointerBinding: false
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 60
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerBindsToType: true
SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: false
Standard:        Cpp03
IndentWidth:     4
TabWidth:        8
UseTab:          Never
BreakBeforeBraces: Linux
IndentFunctionDeclarationAfterType: false
SpacesInParentheses: false
SpacesInAngles:  false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
...


$ vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Dec 21 2016 17:00:20)
Included patches: 1-160
Modified by <[email protected]>
Compiled by <[email protected]>
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +syntax
+arabic          +file_in_path    +mouse_sgr       +tag_binary
+autocmd         +find_in_path    -mouse_sysmouse  +tag_old_static
-balloon_eval    +float           +mouse_urxvt     -tag_any_white
-browse          +folding         +mouse_xterm     -tcl
++builtin_terms  -footer          +multi_byte      +terminfo
+byte_offset     +fork()          +multi_lang      +termresponse
+cindent         +gettext         -mzscheme        +textobjects
-clientserver    -hangul_input    +netbeans_intg   +title
-clipboard       +iconv           +path_extra      -toolbar
+cmdline_compl   +insert_expand   +perl            +user_commands
+cmdline_hist    +jumplist        +persistent_undo +vertsplit
+cmdline_info    +keymap          +postscript      +virtualedit
+comments        +langmap         +printer         +visual
+conceal         +libcall         +profile         +visualextra
+cryptv          +linebreak       +python/dyn      +viminfo
+cscope          +lispindent      -python3         +vreplace
+cursorbind      +listcmds        +quickfix        +wildignore
+cursorshape     +localmap        +reltime         +wildmenu
+dialog_con      -lua             +rightleft       +windows
+diff            +menu            +ruby/dyn        +writebackup
+digraphs        +mksession       +scrollbind      -X11
-dnd             +modify_fname    +signs           -xfontset
-ebcdic          +mouse           +smartindent     -xim
+emacs_tags      -mouseshape      -sniff           -xsmp
+eval            +mouse_dec       +startuptime     -xterm_clipboard
+ex_extra        +mouse_gpm       +statusline      -xterm_save
+extra_search    -mouse_jsbterm   -sun_workshop    -xpm
   system vimrc file: "/etc/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/etc"
 f-b for $VIMRUNTIME: "/usr/share/vim/vim74"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H     -O2 -g -pipe -Wall -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches   -m64 -mtune=generic -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1      
Linking: gcc   -L. -Wl,-z,relro -fstack-protector -rdynamic -Wl,-export-dynamic -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE  -Wl,-z,relro  -L/usr/local/lib -Wl,--as-needed -o vim        -lm -lnsl  -lselinux  -lncurses -lacl -lattr -lgpm -ldl   -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE  -fstack-protector  -L/usr/lib64/perl5/CORE -lperl -lresolv -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc    

indent is not correct

clang-format version 4.0.0 (tags/google/testing/2016-08-03)

vim config:

"linux kernel coding stype
set tabstop=8  "number of spaces a <Tab> in the text stands for
set shiftwidth=8 "number of spaces used for each step of (auto)indent
set softtabstop=8  "if non-zero, number of spaces to insert for a <Tab>
set noexpandtab
set nosmarttab "a <Tab> in an indent inserts 'shiftwidth' spaces
set textwidth=80
" linux kernel coding style
let g:clang_format#code_style='llvm'
let g:clang_format#style_options = {
            \ 'IndentWidth' : '8',
            \ 'UseTab' : 'Always',
            \ 'BreakBeforeBraces' : 'Linux',
            \ 'AllowShortIfStatementsOnASingleLine': 'false',
	    \ 'AllowShortBlocksOnASingleLine': 'false',
	    \ 'AllowShortCaseLabelsOnASingleLine': 'false',
	    \ 'AllowShortFunctionsOnASingleLine': 'None',
	    \ 'AllowShortLoopsOnASingleLine': 'false',
            \ 'IndentCaseLabels' : 'false'}

original c code:

struct test_t var = {
        .a=2,
        .c=3,
};

after clang-format:

struct test_t var = {
    .a = 2, .c = 3,
};

As showing above, when using this type of structure initialize, the indent is not correct after clang-format.

Unexpected behavior in split panes

It works weirdly when I use :sp to edit two different positions on the same file simultaneously and call :ClangFormat in one pane. The current pane is correctly indented and displayed; however, the other pane always scrolls down to the bottom of the file.

Is there a way to make the other pane stay still?

Error in ubuntu

It works on mac, but doesn't work on ubuntu... vim's version is 7.4
here is the output of :12verbose ClangFormat

calling function clang_format#replace
calling function clang_format#replace[2]..<SNR>15_verify_command
calling function clang_format#replace[2]..<SNR>15_verify_command[1]..clang_format#is_invalid
function clang_format#replace[2]..<SNR>15_verify_command[1]..clang_format#is_invalid returning #0
continuing in function clang_format#replace[2]..<SNR>15_verify_command
function clang_format#replace[2]..<SNR>15_verify_command returning #0
continuing in function clang_format#replace
calling function clang_format#replace[13]..clang_format#format
calling function clang_format#replace[13]..clang_format#format[2]..<SNR>15_detect_style_file
function clang_format#replace[13]..clang_format#format[2]..<SNR>15_detect_style_file returning #1
continuing in function clang_format#replace[13]..clang_format#format
calling function clang_format#replace[13]..clang_format#format[13]..<SNR>15_shellescape
function clang_format#replace[13]..clang_format#format[13]..<SNR>15_shellescape returning '''10567.cpp'''
continuing in function clang_format#replace[13]..clang_format#format
calling function clang_format#replace[13]..clang_format#format[16]..<SNR>15_shellescape
function clang_format#replace[13]..clang_format#format[16]..<SNR>15_shellescape returning '''/usr/bin/clang-format'''
continuing in function clang_format#replace[13]..clang_format#format
calling function clang_format#replace[13]..clang_format#format[18]..<SNR>15_system
calling function clang_format#replace[13]..clang_format#format[18]..<SNR>15_system[8]..<SNR>15_has_vimproc
function clang_format#replace[13]..clang_format#format[18]..<SNR>15_system[8]..<SNR>15_has_vimproc returning #0
continuing in function clang_format#replace[13]..clang_format#format[18]..<SNR>15_system
Calling shell to execute: "('/usr/bin/clang-format'  -lines=1:83 -style=file -assume-filename='10567.cpp'  --) < /tmp/vH87AQr/9 >/tmp/v
H87AQr/10 2>&1"

function clang_format#replace[13]..clang_format#format[18]..<SNR>15_system returning 'YAML:47:27: error: unknown key ''Spl...("Not matc
hed");^@  }^@^@  return 0;^@}'
continuing in function clang_format#replace[13]..clang_format#format
function clang_format#replace[13]..clang_format#format returning 'YAML:47:27: error: unknown key ''Spl...("Not matched");^@  }^@^@  ret
urn 0;^@}'
continuing in function clang_format#replace
calling function clang_format#replace[14]..<SNR>15_success
calling function clang_format#replace[14]..<SNR>15_success[1]..<SNR>15_has_vimproc
function clang_format#replace[14]..<SNR>15_success[1]..<SNR>15_has_vimproc returning #0
continuing in function clang_format#replace[14]..<SNR>15_success
function clang_format#replace[14]..<SNR>15_success returning #0
continuing in function clang_format#replace
calling function clang_format#replace[18]..<SNR>15_error_message
function clang_format#replace[18]..<SNR>15_error_message aborted
continuing in function clang_format#replace
calling function clang_format#replace[31]..<SNR>15_restore_screen_pos
function clang_format#replace[31]..<SNR>15_restore_screen_pos returning #0
continuing in function clang_format#replace
Error detected while processing function clang_format#replace[18]..<SNR>15_error_message:
line    1:
clang-format has failed to format.
function clang_format#replace aborted

Cannot find clang-format when using with vimproc on Windows

When I use vim-clang-format with vimproc.vim on Windows, the following message shows up.

[vimproc] vimproc#get_command_name: File "^clang-format^" is not found.
[vimproc] vimproc#get_command_name: File "^clang-format^" is not found.
Error detected while processing function clang_format#replace[16]..<SNR>143_error_message:
line    1:
clang-format has failed to format.
E474: Invalid argument

This function escapes clang-format as ^"clang-format^", and vimproc cannot correctly handle shell escape for Windows.
But do we really need to escape clang-format as ^"clang-format^"? I tried just "clang-format", and it seems no problem.
Should we replace it with this?

function! s:shellescape(str) abort
    if s:on_windows && (&shell =~? 'cmd\.exe')
        return '"' . substitute(substitute(substitute(a:str,
                    \ '[&|<>()^"%]', '^\0', 'g'),
                    \ '\\\+\ze"', '\=repeat(submatch(0), 2)', 'g'),
                    \ '\^"', '\\\0', 'g') . '"'
    endif
    return shellescape(a:str)
endfunction

Undo after formatting region reverts the previous change

Let's say you add something to a line, then you select the line and call ClangFormat command to format it, but then you decide to revert the formatting, so you press u for undo. However, that also reverts what you added to that line before invoking ClangFormat, which isn't what you might expect.

That behaviour matches the one described in the documentation for undojoin command:

:undoj[oin] Join further changes with the previous undo block.
Warning: Use with care, it may prevent the user from
properly undoing changes. Don't use this after undo
or redo.

The proposed fix is just to not use undojoin in autoload/clang_format.vim:200.

How to configure nested flags?

Let's say I would like to configure BraceWrapping which as of documentation (http://clang.llvm.org/docs/ClangFormatStyleOptions.html) says is of type BraceWrappingFlags.

This setting will be taken into consideration when BreakBeforeBraces is set to BS_Custom.

I know how to use one-dimensional (as below) simple format but I have tried already several options how to use this nested style and I frankly do not know how to do that.

My exemplar format settings:

let g:clang_format#style_options = { 
            \ "AccessModifierOffset" : -2, 
            \ "AlignTrailingComments" : "true",
            \ "AlignAfterOpenBracket" : "true",
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "AllowShortFunctionsOnASingleLine" : "Inline",
            \ "BreakBeforeBraces" : "Allman",
            \ "BinPackParameters" : "false",
            \ "Standard" : "C++11",                                                                                                                                                                                                            
            \ "ColumnLimit" : 100,
            \ "UseTab" : "Never" }

Indexing error on version checking function

On Ubuntu I had to change:

return matchlist(split(s:system(g:clang_format#command.' --version 2>&1'), "\n")[1], '\(\d\+\)\.\(\d\+\)')[1:2]

to

return matchlist(split(s:system(g:clang_format#command.' --version 2>&1'), "\n")[0], '\(\d\+\)\.\(\d\+\)')[1:2]

to avoid several errors the first time I call :ClangFormat. Maybe an improved version check mechanism is needed.

整形時のスクロール位置、カーソル位置が移動してしまう

https://github-camo.global.ssl.fastly.net/d7c327d3895f3a3bc1c0859117a5538db89b0c20/687474703a2f2f6769667a6f2e6e65742f42497465474a39566173672e676966
これを見てると、整形前と整形後でスクロール位置は変更ないのですが、
自分の環境では整形時にスクロール位置が移動してしまいます。

また整形を行いアンドゥを行うと、カーソル位置がバッファ先頭に移動してしまいます。

Buffer local auto format

The auto format option is global,

g:clang_format#auto_format

but it makes sense to be able to have different settings per buffer as you e.g. don't want to auto-format some one elses code in one buffer but want it on my code in another. I've tried to change "g" to "b" but it vim complains that the varname is illegal. Is it possible to make this a per-buffer setting additionally to having the global setting?

clang-format

when format the following code
vector<vector<keypointslist > >keys1;
it changes to 
vector<vector<keypointslist >> keys1;

and compile it will cause an error.

:ClangFormat forces me to presse ENTER to continue

Whether it's on the current line using :ClangFormat or when I use 'let g:clang_format#auto_format = 1', I get this message and can't continue without hitting enter.

129 fewer lines
"src/foo.cc" 130L, 4040C written
Press ENTER or type command to continue

clang-format not detecting my settings

I am on debian 8 using gnome-terminal

I followed the instructions to install vim-clang-format through Vundle.

After installing clang format from debian repo and testing it on the command line it works there. When I attempt to do :ClangFormat in vim I get this error:

cf error

my vim folder structure looks like this
cf error

I am not sure what's going, can you offer some assistance.

Insert mode broken when using auto_formatexpr with textwidth

If you have these options set:

let g:clang_format#auto_formatexpr=1
set textwidth=80

where the textwidth is anything except 0, then insert mode is really messed up.

I found this thread which mentions:

formatexpr is called on every keystroke in Insert mode

that is, unless you don't set a textwidth. I tried clearing formatoption so none of the automatic wrapping at the textwidth was enabled, but it had no effect.

Something about passing it to the ClangFormat function, however, really messes with insert mode - some keys have no effect (you have to type them twice) and there's some weird highlighting going on.

Folding issues

The second problem I am having is related to folding. Every time I run ClangFormat it refolds my document, which is somewhat disrupting to my workflow. Once more, I have included a gif to illustrate my point

folding

I have the same minimal installation as in #53.

I am using vim version 7.4.2367, compiled from source.

Other than that I really love the plugin, and am looking forward to being able to use it for my projects ❤️

Formatting is slow

Hi,
I tested your plugin but I noticed that it is significantly slower than executing the python script. Would you happen to know why ?
How could I help ?

This was my configuration:

" Clang format
let g:clang_format#style_options = {
    \ "AccessModifierOffset": -4,
    \ "AlignEscapedNewlinesLeft": "false",
    \ "AlignTrailingComments": "true",
    \ "AllowAllParametersOfDeclarationOnNextLine": "true",
    \ "AllowShortFunctionsOnASingleLine": "false",
    \ "AllowShortIfStatementsOnASingleLine": "false",
    \ "AllowShortLoopsOnASingleLine": "false",
    \ "AlwaysBreakBeforeMultilineStrings": "false",
    \ "AlwaysBreakTemplateDeclarations": "true",
    \ "BinPackParameters": "false",
    \ "BreakBeforeBinaryOperators": "false",
    \ "BreakBeforeBraces": "Allman",
    \ "BreakConstructorInitializersBeforeComma": "true",
    \ "ColumnLimit":     80,
    \ "ConstructorInitializerAllOnOneLineOrOnePerLine": "false",
    \ "ConstructorInitializerIndentWidth": 0,
    \ "Cpp11BracedListStyle": "true",
    \ "DerivePointerBinding": "true",
    \ "ExperimentalAutoDetectBinPacking": "false",
    \ "IndentCaseLabels": "false",
    \ "IndentFunctionDeclarationAfterType": "false",
    \ "IndentWidth":     4,
    \ "MaxEmptyLinesToKeep": 1,
    \ "NamespaceIndentation": "None",
    \ "ObjCSpaceBeforeProtocolList": "true",
    \ "PenaltyBreakComment": 60,
    \ "PenaltyBreakFirstLessLess": 100,
    \ "PenaltyBreakString": 1000,
    \ "PenaltyExcessCharacter": 8,
    \ "PenaltyReturnTypeOnItsOwnLine": 99,
    \ "PointerBindsToType": "true",
    \ "SpaceAfterControlStatementKeyword": "true",
    \ "SpaceBeforeAssignmentOperators": "true",
    \ "SpaceInEmptyParentheses": "false",
    \ "SpacesBeforeTrailingComments": 1,
    \ "SpacesInCStyleCastParentheses": "false",
    \ "SpacesInParentheses": "false",
    \ "Standard":        "Cpp11",
    \ "TabWidth":        4,
    \ "UseTab":          "Never"}

let g:clang_format#detect_style_file=1

autocmd FileType c,cpp,objc map <buffer><C-f> <Plug>(operator-clang-format)
autocmd FileType c,cpp,objc imap <buffer><C-f><ESC><Plug>(operator-clang-format)<CR>i

(on a side note, the imap was not working, if you know why I would love to ear the reason.)

Thanks for your work !

Catch error when not using vim-operator-user

I noticed a small error when using vim-clang-format without the plugin vim-operator-user.

I get this when launching vim :

line    6:
E117: Unknown function: operator#user#define
Press ENTER or type command to continue

But if I change the catch line to :

catch /^Vim\%((\a\+)\)\=:E117/

Then it works as expected

.clang-format file is not detected

I have a .clang-format file in the root directory of my source code. I assumed that vim-clang-format would work like clang-format and search upwards in the directory tree. It still formats in llvm default style:
This is in my .vimrc:
let g:clang_format#command = "clang-format-3.5"
let g:clang_format#detect_style_file = 1

structure is like that:
~/project/include/foo/bar.h
~/project/.clang_format

current working directory with vim: ~/build/

I opened the header file and reformated a section of the code. Looked like llvm-style. Doing it with clang-format-3.5 directly gave me a different result.

Cursor position not maintained after undo

To replicate:

  1. shift+v to visually select a line
  2. ,cf to run clang format (cursor is in correct position)
  3. u to undo (cursor is now at top of file)

Is there a way to have the cursor remain in the original position after the undo?

clang-format version 3.4

Removing first line if folded

Not sure if this project is actively developed anymore, but I have two bugs (will add the second one in a separate issue).

For some reason the first line of my file is removed when I run ClangFormat both in normal mode and in visual mode if the line is folded. I have included a gif for clarity

header

I have tested this with a minimal vim configuration, this is my vimrc

set nocompatible
 
call plug#begin('~/.vim/plugged')

Plug 'rhysd/vim-clang-format'

call plug#end()

set tabstop=2
set expandtab
set shiftwidth=2

set foldmethod=syntax

"vim-clang-format
"{{{
let g:clang_format#code_style = "google"
let g:clang_format#style_options = {
            \ "BreakBeforeBraces" : "Stroustrup",
            \ "Standard" : "C++11"}
"}}}

nnoremap <buffer><Leader>cf :<C-u>ClangFormat<CR>
vnoremap <buffer><Leader>cf :ClangFormat<CR>

and my .vim folder has the Plug files + your plugin

clang-format is not found

Hi, I have installed clang-format:

Ubuntu clang-format version 3.5-1ubuntu1 (trunk) (based on LLVM 3.5)

and vim-clang-format plugin:
a26c71a194770b8c31adaed33870106c

When I try to execute :ClangFormat in Vim i get this error
cd0e6ed0b58cd89dea80573625c2e452

How can I fix it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.