I am new to Neovim, having moved from Emacs. One of the features I really liked and got used to in Emacs was automatic indentation and formatting while in different modes such as C++. I knew how to do this in Emacs and it was through the following added to my .emacs
:
defun linux-c-mode ()
"C mode with adjusted defaults for use with the Linux kernel."
(interactive)
(c-mode)
(c-set-style "K&R")
(setq tab-width 8)
(setq indent-tabs-mode t)
(setq c-basic-offset 8))
It worked beautifully when I was editing any file with a .c
extension: with the code text moving according to the C syntax. Similarly, for other kinds of files.
As an illustration, here is an animated gif of what I am looking for (in Emacs). Pardon my lack of typing skills that make it more painful to watch, but note that the indentation and formatting as happening automagically as I type in Emacs.
Is there similar code that I can put in my .config/nvim/init.vim
or some other file like that?
So, if you see, what is happening in the animated gif is that as I am typing with Emacs, I write for (
, the automatic indentation happens the moment I press the (
and then when the brace opens next {
, the indentation for the next line is automatic when I hit return key. Note that I am not actually having to press any key combination and formatting is happening according to the "Kernighan and Ritchie" style of C programming (as asked for in the style setting). This really helps in making fewer errors while writing code.
I looked into formatter.nvim
at https://github.com/mhartington/formatter.nvim but I am not sure it is possible to do what I am looking for automagically. Being new to nvim
, it is also quite confusing, and difficult to easily find suggestions because I am not sure what to search on.
For C bindings, I have found that adding the following to my `.config/nvim/init.vim' works fairly well:
autocmd BufEnter *.c,*.h,*.C set cindent formatoptions=croq
autocmd BufLeave *.c,*.h,*.C set nocindent formatoptions=tcq
However, I am still looking for better solutions.
Thanks for all the suggestions and the help, and my best wishes!
:help :filetype
and follow the links to different things like per-filetype indent settings. This is also introduced at some point in the user guide.\t
characters that are 8 characters wide?