GNOME Bugzilla – Bug 358866
Add code-style emacs & vi instruction snippets to beginning of files
Last modified: 2016-02-07 23:31:24 UTC
See bug 358042 comment 10 where Havoc points out that having /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ in our files would help with indentation style for those editing the code with emacs; I'll add that soon, but we should find out what the similar vi command is.
I think we need something like this at the end or beginning of the file: /* vi: set filetype=c: */ /* vi: set shiftwidth=8: */ /* vi: set cinoptions={.5s: */ See http://www.vim.org/tips/tip.php?tip_id=331 .
I object to shiftwidth=8 -- it would make working on the code highly annoying for me. It is needed to set shiftwidth explicitely because it is clearly visible in the code what indentation is being used and developers will use the visual feedback to get the indentation they want anyway. Moreover, almost all code (all that I have seen so far) uses an indentation of 4 spaces. If you'd set shiftwidth at all, it should be set to 4. By not using an 's' in cinoptions, it is not necessary to set shiftwidth anyway. Setting the filetype for *.c and *.h files is not necessary imho. What would be good is this addition: /* vi: set expandtab: */ I am not sure it is wise to add any other style enforcements to the source code itself, (that is - if it isn't possible to override them anymore for developer). But if you really want to, then the following is not depending on the shiftwidth and results in near perfectly close to the currently used style: /* vi: set expandtab: */ /* vi: set smartindent: */ /* vi: set cindent: */ /* vi: set cinoptions=>4,e-2,n-2,{2,^-2,=2,l1,t0,+2,(0,u2: */ Note that both, cindent and smartindent are needed. I tested this (took me several hours to compose and test it). It works (using vim 7.0; both +smartindent and +cindent features need to be compiled in) whether those lines are added at the top or at the bottom. I tested the cinoptions by replacing any leading TABs in src/window.c with the appropriate number of spaces, storing the result to window.compare. Then removed all leading spaces, storing the result to 'input' and then running a command simular to: cp header test.c; (echo -n "Go" && cat input && echo "^[:wq") | vi test.c which simulates re-typing all of window.c. Diffing test.c with window.compare shows that only comments and empty lines are different, except for a few styles here and there fixed and a small handful of indentations changed (very small). So, I am convinced that this is the optimal configuration. Actually, it still should contain also a ",:2" - but that colon is interpreted as the end of the inline command :/. So, the ':' setting remains 's' (1 shiftwidth). This shouldn't be a problem when the developer has the shiftwidth set to 2 (as I have). ':' controls the indentation of case labels relative to the switch statement (not very important anyway, thus).
I meant above: [...] It is NOT needed to set shiftwidth explicitely [...]
/* vi: set sw=4 ts=4 et si: -*- Mode: C; c-file-style: "gnu"; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ All (vi + emacs) in one line. Carlo, I left cindent for thinking it's not necessary. If is, we can add.
You also left out cinoptions, which in itself isn't that bad - but the whole point is to NOT change the shiftwidth. You should CERTAINLY not change the tab width! Your proposal is unusable. It's better to have no automatic style correction and a normal tabwidth (of standard 8), then visa versa. I'd almost go as far as to say that it's a bug in vi that it is possible to change the tab width. It should be standarized to 8. Now, if some weird people want to drive on the left side of the road, have a monetary system base 12 instead of 10 and use a TAB distance unequal 8, then that is their problem; but the metacity project really shouldn't. The point of the cinoptions line that I gave is that is not *depending* on the value of shiftwidth (so each developer can set it to what they want) and allows the tabwidth to be what it should be: 8.
Hey, we gave up the base 12 money 36 years ago now.
Carlo: I tried adding your suggested settings, closing vi and reopening it on that file, and then reformatting this function: void bananas (void) { if (tangerines) { pomegranates (); } } It came out thus: /* vi: set expandtab: */ /* vi: set smartindent: */ /* vi: set cindent: */ /* vi: set cinoptions=>4,e-2,n-2,{2,^-2,=2,l1,t0,+2,(0,u2: */ #include<stdio.h> void bananas (void) { if (tangerines) { pomegranates(); } } Do you fancy digging around in vim's cinoptions documentation and finding something better? If not, I'll give it a look later.
I get: void bananas(void) { if (tangerines) { pomegranates(); } } Note that the vim docs say: Note: If you change the current line's indentation manually, Vim ignores the cindent settings for that line. This prevents vim from reindenting after you have changed the indent by typing <BS>, <Tab>, or <Space> in the indent or used CTRL-T or CTRL-D. So, if you change the indentation of a function and expect it to be forced back to what vim dictates, that won't work. These settings are meant to give you the correct indentation when TYPE in new code. Try copying this with your mouse, and pasting it (with :set nopaste): void bananas(void) { if (tangerines) { pomegranates(); } } In other words, as if you type it.
The results of that experiment for me are: void bananas(void) { if (tangerines) { pomegranates(); } } Perhaps there's something that causes the half-indent that I have specified in my .vimrc which isn't specified in that cindent line? I'm aware that Vim doesn't reformat lines that you unformat manually (thank heavens); when I said I reformatted the function I meant going to the top and typing "=G".
If I type =G I get: void bananas(void) { if (tangerines) { pomegranates(); } } I have to manually type :set expandtab :set smartindent :set cindent :set cinoptions=>4,e-2,n-2,{2,^-2,=2,l1,t0,+2,(0,u2 first, because I can't get it to read it from the source file :/ The result of :set all after that is: :set all --- Options --- aleph=224 noconfirm foldcolumn=0 includeexpr= modifiable scroll=24 suffixesadd= undolevels=1000 noarabic nocopyindent foldenable noincsearch modified noscrollbind swapfile updatecount=200 arabicshape cpoptions=aABceFs foldexpr=0 indentexpr= more scrolljump=1 swapsync=fsync updatetime=4000 noallowrevins cscopepathcomp=0 foldignore=# noinfercase mouse= scrolloff=0 switchbuf= verbose=0 noaltkeymap cscopeprg=cscope foldlevel=0 noinsertmode nomousefocus nosecure synmaxcol=3000 verbosefile= ambiwidth=single cscopequickfix= foldlevelstart=-1 isprint=@,161-255 mousehide selectmode= syntax=c virtualedit= noautochdir nocscopetag foldmethod=manual joinspaces mousemodel=extend shell=/bin/bash tabline= novisualbell autoindent cscopetagorder=0 foldminlines=1 key= mousetime=500 shellcmdflag=-c tabpagemax=10 warn noautoread nocscopeverbose foldnestmax=20 keymap= nonumber shellquote= tabstop=8 noweirdinvert autowrite nocursorcolumn formatexpr= keymodel= numberwidth=4 shelltemp tagbsearch whichwrap=b,s noautowriteall nocursorline formatprg= keywordprg=man operatorfunc= shellxquote= taglength=0 wildchar=<Tab> background=light debug= fsync langmap= nopaste noshiftround tagrelative wildcharm=0 nobackup nodelcombine nogdefault langmenu= pastetoggle= shiftwidth=2 tagstack wildignore= backupcopy=auto dictionary= guifont= laststatus=1 patchexpr= noshortname term=xterm nowildmenu backupext=~ nodiff guifontwide= nolazyredraw patchmode= showbreak= notermbidi wildmode=full backupskip=/tmp/* diffexpr= guiheadroom=50 nolinebreak nopreserveindent noshowcmd termencoding= wildoptions= balloondelay=600 diffopt=filler guipty lines=50 previewheight=12 noshowfulltag noterse winaltkeys=menu noballooneval nodigraph guitablabel= linespace=0 nopreviewwindow showmatch textauto window=49 balloonexpr= display= guitabtooltip= nolisp printdevice= showmode notextmode winheight=1 nobinary eadirection=both helpheight=20 nolist printencoding= showtabline=1 textwidth=0 nowinfixheight nobomb noedcompatible helplang=en listchars=eol:$ printfont=courier sidescroll=8 thesaurus= nowinfixwidth browsedir=last encoding=utf-8 nohidden loadplugins printmbcharset= sidescrolloff=0 notildeop winminheight=1 bufhidden= endofline history=50 magic printmbfont= nosmartcase timeout winminwidth=1 buflisted equalalways nohkmap makeef= prompt smartindent timeoutlen=1000 winwidth=20 buftype= equalprg= nohkmapp makeprg=makevi pumheight=0 nosmarttab title nowrap cdpath=,, noerrorbells hlsearch matchtime=5 quoteescape=\ softtabstop=0 titlelen=85 wrapmargin=0 cedit=^F esckeys icon maxcombine=2 noreadonly nospell titlestring= wrapscan charconvert= eventignore= iconstring= maxfuncdepth=100 redrawtime=2000 spellfile= nottimeout write cindent expandtab noignorecase maxmapdepth=1000 remap spelllang=en ttimeoutlen=-1 nowriteany cmdheight=1 noexrc imactivatekey= maxmem=2018662 report=2 spellsuggest=best ttybuiltin writebackup cmdwinheight=7 fileformat=unix noimcmdline maxmemtot=2018662 norevins nosplitbelow ttyfast writedelay=0 columns=165 filetype=c noimdisable menuitems=25 norightleft nosplitright ttymouse=xterm2 nocompatible nofkmap iminsert=2 nomodeline ruler startofline ttyscroll=999 completefunc= foldclose= imsearch=2 modelines=5 rulerformat= statusline= ttytype=xterm backspace=indent,eol,start backupdir=.,~/tmp,~/ breakat= ^I!@*-+;:,./? casemap=internal,keepascii cinkeys=0{,0},0),:,0#,!^F,o,O,e cinoptions=>4,e-2,n-2,{2,^-2,=2,l1,t0,+2,(0,u2 cinwords=if,else,while,do,for,switch clipboard=autoselect,exclude:cons\|linux comments=sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,:// commentstring=/*%s*/ complete=.,w,b,u,t,i completeopt=menu,preview define=^\s*#\s*define directory=.,~/tmp,/var/tmp,/tmp errorfile=errors.err errorformat=%*[^"]"%f"%*\D%l: %m,"%f"%*\D%l: %m,%-G%f:%l: (Each undeclared identifier is reported only once,%-G%f:%l: for each function it appears in.),%f:%l:%c:%m ,%f(%l):%m,%f:%l:%m,"%f"\, line %l%*\D%c%*[^ ] %m,%D%*\a[%*\d]: Entering directory `%f',%X%*\a[%*\d]: Leaving directory `%f',%D%*\a: Entering directory `%f',%X%*\a: Leaving directory `%f',%DMaking %*\a in %f,%f|%l| %m fileencoding=utf-8 fileencodings=ucs-bom,utf-8,default,latin1 fileformats=unix,dos fillchars=vert:|,fold:- foldmarker={{{,}}} foldopen=block,hor,mark,percent,quickfix,search,tag,undo foldtext=foldtext() formatoptions=croql formatlistpat=^\s*\d\+[\]:.)}\t ]\s* grepformat=%f:%l:%m,%f:%l%m,%f %l%m grepprg=grep -n $* /dev/null guicursor=n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor,sm:block-Cursor-blinkwait175-blinkoff150-bl inkon175 guioptions=aegimrLtT helpfile=/usr/share/vim/vim71/doc/help.txt highlight=8:SpecialKey,@:NonText,d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr,r:Question,s:StatusLine,S:StatusLineNC,c:VertSplit,t:Titl e,v:Visual,V:VisualNOS,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn,A:DiffAdd,C:DiffChange,D:DiffDelete,T:DiffText,>:SignColumn,B:SpellBad,P:SpellCap,R:SpellRare,L: SpellLocal,+:Pmenu,=:PmenuSel,x:PmenuSbar,X:PmenuThumb,*:TabLine,#:TabLineSel,_:TabLineFill,!:CursorColumn,.:CursorLine include=^\s*#\s*include indentkeys=0{,0},:,0#,!^F,o,O,e isfname=@,48-57,/,.,-,_,+,,,#,$,%,~,= isident=@,48-57,_,192-255 iskeyword=@,48-57,_,192-255 lispwords=defun,define,defmacro,set!,lambda,if,case,let,flet,let*,letrec,do,do*,define-syntax,let-syntax,letrec-syntax,destructuring-bind,defpackage,defparameter,d efstruct,deftype,defvar,do-all-symbols,do-external-symbols,do-symbols,dolist,dotimes,ecase,etypecase,eval-when,labels,macrolet,multiple-value-bind,multiple-value-cal l,multiple-value-prog1,multiple-value-setq,prog1,progv,typecase,unless,unwind-protect,when,with-input-from-string,with-open-file,with-open-stream,with-output-to-stri ng,with-package-iterator,define-condition,handler-bind,handler-case,restart-bind,restart-case,with-simple-restart,store-value,use-value,muffle-warning,abort,continue ,with-slots,with-slots*,with-accessors,with-accessors*,defclass,defmethod,print-unreadable-object matchpairs=(:),{:},[:] maxmempattern=1000 mkspellmem=460000,2000,500 mouseshape=i-r:beam,s:updown,sd:udsizing,vs:leftright,vd:lrsizing,m:no,ml:up-arrow,v:rightup-arrow nrformats=octal,hex omnifunc=ccomplete#Complete paragraphs=IPLPPPQPP LIpplpipbp path=.,/usr/include,, printexpr=system('lpr' . (&printdevice == '' ? '' : ' -P' . &printdevice) . ' ' . v:fname_in) . delete(v:fname_in) + v:shell_error printheader=%<%f%h%m%=Page %N printoptions=paper:letter rightleftcmd=search runtimepath=~/.vim,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/share/vim/vim71,/usr/share/vim/vimfiles/after,/var/lib/vim/addons/after,~/.vim/after scrollopt=ver,jump sections=SHNHH HUnhsh selection=inclusive sessionoptions=blank,buffers,curdir,folds,help,options,tabpages,winsize shellpipe=2>&1| tee shellredir=>%s 2>&1 shortmess=filnxtToO spellcapcheck=[.?!]\_[\])'"^I ]\+ suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc tags=./tags,./TAGS,tags,TAGS titleold=Thanks for flying Vim toolbar=icons,tooltips toolbariconsize=small viewdir=~/.vim/view viewoptions=folds,options,cursor viminfo='20,<50,s10,h