Giter Site home page Giter Site logo

vim-autoformat's Introduction

vim-autoformat

Format code with one button press (or automatically on save).

This plugin makes use of external formatting programs to achieve the most decent results. Check the list of formatprograms below to see which languages are supported by default. Most formatprograms will obey vim settings, such as textwidth and shiftwidth(). You can easily customize existing formatprogram definitions or add your own formatprogram. When no formatprogram exists (or no formatprogram is installed) for a certain filetype, vim-autoformat falls back by default to indenting, (using vim's auto indent functionality), retabbing and removing trailing whitespace.

Requirement

vim-autoformat requires vim to have python support (python 2 or python 3). You can check your vim has python support by running :echo has("python3") and :echo has("python2").

Neovim

Neovim does not come with python support by default, and additional setup is required.

First install pynvim

python3 -m pip install pynvim

And add the following configuration in your .vimrc

let g:python3_host_prog="/path/to/python/executable/"

How to install

Vundle

Put this in your .vimrc.

Plugin 'vim-autoformat/vim-autoformat'

Then restart vim and run :PluginInstall. Alternatively, you could run :source $MYVIMRC to reload your .vimrc without restarting vim. To update the plugin to the latest version, you can run :PluginUpdate.

Pathogen

Download the source and extract in your bundle directory. Updating has to be done manually, as far as I'm aware.

Other

It is highly recommended to use a plugin manager such as Vundle, since this makes it easy to update plugins or uninstall them. It also keeps your .vim directory clean. Still you can decide to download this repository as a zip file or whatever and extract it to your .vim folder.

How to use

First you should install an external program that can format code of the programming language you are using. This can either be one of the programs that are listed below as defaultprograms, or a custom program. For defaultprograms, vim-autoformat knows for which filetypes it can be used. For using a custom formatprogram, read the text below How can I change the behaviour of formatters, or add one myself? If the formatprogram you want to use is installed in one of the following ways, vim automatically detects it:

  • It suffices to make the formatprogram globally available, which is the case if you install it via your package manager.
  • Alternatively you can point vim-autoformat to folders containing formatters, by putting the absolute paths to these folders in g:formatterpath in your .vimrc, like:
let g:formatterpath = ['/some/path/to/a/folder', '/home/superman/formatters']

Remember that when no formatprograms exists for a certain filetype, vim-autoformat falls back by default to indenting, retabbing and removing trailing whitespace. This will fix at least the most basic things, according to vim's indentfile for that filetype.

When you have installed the formatter you need, you can format the entire buffer with the command :Autoformat. You can provide the command with a file type such as :Autoformat json, otherwise the buffer's filetype will be used.

Some formatters allow you to format only a part of the file, for instance clang-format and autopep8. To use this, provide a range to the :Autoformat command, for instance by visually selecting a part of your file, and then executing :Autoformat. For convenience it is recommended that you assign a key for this, like so:

noremap <F3> :Autoformat<CR>

Or to have your code be formatted upon saving your file, you could use something like this:

au BufWrite * :Autoformat

You can also format the current line only (without having to make a visual selection) by executing :AutoformatLine.

To disable the fallback to vim's indent file, retabbing and removing trailing whitespace, set the following variables to 0.

let g:autoformat_autoindent = 0
let g:autoformat_retab = 0
let g:autoformat_remove_trailing_spaces = 0

To disable or re-enable these option for specific buffers, use the buffer local variants: b:autoformat_autoindent, b:autoformat_retab and b:autoformat_remove_trailing_spaces. So to disable autoindent for filetypes that have incompetent indent files, use

autocmd FileType vim,tex let b:autoformat_autoindent=0

You can manually autoindent, retab or remove trailing whitespace with the following respective commands.

gg=G
:retab
:RemoveTrailingSpaces

For each filetype, vim-autoformat has a list of applicable formatters. If you have multiple formatters installed that are supported for some filetype, vim-autoformat tries all formatters in this list of applicable formatters, until one succeeds. You can set this list manually in your vimrc (see section How can I change the behaviour of formatters, or add one myself?, or change the formatter with the highest priority by the commands :NextFormatter and :PreviousFormatter. To print the currently selected formatter use :CurrentFormatter. These latter commands are mostly useful for debugging purposes. If you have a composite filetype with dots (like django.python or php.wordpress), vim-autoformat first tries to detect and use formatters for the exact original filetype, and then tries the same for all supertypes occurring from left to right in the original filetype separated by dots (.).

Using multiple formatters for the same file

It is possible to apply multiple formatters for single file, for example, html can use special formatters for js/css etc. Support can be enabled via the g:run_all_formatters_<identifier> option.

In this case, formatters from g:formatdef_<identifier> will be applied to the file one by one. Fallback (vim) formatting isn't used if at least one formatter has finished sucessfully.

Sample config:

let g:formatters_vue = ['eslint_local', 'stylelint']
let g:run_all_formatters_vue = 1

Default formatprograms

Here is a list of formatprograms that are supported by default, and thus will be detected and used by vim when they are installed properly. They are defined in https://github.com/Chiel92/vim-autoformat/blob/master/plugin/defaults.vim. They are simply tried in the order they are listed until one succeeds.

  • asmfmt for Assembly. An assembly formatter. Can be installed with go get -u github.com/klauspost/asmfmt/cmd/asmfmt. See https://github.com/klauspost/asmfmt for more info.

  • astyle for C#, C++, C and Java. Download it here: http://astyle.sourceforge.net/. Important: version 2.0.5 or higher is required, since only those versions correctly support piping and are stable enough.

  • autopep8 for Python (supports formatting ranges). It's probably in your distro's repository, so you can download it as a regular package. For Ubuntu type sudo apt-get install python-autopep8 in a terminal. Here is the link to the repository: https://github.com/hhatto/autopep8. And here the link to its page on the python website: http://pypi.python.org/pypi/autopep8/0.5.2.

  • black for Python. Most users can install with the terminal command sudo pip install black or pip install --user black. Here is the link to the repository: https://github.com/ambv/black

  • buildifier for bazel build files. (https://github.com/bazelbuild/buildtools/tree/master/buildifier)

  • clang-format for C, C++, Objective-C, Protobuf (supports formatting ranges). Clang-format is a product of LLVM source builds. If you brew install llvm, clang-format can be found in /usr/local/Cellar/llvm/bin/. Vim-autoformat checks whether there exists a .clang-format or a _clang-format file up in the current directory's ancestry. Based on that it either uses that file or tries to match vim options as much as possible. Details: http://clang.llvm.org/docs/ClangFormat.html.

  • cmake-format for CMake. Install cmake_format with pip. See https://github.com/cheshirekow/cmake_format for more info.

  • css-beautify for CSS. It is shipped with js-beautify, which can be installed by running npm install -g js-beautify. Note that nodejs is needed for this to work. Here is the link to the repository: https://github.com/einars/js-beautify.

  • dartfmt for Dart. Part of the Dart SDK (make sure it is on your PATH). See https://www.dartlang.org/tools/dartfmt/ for more info.

  • dfmt for D. It can be built or downloaded from https://github.com/dlang-community/dfmt. Arch Linux users can install it from the community repository with pacman -S dfmt. If dfmt is not found in PATH, Vim-autoformat will try to use dub run dfmt command to automatically download and run dfmt.

  • dhall format for Dhall. The standard formatter, bundled with the interpreter. See https://github.com/dhall-lang/dhall-lang for more info.

  • ESlint for Javascript. http://eslint.org/ It can be installed by running npm install eslint for a local project or by running npm install -g eslint for global use. The linter is then installed locally at $YOUR_PROJECT/node_modules/.bin/eslint or globally at ~/.npm-global/bin/eslint. When running the formatter, vim will walk up from the current file to search for such local installation and a ESLint configuration file (either .eslintrc.js or eslintrc.json). When the local version is missing it will fallback to the global version in your home directory. When both requirements are found eslint is executed with the --fix argument. Note that the formatter's name is still eslint_local for legacy reasons even though it already supports global eslint. Currently only working on *nix like OS (Linux, MacOS etc.) as it requires the OS to provide sh like shell syntax.

  • fish_indent for Fish-shell. Fish shell builtin fish_indent formatter for fish shell script.

  • fixjson for JSON. It is a JSON file fixer/formatter for humans using (relaxed) JSON5. It fixes various failures while humans writing JSON and formats JSON codes. It can be installed with npm install -g fixjson. More info is available at https://github.com/rhysd/fixjson.

  • fprettify for modern Fortran. Download from official repository. Install with ./setup.py install or ./setup.py install --user.

  • gnatpp for Ada. http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gnat_ugn_unw/The-GNAT-Pretty_002dPrinter-gnatpp.html

  • gofmt for Golang. The default golang formatting program is shipped with the golang distribution. Make sure gofmt is in your PATH (if golang is installed properly, it should be). Here is the link to the installation: https://golang.org/doc/install An alternative formatter is gofumpt, which enforces a stricter format than gofmt. To enable gofumpt support, you should install it by running go install mvdan.cc/gofumpt latest, and then change the default golang formatter by configuring let g:formatters_go = ['gofumpt'].

  • haxe-formatter for Haxe. haxe-formatter is a thin wrapper around the haxelib formatter library. It can be installed by running haxelib install formatter. Here is the link to the repository: https://github.com/HaxeCheckstyle/haxe-formatter

  • html-beautify for HTML. It is shipped with js-beautify, which can be installed by running npm install -g js-beautify. Note that nodejs is needed for this to work. Here is the link to the repository: https://github.com/einars/js-beautify.

  • js-beautify for Javascript and JSON. It can be installed by running npm install -g js-beautify. Note that nodejs is needed for this to work. The python version version is also supported by default, which does not need nodejs to run. Here is the link to the repository: https://github.com/einars/js-beautify.

  • JSCS for Javascript. https://jscs-dev.github.io/

  • JuliaFormatter.jl for Julia. It can be installed by running julia -e 'import Pkg; Pkg.add("JuliaFormatter")'. You will need to install Julia and have the julia binary in your PATH. See https://github.com/domluna/JuliaFormatter.jl for more information on how to configure JuliaFormatter.jl. Note that since vim-autoformat works by running a subprocess, a new instance of Julia is instantiated every time it is invoked. And since Julia needs to precompile the code to run format_text, this may block the vim instance while the subprocess is running. Once Julia finishes executing, control will be handled back to the user and the formatted text will replaces the current buffer. You can consider precompiling JuliaFormatter.jl to make this process faster (See PackageCompiler.jl for more information on that), or consider using a dedicated JuliaFormatter.vim plugin that works asynchronously.

  • latexindent.pl for LaTeX. Installation instructions at https://github.com/cmhughes/latexindent.pl. On mac you can install it with brew install latexindent, then you have to add let g:formatdef_latexindent = '"latexindent -"' to .vimrc.

  • luafmt for Lua. Install luafmt with npm. See https://github.com/trixnz/lua-fmt for more info.

  • stylua for Lua. Install stylua with cargo. See https://github.com/JohnnyMorganz/StyLua for more info.

  • mix format for Elixir. mix format is included with Elixir 1.6+.

  • nginxfmt.py for NGINX. See https://github.com/slomkowski/nginx-config-formatter for more info.

  • nixfmt for Nix. It can be installed from nixpkgs with nix-env -iA nixpkgs.nixfmt. See https://github.com/serokell/nixfmt for more.

  • ocamlformat for OCaml. OCamlFormat can be installed with opam: opam install ocamlformat. Details: https://github.com/ocaml-ppx/ocamlformat. We also provide ocp-indent as reserve formatter.

  • packer fmt for Packer. The standard formatter included with Packer. See https://www.packer.io/docs/commands/fmt for more info.

  • perltidy for Perl. It can be installed from CPAN cpanm Perl::Tidy . See https://metacpan.org/pod/Perl::Tidy and http://perltidy.sourceforge.net/ for more info.

  • purty for Purescript It can be installed using npm install purty. Further instructions available at https://gitlab.com/joneshf/purty

  • rbeautify for Ruby. It is shipped with ruby-beautify, which can be installed by running gem install ruby-beautify. Note that compatible ruby-beautify-0.94.0 or higher version. Here is the link to the repository: https://github.com/erniebrodeur/ruby-beautify. This beautifier developed and tested with ruby 2.0+, so you can have weird results with earlier ruby versions.

  • remark for Markdown. A Javascript based markdown processor that can be installed with npm install -g remark-cli. More info is available at https://github.com/wooorm/remark.

  • rubocop for Ruby. It can be installed by running gem install rubocop. Here is the link to the repository: https://github.com/bbatsov/rubocop

  • rustfmt for Rust. It can be installed using cargo, the Rust package manager. Up-to-date installation instructions are on the project page: https://github.com/rust-lang/rustfmt#quick-start.

  • sass-convert for SCSS. It is shipped with sass, a CSS preprocessor written in Ruby, which can be installed by running gem install sass. Here is the link to the SASS homepage: http://sass-lang.com/.

  • shfmt for Shell. A shell formatter written in Go supporting POSIX Shell, Bash and mksh that can be installed with go get -u mvdan.cc/sh/cmd/shfmt. See https://github.com/mvdan/sh for more info.

  • sqlformat for SQL. Install sqlparse with pip.

  • standard for Javascript. It can be installed by running npm install -g standard (nodejs is required). No more configuration needed. More information about the style guide can be found here: http://standardjs.com/.

  • stylelint for CSS. https://stylelint.io/ It can be installed by running npm install stylelint stylelint-config-standard for a local project or by running npm install -g stylelint stylelint-config-standard for global use. The linter is then installed locally at $YOUR_PROJECT/node_modules/.bin/stylelint or globally at ~/.npm-global/bin/stylelint. When running the formatter, vim will walk up from the current file to search for such local installation. When the local version is missing it will fallback to the global version in your home directory. When both requirements are found styelint is executed with the --fix argument. Currently only working on *nix like OS (Linux, MacOS etc.) as it requires the OS to provide sh like shell syntax.

  • stylish-haskell for Haskell It can be installed using cabal build tool. Installation instructions are available at https://github.com/jaspervdj/stylish-haskell#installation

  • terraform fmt for Terraform. The standard formatter included with Terraform. See https://www.terraform.io/docs/cli/commands/fmt.html for more info.

  • tidy for HTML, XHTML and XML. It's probably in your distro's repository, so you can download it as a regular package. For Ubuntu type sudo apt-get install tidy in a terminal.

  • typescript-formatter for Typescript. typescript-formatter is a thin wrapper around the TypeScript compiler services. It can be installed by running npm install -g typescript-formatter. Note that nodejs is needed for this to work. Here is the link to the repository: https://github.com/vvakame/typescript-formatter.

  • xo for Javascript. It can be installed by running npm install -g xo (nodejs is required). Here is the link to the repository: https://github.com/sindresorhus/xo.

  • yapf for Python (supports formatting ranges). Vim-autoformat checks whether there exists a .style.yapf or a setup.cfg file up in the current directory's ancestry. Based on that it either uses that file or tries to match vim options as much as possible. Most users can install with the terminal command sudo pip install yapf or pip install --user yapf. YAPF has one optional configuration variable to control the formatter style. For example:

    let g:formatter_yapf_style = 'pep8'

    pep8 is the default value, or you can choose: google, facebook, chromium. Here is the link to the repository: https://github.com/google/yapf

  • zigformat for Zig. It is an unofficial binary. You can find the installation instructions from the repo: zigformat

Help, the formatter doesn't work as expected!

If you're struggling with getting a formatter to work, it may help to set vim-autoformat in verbose-mode. Vim-autoformat will then output errors on formatters that failed. The value of g:autoformat_verbosemode could set as 0, 1 or 2. which means: 0: no message output. 1: only error message output. 2: all message output.

let g:autoformat_verbosemode=1
" OR:
let verbose=1

To read all messages in a vim session type :messages. Since one cannot always easily copy the contents of messages (e.g. for posting it in an issue), vim-autoformats command :PutMessages may help. It puts the messages in the current buffer, allowing you to do whatever you want.

Reporting bugs

Please report bugs by creating an issue in this repository. When there are problems with getting a certain formatter to work, provide the output of verbose mode in the issue.

How can I change the behaviour of formatters, or add one myself?

If you need a formatter that is not among the defaults, or if you are not satisfied with the default formatting behaviour that is provided by vim-autoformat, you can define it yourself. The formatprogram must read the unformatted code from the standard input, and write the formatted code to the standard output.

Basic definitions

The formatprograms that available for a certain <filetype> are defined in g:formatters_<filetype>. This is a list containing string identifiers, which point to corresponding formatter definitions. The formatter definitions themselves are defined in g:formatdef_<identifier> as a string expression. Defining any of these variable manually in your .vimrc, will override the default value, if existing. For example, a complete definition in your .vimrc for C# files could look like this:

let g:formatdef_my_custom_cs = '"astyle --mode=cs --style=ansi -pcHs4"'
let g:formatters_cs = ['my_custom_cs']

In this example, my_custom_cs is the identifier for our formatter definition. The first line defines how to call the external formatter, while the second line tells vim-autoformat that this is the only formatter that we want to use for C# files. Please note the double quotes in g:formatdef_my_custom_cs. This allows you to define the arguments dynamically:

let g:formatdef_my_custom_cs = '"astyle --mode=cs --style=ansi -pcHs".&shiftwidth'
let g:formatters_cs = ['my_custom_cs']

Please notice that g:formatdef_my_custom_cs contains an expression that can be evaluated, as required. As you see, this allows us to dynamically define some parameters. In this example, the indent width that astyle will use, depends on the buffer local value of &shiftwidth, instead of being fixed at 4. So if you're editing a csharp file and change the shiftwidth (even at runtime), the g:formatdef_my_custom_cs will change correspondingly.

For the default formatprogram definitions, the options expandtab, shiftwidth and textwidth are taken into account whenever possible. This means that the formatting style will match your current vim settings as much as possible. You can have look look at the exact default definitions for more examples. They are defined in vim-autoformat/plugin/defaults.vim. As a small side note, in the actual defaults the function shiftwidth() is used instead of the property. This is because it falls back to the value of tabstop if shiftwidth is 0.

If you have a composite filetype with dots (like django.python or php.wordpress), vim-autoformat internally replaces the dots with underscores so you can specify formatters through g:formatters_django_python and so on.

To override these options for a local buffer, use the buffer local variants: b:formatters_<filetype> and b:formatdef_<identifier>. This can be useful, for example, when working with different projects with conflicting formatting rules, with each project having settings in its own vimrc or exrc file:

let b:formatdef_custom_c='"astyle --mode=c --suffix=none --options=/home/user/special_project/astylerc"'
let b:formatters_c = ['custom_c']

Ranged definitions

If your format program supports formatting specific ranges, you can provide a format definition which allows to make use of this. The first and last line of the current range can be retrieved by the variables a:firstline and a:lastline. They default to the first and last line of your file, if no range was explicitly specified. So, a ranged definition could look like this.

let g:formatdef_autopep8 = "'autopep8 - --range '.a:firstline.' '.a:lastline"
let g:formatters_python = ['autopep8']

This would allow the user to select a part of the file and execute :Autoformat, which would then only format the selected part.

Contributing

This project is community driven. I don't actively do development on vim-autoformat myself, as its current state fulfills my personal needs. However, I will review pull requests and keep an eye on the general sanity of the code.

If you have any improvements on this plugin or on this readme, if you have some formatter definition that can be added to the defaults, or if you experience problems, please open a pull request or an issue in this repository.

Major Change Log

October 2018

  • We also take the returncode of the formatter process into account, not just the presence of output on stderr.

March 2016

  • We don't use the option formatprg internally anymore, to always have the possible of using the default gq command.
  • More fallback options have been added.

June 2015

  • Backward incompatible patch!
  • Multiple formatters per filetype are now supported.
  • Configuration variable names changed.
  • Using gq as alias for :Autoformat is no longer supported.
  • :Autoformat now supports ranges.
  • Composite filetypes are fully supported.

December 20 2013

  • html-beautify is now the new default for HTML since it seems to be better maintained, and seems to handle inline javascript neatly.
  • The formatters/ folder is no longer supported anymore, because it is unnecessary.
  • js-beautify can no longer be installed as a bundle, since it only makes this plugin unnecessarily complex.

March 27 2013

  • The default behaviour of gq is enabled again by removing the fallback on auto-indenting. Instead, the fallback is only used when running the command :Autoformat.

March 16 2013

  • The options expandtab, shiftwidth, tabstop and softtabstop are not overwritten anymore.
  • This obsoletes g:autoformat_no_default_shiftwidth
  • g:formatprg_args_expr_<filetype> is introduced.

March 13 2013

  • It is now possible to prevent vim-autoformat from overwriting your settings for tabstop, softtabstop, shiftwidth and expandtab in your .vimrc.

March 10 2013

  • When no formatter is installed or defined, vim will now auto-indent the file instead. This uses the indentfile for that specific filetype.

March 9 2013

  • Customization of formatprograms can be done easily now, as explained in the readme.
  • I set the default tabwidth to 4 for all formatprograms as well as for vim itself.
  • phpCB has been removed from the defaults, due to code-breaking behaviour.

vim-autoformat's People

Contributors

c02y avatar chaucerbao avatar chrishubinger avatar chtenb avatar cmcginty avatar danihodovic avatar dc3671 avatar ettom avatar faceleg avatar hftsin avatar jdonaldson avatar joshpetit avatar jpmv27 avatar keith avatar kuon avatar lstrojny avatar mmlb avatar mqudsi avatar oprudkyi avatar pseewald avatar raine avatar sbdchd avatar shanesmith avatar stdiopt avatar suminb avatar svenstaro avatar tamamcglinn avatar titanism avatar veelenga avatar yunlingz 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  avatar  avatar  avatar  avatar  avatar

vim-autoformat's Issues

Autoformat gofmt not work correctly

When I use gofmt from bash, it display my code with tabspace like 4 or 8 but when use gofmt with autoformat in vim, my code still use global setting tabstop=2. How can I avoid tabstop when use with only golang.
screenshot from 2015-08-02 14 02 04
screenshot from 2015-08-02 14 03 16

par support

If no formater set is there a way to let the defined formatprg untouched ?

for example in my .vimrc I have
:set formatprg=par

but when using autoformart resets it to formatpgr = ""

regards

Use parent formatting rules for child file types

For instance when I am editing a file that is of filetype html.handlebars I would like to use the formatprg options for the html filetype by default but currently I must manually set these values in vimrc to match that for html or autoformat will just use default vim indenting.

Could autoformat automatically use the before-the-dot filetype to set defaults for these "complex" filetypes?

Autoformat with autopep8 inserts newline at EOF

Hi,

:Autoformat in a python file inserts a newline at the end of the file, which causes the pep8 syntax checker to complain. Since I set up to run both at BufWrite automatically, this creates quite a paradox situation. The newline isn't added by the autopep8 command line program, as verified by doing a :%!autopep8 -.

formatprg should only be set locally

Right now, when opening a buffer, the formatprg is set for all buffers, which can lead to problems when working on multiple files with different filetypes.

Does not work with python file.

it works well with Java, and other file type, except python.
After I run :Autoformat in one open python file(60 lines), from the status line, I got following output
"60 lines filtered". and, all the 60 lines is deleted, what I got, is just an empty file.
Could you help me with this issue?

Error when running Autoformat on Ruby file

I've googled for a solution and am sure that I am probably doing something silly, but when running :Autoformat

I get the following output (verbosity turned on)

Error detected while processing function <SNR>12_TryAllFormatters:
line   27:
E117: Unknown function: rbeautify
E15: Invalid expression: rbeautify (&expandtab ? "-s -c ".&shiftwidth : "-t")
Formatter rbeautify has errors: /bin/sh: 0: command not found
. Skipping.
Failing config: '0'

The ruby-beautify gem is installed and on the PATH variable. From what I can tell line, 122 of autoformat.vim formatprg = vim.eval('&formatprg') evaluates to '0' instead of 'rbeautify' which is what is causing the message Formatter rbeautify has errors: /bin/sh: 0: command not found to be put in to stderr and printed on line 134 of autoformat.vim.

Again, I know this is likely to come down to me having gotten something very basic wrong. Any idea what it is?

Many thanks in advance.

Format selected lines

I'm not sure if this was mentioned before, but it would be neat to have the ability to indent select lines from visual mode. Since most of the formatters use stdin/stdout it seems possible to implement.

Can not format Python file.

When I type :Autoformat in a python file buffer, it just tell me that

No formatter installed for this file type.

But I did installed autopep8 via pip.

Add Objective-C support

astyle also supports Objective-C.

I tested it, and it seems to work just fine on the command-line:
astyle <myObjCFile.m>

However, in vim when I execute :Autoformat, I get the fallback vim auto indent rather than astyle's output. Adding this to my .vimrc did the trick:
let g:formatprg_objc= "astyle"

No Windows support for python

Just reporting, that the plugin doesn't work for windows because of g:formatprg_args_expr_python. It needs /dev/stdin which has no easy equivalent on windows.

Multiple formatters per language out of the box

When writing my own JS projects I use standard-format, however when writing code for work we use jsfmt. Syntastic has a whole list of linters they support out of the box, whereas with vim-autoformat some logic needs to be written. Is having multiple formatters per language out of the box something you would consider having? Thanks!

Autoformat deletes last line

To reproduce the issue create Exemple.rb file in vim:

class Example
  def dummy
    nil
  end
end

When one use autoformat the last line is deleted. The command ruby-beautify doesn't remove it when it is executed through command line..

ruby-beautify -v
0.97.3

ruby -v
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]

.astylerc settings are not used

I don't know if this is just me or if this is a common issue but when I run Astyle with vim-autoformat, it does not use the settings in .astylerc. Instead it looks like it uses the defaults. If I run astyle from the command line, it does work.

Use shiftwidth() instead of shiftwidth

A shiftwidth value of 0 means that the value of tabstop should be used instead. I had it set like that in my .vimrc and auto-indent did not work.

I my case, set sw=4 didn't work either, because something sets it back to 0. For anyone else having trouble, I had to use set &sw=&ts.

Must define at least one file

Hi, thank you so much for creating this plugin, and I use this all the time.
But recently, when I format a javascript file, the context of this file is replaced by js-beautify's help document:

Must define at least one file.
[email protected]
Javascript beautifier (http://jsbeautifier.org/)
Usage: jsbeautifier.py [options] <infile>
    <infile> can be "-", which means stdin.
    <outfile> defaults to stdout

Input options:

-i,  --stdin                      read input from stdin

Output options:

-s,  --indent-size=NUMBER         indentation size. (default 4).
...

So what happen? Do I missing something?
Thank You

How to specify external formatting program for compound filetypes?

I am using WordPress.vim addon which changes filetype for WordPress files to the compound file type php.wordpress.

I am trying to specify the autoformat programs for this compound filetype using the following, but it is not working

let g:formatprg_wordpress = "/Users/sudar/Dropbox/code/wp/phptidy/phptidy.php"
let g:formatprg_args_wordpress = "-q -c=/Users/sudar/Dropbox/code/dotfiles/vim/vim/phptidy-config.php"

Let me know how I should specify the autoformat program for these compound filetypes.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0'

This may not be related to the plugin but for some reason while opening a python file and trying to give format with autopep8, I am getting something like this:

Traceback (most recent call last):                                                                                                                                                                                          
File "/usr/local/bin/autopep8", line 9, in <module>                                                                                                                                                                     
    load_entry_point('autopep8==1.0.4a0', 'console_scripts', 'autopep8')()                                                                                                                                                  
File "/usr/local/lib/python2.7/site-packages/autopep8.py", line 3631, in main                                                                                                                        
    encoding=sys.stdin.encoding))                                                                                                                                                                                           
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 56672: ordinal not in range(128) 

Out of vim , from a terminal, autopep8 works using something like this:

cat a.py | autopep8 - --aggressive --aggressive --indent-size 4

On my .vimrc I have something like this:

let g:formatprg_args_expr_python = '"- --aggressive --aggressive --indent-size 4"'

My terminal locale output:

> locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=

Any idea of how to fix this?

php-cs-fixer

Hi, I am trying this so that I can use the php-cs-fixer:

let g:formatprg_php = "/usr/local/bin/php-cs-fixer"
let g:formatprg_args_expr_php = '"--fixers=linefeed,trailing_spaces,eof_ending,extra_empty_lines,controls_spaces -q fix ".expand("%:p")'

problem is that when current code is processed and it is clean (has no errors), vim removes the current code.

Any idea of how to just call the formater with out replacing the current code with the exit in this case of the php-cs-fixer ?

regards

c++ (clang-format) not using .clang-format file

I have set let g:formatdef_clangformat_objc = '"clang-format -style=file"' in my .vimrc.

In my C++ project I have a .clang-format file. I open vim in this directory, open a .cpp file, perform :Autoformat. It formats, but it doesn't follow the rules I defined in my .clang-format file.

Support for html-beautify

einars/js-beautify also provides html-beautify

I got it to work like this but perhaps it should be supported out of box?

let g:formatprg_html = "html-beautify"
let g:formatprg_args_html = '-f -'

bashrc not loaded

When triing to add php formatter (php-cs-fixer) throught composer, it not loads .bashrc so no alliases are working nor exports of path.

Problem with NodeJs for HTML and Javascript

I get this error (as an output) when I try to format HTML or Javascript codes.

node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: Object # has no method 'existsSync' at verifyExists (/usr/local/lib/node_modules/js-beautify/js/lib/cli.js:120:15) at findRecursive (/usr/local/lib/node_modules/js-beautify/js/lib/cli.js:126:18) at Object.interpret (/usr/local/lib/node_modules/js-beautify/js/lib/cli.js:155:9) at Object. (/usr/local/lib/node_modules/js-beautify/js/bin/js-beautify.js:4:5) at Module._compile (module.js:441:26) at Object..js (module.js:459:10) at Module.load (module.js:348:32) at Function._load (module.js:308:12) at Array.0 (module.js:479:10) at EventEmitter._tickCallback (node.js:192:41)

Wrong indentation when using a range / support range with commands

When using gqq on the third line of this:

def foo():
    if True:
        pass

It will become this:

def foo():
    if True:
    pass

That's probably caused by autopep8 not having enough context here,
because it only sees the pass line by itself.

Would it be possible for vim-autoformat to pass the whole buffer, but only
update/change the region that is being given?

There's a --line-range option for autopep8, which would allow for something like:

  • write buffer to a temporary file
  • call autopep8 --line-range 3 3 -d $tempfile
  • apply the diff to the current buffer

A generic approach would then have to use a special/new setting for programs that support ranges.
Does that sound sensible?

btw: I've noticed that the :Autoformat command doesn't support a range,
while this is possible through gq.

js-beautify fails with help text

I opened a file using CtrlP. On using :Autoformat it returns shell returned 1

_And finally fills the buffer with the following js-beautify help text:_
Must define at least one file.
[email protected]

Javascript beautifier (http://jsbeautifier.org/)

Usage: jsbeautifier.py [options]

<infile> can be "-", which means stdin.
<outfile> defaults to stdout

Input options:

-i, --stdin read input from stdin

Output options:

-s, --indent-size=NUMBER indentation size. (default 4).
-c, --indent-char=CHAR character to indent with. (default space).
-t, --indent-with-tabs Indent with tabs, overrides -s and -c
-d, --disable-preserve-newlines do not preserve existing line breaks.
-P, --space-in-paren add padding spaces within paren, ie. f( a, b )
-E, --space-in-empty-paren Add a single space inside empty paren, ie. f( )
-j, --jslint-happy more jslint-compatible output

How could I indent c++ pragma

There was a version that would indent the c++ pragma like this:

#include <omp.h>
#include <cstdio>
int main()
{
    #pragma omp parallel for
    for (int i = 0; i < 10; ++i)
    {
        puts("demo");
    }
    return 0;
}

instead of this:

#include <omp.h>
#include <cstdio>
int main()
{
#pragma omp parallel for
    for (int i = 0; i < 10; ++i)
    {
        puts("demo");
    }
    return 0;
}

the current version won't do that and I want to configure to restore that feature.

I tried to add this code into .vimrc but it didn't work:

let g:formatdef_mydef = '"astyle --mode=c --style=ansi -pcH".(&expandtab ? "s".&shiftwidth : "t")'
let g:formatters_cpp=['mydef']

Avoid changing buffer on error

Great plugin, super useful.

One issue I had is that if for some reason astyle errors out, it will replace my buffer with whatever error message it produced. To reproduce, if you add --foobar or some other bad option to format args, the buffer will be replaced by:

Invalid command line options:
foobar

For help on options type 'astyle -h'

Artistic Style has terminated

Would it be possible to restore the original buffer if the formatter returned 1?

Take 'textwidth' into account

For example in javascript i use somethingl line this

let g:formatprg_args_expr_javascript = '"-f - -k -".(&expandtab ? "s ".&shiftwidth : "t").(&textwidth ? " -w ".&textwidth : "")'

AStyle can't use the unix lineend

I added this in my _vimrc:

let g:formatdef_astyle_cpp = '"astyle --mode=c -z2 --style=ansi -pcH".(&expandtab ? "s".&shiftwidth : "t")'

But every times I run :Autoformat,the C++ file will be changed to dos lineend.
AStyle 2.051 built by VS2013 .When I run it in cmd with -z2,it works will.

conflict with ftplugin/markdown.vim

After I have installed vim-autoformat, there will be an error occured when I open a markdown file .

Here is the error message :

Vim(let):E121: Undefined variable: b:undo_ftplugin
Error occured in executing action!

Out of box support for jscs

http://jscs.info/

JSCS is a code style linter for programmatically enforcing your style guide. You can configure JSCS for your project in detail using over 90 validation rules, including presets from popular style guides like jQuery, Airbnb, Google, and more.

Adoption rates are high, it'd be great to see support for this built into this plugin

Autoformat Project

It would be very cool to be able to run a command that executes Autoformat on every file of a given type in the current project (the current directory and all subdirectories).

This would be useful for doing an auto-format on all files for the first time in a project that previously didn't have any auto-formatting or had a different auto-formatting scheme.

Using `:Autoformat` sets 'formatprg' / re-add support for `gq`

I've noticed that support for gq has been removed (dfd9461), which was previously handled like this:

noremap <expr> gq <SID>set_formatprg() ? 'gq' : 'gq'

Since gq makes use of 'formatprg', and invoking :Autoformat sets and does not restore it, gq appears to be (accidentally?) supported still, after you've manually called :Autoformat once.

Given that, what was the reason for removing direct support of gq, and do you think it could be re-added (to work right away)?

Why even use fmtprogram?

Vim's fmtprog will cause undo/redo to be reset to the first line. It also modifies the buffer even when nothing was actually formatted. I wrote my own version that just shells out and finds the first line that actually changed and begins calling setLine from there. Why not take this approach with vim-autoformat?

astyle --mode=cpp should be --mode=c

Hello,

the default option should be --mode=c and not --mode=cpp even for C++ code.

This is an excerpt from astyle --help
--mode=c
Indent a C or C++ source file (this is the default).

Using --mode=cpp results in an error which will leave the current buffer with the error message from astyle instead my formatted (or at least original) code.

The error message:

Invalid command line options:
mode=cpp

For help on options type 'astyle -h'

Artistic Style has terminated

python3 Type error

On the master branch, when formatting a python file, I get the following error:

format-error

I am using Python 3.5 on Arch Linux

When I switch to you dev branch, it works, but it adds an endline at the end of the file. I remember seeing the endline problem come up and get fixed, but does not seem to be working for me.

It does work fine from command line usage of autopep8.

E121 undefined variable: fix

error detected while processing function 49_Autoformat..49_set_formatprg:
line 20
E121 undefined variable:fix

Better document custom program formatting variable names

I spent a while (okay fine, 15 minutes or so) trying to debug why the setting formatprg_args_js wasn't working. I checked, and the documentation says it should be the filetype, so I wasn't sure what was wrong. Finally I dug into the source code and realized it should actually be javascript. Something making this a bit more clear would be nice.

Supply License

I know it's just a tiny script, but it would be nice to supply a license (MIT is a great choice ;) )

autopep8 does nothing

I installed autopep8 on my Ubuntu 15.04 system and verified that it works on the command line using "autopep8 -i -a somefile.py". Autopep8 is available globally.

Then I installed vim-autoformat using vundle. PluginList shows it is installed. When running :Autoformat, absolutely nothing happens. For example, I wish to have whitespaces (__) removed from the following code snippet:

for ___item in somelist: print item

When running autopep from the command line, the code is reformatted to:

for item in somelist: print item

When running :Autoformat, nothing happens.

I tried changing the default for autopep8 in vim-autoformat/plugin/defaults.vim to include --aggressive. Again, nothing.

Please advise. No idea what's going on here.

Arne

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.