root/dotfiles/vim/kana/dot.vimrc

Revision 7152, 45.1 kB (checked in by kana, 6 years ago)

dotfiles/vim/kana:
* s:_vcs_branch_name():

  • Fix the bug that the name of some remote branches weren't correctly gotten.
  • Revise the style of output for remote branches.

* 'tabline': Revise the style.

  • Property svn:keywords set to Id
Line 
1" My .vimrc
2" $Id$
3" Notes  "{{{1
4"
5" * This file consists of "sections".
6"
7"   - The name of each section should be one word.
8"
9" * Each section consists of zero or more "subsections".
10"
11"   - There is no rule for the name of each subsection.
12"
13" * The last subsection in a section should be named as "Misc.".
14"
15" * Whenever new subsection is inserted,
16"   it should be inserted just before Misc. subsection.
17"
18" * If a setting can be categorized into two or more sections,
19"   it should be put into the most bottom section in this file.
20"
21"   For example, key mappings for a specific plugin should be put into the
22"   Plugins section.
23"
24"
25" Coding Rule
26"
27" * Separate sections with 8 blank lines.
28"
29" * Separate subsections with 4 blank lines.
30"
31" * Character Encoding and Indentation:
32"   see the modelines in the bottom of this files.
33"
34" * Limit all lines to a maximum of 79 characters.
35"
36" * Separate {lhs} and {rhs} of key mappings with 2 spaces.
37"
38" * Separate {cmd} and {rep} of :command definitions with 2 spaces.
39"
40" * Write the full name for each command,
41"   e.g., write nnoremap not nn.
42"
43"     - But abbreviated names may be used to follow the maximum line length.
44"
45" * Key Notation:
46"
47"   - Control-keys: Write as <C-x>, neither <C-X> nor <c-x>.
48"
49"   - Carriage return: Write as <Return>, neither <Enter> nor <CR>.
50"
51"     - But <CR> may be used to follow the maximum line length.
52"
53"   - Other characters: Write as same as :help key-notation
54"
55" * Line continuation:
56"
57"   - Key mappings and abbreviations: Write \ at the previous column of the
58"     start of the {rhs}.
59"
60"   - Others: Write \ at the same column of the end of the previous command.
61"     Note that don't include "!".
62"
63"   - Examples:
64"
65"     silent! execute foo()
66"          \        . bar()
67"          \        . baz()
68"
69"     map <silent> xyzzy  :<C-u>execute foo()
70"                        \ bar()
71"                        \ baz()
72"                        \<Return>
73
74
75
76
77
78
79
80
81" Basic  "{{{1
82" Absolute  "{{{2
83
84set nocompatible  " to use many extensions of Vim.
85
86
87function! s:SID_PREFIX()
88 return matchstr(expand('<sfile>'), '<SNR>\d\+_')
89endfunction
90
91
92
93
94" Encoding  "{{{2
95
96" To deal with Japanese language.
97if $ENV_WORKING ==# 'colinux'
98  set encoding=utf-8
99else
100  set encoding=japan
101endif
102if !exists('did_encoding_settings') && has('iconv')
103  let s:enc_euc = 'euc-jp'
104  let s:enc_jis = 'iso-2022-jp'
105
106  " Does iconv support JIS X 0213 ?
107  if iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb"
108    let s:enc_euc = 'euc-jisx0213,euc-jp'
109    let s:enc_jis = 'iso-2022-jp-3'
110  endif
111
112  " Make fileencodings
113  let &fileencodings = 'ucs-bom'
114  if &encoding !=# 'utf-8'
115    let &fileencodings = &fileencodings . ',' . 'ucs-2le'
116    let &fileencodings = &fileencodings . ',' . 'ucs-2'
117  endif
118  let &fileencodings = &fileencodings . ',' . s:enc_jis
119
120  if &encoding ==# 'utf-8'
121    let &fileencodings = &fileencodings . ',' . s:enc_euc
122    let &fileencodings = &fileencodings . ',' . 'cp932'
123  elseif &encoding =~# '^euc-\%(jp\|jisx0213\)$'
124    let &encoding = s:enc_euc
125    let &fileencodings = &fileencodings . ',' . 'utf-8'
126    let &fileencodings = &fileencodings . ',' . 'cp932'
127  else  " cp932
128    let &fileencodings = &fileencodings . ',' . 'utf-8'
129    let &fileencodings = &fileencodings . ',' . s:enc_euc
130  endif
131  let &fileencodings = &fileencodings . ',' . &encoding
132
133  unlet s:enc_euc
134  unlet s:enc_jis
135
136  let did_encoding_settings = 1
137endif
138
139
140if $ENV_ACCESS ==# 'cygwin'
141  set termencoding=cp932
142elseif $ENV_ACCESS ==# 'linux'
143  set termencoding=euc-jp
144elseif $ENV_ACCESS ==# 'colinux'
145  set termencoding=utf-8
146else  " fallback
147  set termencoding=  " same as 'encoding'
148endif
149
150
151
152
153" Options  "{{{2
154
155if 1 < &t_Co && has('syntax')
156  if &term ==# 'rxvt-cygwin-native'
157    set t_Co=256
158  endif
159  syntax enable
160  colorscheme default
161  set background=dark
162endif
163
164filetype plugin indent on
165
166
167set ambiwidth=double
168set autoindent
169set backspace=indent,eol,start
170set backup
171set backupcopy&
172set backupdir=.,~/tmp
173set backupskip&
174set backupskip+=svn-commit.tmp,svn-commit.[0-9]*.tmp
175set cinoptions=:0,t0,(0,W1s
176set directory=.,~/tmp
177set noequalalways
178set formatoptions=tcroqnlM1
179set formatlistpat&
180let &formatlistpat .= '\|^\s*[*+-]\s*'
181set history=100
182set hlsearch
183nohlsearch  " To avoid (re)highlighting the last search pattern
184            " whenever $MYVIMRC is (re)loaded.
185set grepprg=internal
186set incsearch
187set laststatus=2  " always show status lines.
188set mouse=
189set ruler
190set showcmd
191set showmode
192set smartindent
193set updatetime=60000
194set title
195set titlestring=Vim:\ %f\ %h%r%m
196set wildmenu
197set viminfo=<50,'10,h,r/a,n~/.viminfo
198
199" default 'statusline' with 'fileencoding'.
200let &statusline = ''
201let &statusline .= '%<%f %h%m%r%w'
202let &statusline .= '%='
203  "" temporary disabled.
204  "let &statusline .= '(%{' . s:SID_PREFIX() . 'vcs_branch_name(getcwd())}) '
205let &statusline .= '[%{&fileencoding == "" ? &encoding : &fileencoding}]'
206let &statusline .= '  %-14.(%l,%c%V%) %P'
207
208function! s:MyTabLine()  "{{{
209  let s = ''
210
211  for i in range(1, tabpagenr('$'))
212    let bufnrs = tabpagebuflist(i)
213    let curbufnr = bufnrs[tabpagewinnr(i) - 1]  " first window, first appears
214
215    let no = (i <= 10 ? i-1 : '#')  " display 0-origin tabpagenr.
216    let mod = len(filter(bufnrs, 'getbufvar(v:val, "&modified")')) ? '+' : ' '
217    let title = s:GetTabVar(i, 'title')
218    let title = len(title) ? title : fnamemodify(s:GetTabVar(i, 'cwd'), ':t')
219    let title = len(title) ? title : fnamemodify(bufname(curbufnr),':t')
220    let title = len(title) ? title : '[No Name]'
221
222    let s .= '%'.i.'T'
223    let s .= '%#' . (i == tabpagenr() ? 'TabLineSel' : 'TabLine') . '#'
224    let s .= no
225    let s .= mod
226    let s .= title
227    let s .= '%#TabLineFill#'
228    let s .= '  '
229  endfor
230
231  let s .= '%#TabLineFill#%T'
232  let s .= '%=%#TabLine#'
233  let s .= '| '
234  let s .= '%999X'
235  let branch_name = s:vcs_branch_name(getcwd())
236  let s .= (branch_name != '' ? branch_name : '?')
237  let s .= '%X'
238  return s
239endfunction "}}}
240let &tabline = '%!' . s:SID_PREFIX() . 'MyTabLine()'
241
242" To automatically detect the width and the height of the terminal,
243" the followings must not be set.
244"
245" set columns=80
246" set lines=25
247
248
249let mapleader=','
250let maplocalleader='.'
251
252
253" Use this group for any autocmd defined in this file.
254augroup MyAutoCmd
255  autocmd!
256augroup END
257
258
259
260
261
262
263
264
265" Utilities  "{{{1
266" For per-'filetype' settings "{{{2
267"
268" To write a bit of customization per 'filetype', an easy way is to write some
269" :autocmds like "autocmd FileType c".  But it doesn't match to compound
270" 'filetype' such as "c.doxygen".  So the pattern should be
271" "{c,*.c,c.*,*.c.*}", but it's hard to read and to write.  :OnFileType which
272" is just a wrapper for :autocmd FileType supports to write such
273" customization.
274"
275" Note: If a:filetype contains one of the following characters:
276"               * ? { } [ ]
277"       a:filetype will be treated as-is to write customization for compound
278"       'filetype' with :OnFileType.
279" Note: If a:filetype contains one or more ",", :OnFileType will be called for
280"       each ","-separated filetype in a:filetype.
281"
282" FIXME: syntax highlighting and completion.
283
284command! -nargs=+ OnFileType  call <SID>OnFileType(<f-args>)
285function! s:OnFileType(group, filetype, ...)
286  let group = (a:group == '-' ? '' : a:group)
287  let commands = join(a:000)
288
289  let SPECIAL_CHARS = '[*?{}[\]]'
290  if a:filetype !~ SPECIAL_CHARS && a:filetype =~ ','
291    for ft in split(a:filetype, ',')
292      call s:OnFileType(group, ft, commands)
293    endfor
294    return
295  endif
296  let filetype = (a:filetype =~ SPECIAL_CHARS
297    \             ? a:filetype
298    \             : substitute('{x,x.*,*.x,*.x.*}', 'x', a:filetype, 'g'))
299
300  execute 'autocmd' group 'FileType' filetype commands
301endfunction
302
303
304
305
306" MAP: wrapper for :map variants.  "{{{2
307"
308" :MAP {option}* {modes} {lhs} {rhs}
309"
310"   {option}
311"     One of the following string:
312"       <echo>    The mapping will be echoed on the command line.
313"                 Default: not echoed.
314"       <re>      The mapping will be remapped.
315"                 Default: not remapped.
316"
317"   {modes}
318"     String which consists of the following characters:
319"       c i l n o s v x
320"
321"   {lhs}, {rhs}
322"     Same as :map.
323
324command! -bar -complete=mapping -nargs=+ MAP  call s:MAP(<f-args>)
325
326function! s:MAP(...)
327  if !(3 <= a:0)
328    throw 'Insufficient arguments: '.string(a:000)
329  endif
330
331  let silentp = 1
332  let noremap = 1
333  let i = 0
334  while i < a:0
335    if a:000[i] ==# '<echo>'
336      let silentp = 0
337    elseif a:000[i] ==# '<re>'
338      let noremap = 0
339    else
340      break
341    endif
342    let i += 1
343  endwhile
344
345  let mapcommand = (noremap ? 'noremap' : 'map')
346  let silentoption = (silentp ? '<silent>' : '')
347  let j = 0
348  let modes = a:000[i]
349  while j < len(modes)
350    execute (modes[j] . mapcommand) silentoption join(a:000[i+1:])
351    let j += 1
352  endwhile
353endfunction
354
355
356autocmd MyAutoCmd FileType vim
357      \   syntax keyword my_vim_MAP MAP
358      \     skipwhite
359      \     nextgroup=my_vim_MAP_option,my_vim_MAP_modes,vimMapMod,vimMapLhs
360      \ | syntax match my_vim_MAP_option '<\(echo\|re\)>'
361      \     skipwhite
362      \     nextgroup=my_vim_MAP_option,my_vim_MAP_modes,vimMapMod,vimMapLhs
363      \ | syntax match my_vim_MAP_modes '\<[cilnosvx]\+\>'
364      \     skipwhite
365      \     nextgroup=vimMapMod,vimMapLhs
366      \ | highlight default link my_vim_MAP vimMap
367      \ | highlight default link my_vim_MAP_option vimUserAttrbCmplt
368      \ | highlight default link my_vim_MAP_modes vimUserAttrbKey
369
370
371
372
373" CMapABC: support input for Alternate Built-in Commands  "{{{2
374" Memo: It's possible to implement this feature by using :cabbrev with <expr>.
375" But it seems to be hard to reset the current definitions.
376
377let s:CMapABC_Entries = []
378function! s:CMapABC_Add(original_pattern, alternate_name)
379  call add(s:CMapABC_Entries, [a:original_pattern, a:alternate_name])
380endfunction
381
382
383cnoremap <expr> <Space>  <SID>CMapABC()
384function! s:CMapABC()
385  let cmdline = getcmdline()
386  for [original_pattern, alternate_name] in s:CMapABC_Entries
387    if cmdline =~# original_pattern
388      return "\<C-u>" . alternate_name . ' '
389    endif
390  endfor
391  return ' '
392endfunction
393
394
395
396
397" Alternate :cd which uses 'cdpath' for completion  "{{{2
398
399command! -complete=customlist,<SID>CommandComplete_cdpath -nargs=1 CD
400      \ TabCD <args>
401
402function! s:CommandComplete_cdpath(arglead, cmdline, cursorpos)
403  return split(globpath(&cdpath, a:arglead . '*/'), "\n")
404endfunction
405
406call s:CMapABC_Add('^cd', 'CD')
407
408
409
410
411" Help-related stuffs  "{{{2
412
413function! s:HelpBufWinNR()
414  let wn = 1
415  while wn <= winnr('$')
416    let bn = winbufnr(wn)
417    if getbufvar(bn, '&buftype') == 'help'
418      return [bn, wn]
419    endif
420    let wn = wn + 1
421  endwhile
422  return [-1, 0]
423endfunction
424
425function! s:HelpWindowClose()
426  let [help_bufnr, help_winnr] = s:HelpBufWinNR()
427  if help_bufnr == -1
428    return
429  endif
430
431  let current_winnr = winnr()
432  execute help_winnr 'wincmd w'
433  execute 'wincmd c'
434  if current_winnr < help_winnr
435    execute current_winnr 'wincmd w'
436  elseif help_winnr < current_winnr
437    execute (current_winnr-1) 'wincmd w'
438  else
439    " NOP
440  endif
441endfunction
442
443
444
445
446" High-level key sequences  "{{{2
447
448function! s:KeysToComplete()
449  if &l:filetype ==# 'vim'
450    return "\<C-x>\<C-v>"
451  elseif strlen(&l:omnifunc)
452    return "\<C-x>\<C-o>"
453  else
454    return "\<C-n>"
455  endif
456endfunction
457
458function! s:KeysToStopInsertModeCompletion()
459  if pumvisible()
460    return "\<C-y>"
461  else
462    return "\<Space>\<BS>"
463  endif
464endfunction
465
466
467function! s:KeysToEscapeCommandlineModeIfEmpty(key)
468  if getcmdline() == ''
469    return "\<Esc>"
470  else
471    return a:key
472  end
473endfunction
474
475
476function! s:KeysToInsertOneCharacter()
477  Echo ModeMsg '-- INSERT (one char) --'
478  return nr2char(getchar()) . "\<Esc>"
479endfunction
480
481
482
483
484" :edit with specified 'fileencoding'.  "{{{2
485
486com! -nargs=? -complete=file -bang -bar Cp932  edit<bang> ++enc=cp932 <args>
487com! -nargs=? -complete=file -bang -bar Eucjp  edit<bang> ++enc=euc-jp <args>
488com! -nargs=? -complete=file -bang -bar Iso2022jp  Jis<bang> <args>
489com! -nargs=? -complete=file -bang -bar Jis edit<bang> ++enc=iso-2022-jp <args>
490com! -nargs=? -complete=file -bang -bar Sjis  Cp932<bang> <args>
491com! -nargs=? -complete=file -bang -bar Utf8  edit<bang> ++enc=utf-8 <args>
492
493
494
495
496" Jump sections  "{{{2
497
498" for normal mode.  a:pattern is '/regexp' or '?regexp'.
499function! s:JumpSectionN(pattern)
500  let pattern = strpart(a:pattern, '1')
501  if strpart(a:pattern, 0, 1) == '/'
502    let flags = 'W'
503  else
504    let flags = 'Wb'
505  endif
506
507  mark '
508  let i = 0
509  while i < v:count1
510    if search(pattern, flags) == 0
511      if stridx(flags, 'b') != -1
512        normal! gg
513      else
514        normal! G
515      endif
516      break
517    endif
518    let i = i + 1
519  endwhile
520endfunction
521
522
523" for visual mode.  a:motion is '[[', '[]', ']]' or ']['.
524function! s:JumpSectionV(motion)
525  execute 'normal!' "gv\<Esc>"
526  execute 'normal' v:count1 . a:motion
527  let line = line('.')
528  let col = col('.')
529
530  normal! gv
531  call cursor(line, col)
532endfunction
533
534
535" for operator-pending mode.  a:motion is '[[', '[]', ']]' or ']['.
536function! s:JumpSectionO(motion)
537  execute 'normal' v:count1 . a:motion
538endfunction
539
540
541
542
543" Per-tab current directory  "{{{2
544
545command! -nargs=1 TabCD
546      \   execute 'cd' <q-args>
547      \ | let t:cwd = getcwd()
548
549autocmd MyAutoCmd TabEnter *
550      \   if !exists('t:cwd')
551      \ |   let t:cwd = getcwd()
552      \ | endif
553      \ | execute 'cd' t:cwd
554
555
556
557
558" Window-related stuffs  "{{{2
559
560" Are the windows :split'ed and :vsplit'ed?
561function! s:WindowsJumbledP()
562  " Calculate the terminal height by some values other than 'lines'.
563  " Don't consider about :vsplit.
564  let calculated_height = &cmdheight
565  let winid = winnr('$')
566  while 0 < winid
567    let calculated_height += 1  " statusline
568    let calculated_height += winheight(winid)
569    let winid = winid - 1
570  endwhile
571  if &laststatus == 0
572    let calculated_height -= 1
573  elseif &laststatus == 1 && winnr('$') == 1
574    let calculated_height -= 1
575  else  " &laststatus == 2
576    " nothing to do
577  endif
578
579  " Calculate the terminal width by some values other than 'columns'.
580  " Don't consider about :split.
581  let calculated_width = 0
582  let winid = winnr('$')
583  while 0 < winid
584    let calculated_width += 1  " VertSplit
585    let calculated_width += winwidth(winid)
586    let winid = winid - 1
587  endwhile
588  let calculated_width -= 1
589
590  " If the windows are only :split'ed, &lines == calculated_height.
591  " If the windows are only :vsplit'ed, &columns == calculated_width.
592  " If there is only one window, both pairs are same.
593  " If the windows are :split'ed and :vsplit'ed, both pairs are different.
594  return (&lines != calculated_height) && (&columns != calculated_width)
595endfunction
596
597
598function! s:MoveWindowThenEqualizeIfNecessary(direction)
599  let jumbled_beforep = s:WindowsJumbledP()
600  execute 'wincmd' a:direction
601  let jumbled_afterp = s:WindowsJumbledP()
602
603  if jumbled_beforep || jumbled_afterp
604    wincmd =
605  endif
606endfunction
607
608
609function! s:MoveWindowIntoTabPage(target_tabpagenr)
610  " Move the current window into a:target_tabpagenr.
611  " If a:target_tabpagenr is 0, move into new tab page.
612  if a:target_tabpagenr < 0  " ignore invalid number.
613    return
614  endif
615  let original_tabnr = tabpagenr()
616  let target_bufnr = bufnr('')
617  let window_view = winsaveview()
618
619  if a:target_tabpagenr == 0
620    tabnew
621    tabmove  " Move new tabpage at the last.
622    execute target_bufnr 'buffer'
623    let target_tabpagenr = tabpagenr()
624  else
625    execute a:target_tabpagenr 'tabnext'
626    let target_tabpagenr = a:target_tabpagenr
627    topleft new  " FIXME: be customizable?
628    execute target_bufnr 'buffer'
629  endif
630  call winrestview(window_view)
631
632  execute original_tabnr 'tabnext'
633  if 1 < winnr('$')
634    close
635  else
636    enew
637  endif
638
639  execute target_tabpagenr 'tabnext'
640endfunction
641
642
643function! s:ScrollOtherWindow(scroll_command)
644  if winnr('$') == 1 || winnr('#') == 0
645    " Do nothing when there is only one window or no previous window.
646    Echo ErrorMsg 'There is no window to scroll.'
647  else
648    execute 'normal!' "\<C-w>p"
649    execute 'normal!' (s:Count() . a:scroll_command)
650    execute 'normal!' "\<C-w>p"
651  endif
652endfunction
653
654
655
656
657" VCS branch name  "{{{2
658" Returns the name of the current branch of the given directory.
659" BUGS: git is only supported.
660let s:_vcs_branch_name_cache = {}  " dir_path = [branch_name, key_file_mtime]
661
662
663function! s:vcs_branch_name(dir)
664  let cache_entry = get(s:_vcs_branch_name_cache, a:dir, 0)
665  if cache_entry is 0
666   \ || cache_entry[1] < getftime(s:_vcs_branch_name_key_file(a:dir))
667    unlet cache_entry
668    let cache_entry = s:_vcs_branch_name(a:dir)
669    let s:_vcs_branch_name_cache[a:dir] = cache_entry
670  endif
671
672  return cache_entry[0]
673endfunction
674
675
676function! s:_vcs_branch_name_key_file(dir)
677  return a:dir . '/.git/HEAD'
678endfunction
679
680
681function! s:_vcs_branch_name(dir)
682  let head_file = s:_vcs_branch_name_key_file(a:dir)
683  let branch_name = ''
684
685  if filereadable(head_file)
686    let ref_info = s:first_line(head_file)
687    if ref_info =~ '^\x\{40}$'
688      let remote_refs_dir = a:dir . '/.git/refs/remotes/'
689      let remote_branches = split(glob(remote_refs_dir . '**'), "\n")
690      call filter(remote_branches, 's:first_line(v:val) ==# ref_info')
691      if 1 <= len(remote_branches)
692        let branch_name = 'remote: '. remote_branches[0][len(remote_refs_dir):]
693      endif
694    else
695      let branch_name = matchlist(ref_info, '^ref: refs/heads/\(\S\+\)$')[1]
696      if branch_name == ''
697        let branch_name = ref_info
698      endif
699    endif
700  endif
701
702  return [branch_name, getftime(head_file)]
703endfunction
704
705
706
707
708" Misc.  "{{{2
709
710function! s:ToggleBell()
711  if &visualbell
712    set novisualbell t_vb&
713    echo 'bell on'
714  else
715    set visualbell t_vb=
716    echo 'bell off'
717  endif
718endfunction
719
720function! s:ToggleOption(option_name)
721  execute 'setlocal' a:option_name.'!'
722  execute 'setlocal' a:option_name.'?'
723endfunction
724
725
726function! s:ExtendHighlight(target_group, original_group, new_settings)
727  redir => resp
728  silent execute 'highlight' a:original_group
729  redir END
730  if resp =~# 'xxx cleared'
731    let original_settings = ''
732  elseif resp =~# 'xxx links to'
733    return s:ExtendHighlight(
734         \   a:target_group,
735         \   substitute(resp, '\_.*xxx links to\s\+\(\S\+\)', '\1', ''),
736         \   a:new_settings
737         \ )
738  else  " xxx {key}={arg} ...
739    let t = substitute(resp,'\_.*xxx\(\(\_s\+[^= \t]\+=[^= \t]\+\)*\)','\1','')
740    let original_settings = substitute(t, '\_s\+', ' ', 'g')
741  endif
742
743  silent execute 'highlight' a:target_group 'NONE'
744       \     '|' 'highlight' a:target_group original_settings
745       \     '|' 'highlight' a:target_group a:new_settings
746endfunction
747
748
749function! s:Count(...)
750  if v:count == v:count1  " count is specified.
751    return v:count
752  else  " count is not specified.  (the default '' is useful for special value)
753    return a:0 == 0 ? '' : a:1
754  endif
755endfunction
756
757command! -nargs=* -complete=expression -range -count=0 Execute
758      \ call s:Execute(<f-args>)
759function! s:Execute(...)
760  let args = []
761  for a in a:000
762    if a ==# '[count]'
763      let a = s:Count()
764    endif
765    call add(args, a)
766  endfor
767  execute join(args)
768endfunction
769
770
771" like join (J), but move the next line into the cursor position.
772function! s:JoinHere(...)
773  let adjust_spacesp = a:0 ? a:1 : 1
774  let pos = getpos('.')
775  let r = @"
776
777  if line('.') == line('$')
778    Echo ErrorMsg 'Unable to join at the bottom line.'
779    return
780  endif
781
782  if adjust_spacesp  " adjust spaces between texts being joined as same as J.
783    normal! D
784    let l = @"
785
786    normal! J
787
788    call append(line('.'), '')
789    call setreg('"', l, 'c')
790    normal! jpkJ
791  else  " don't adjust spaces like gJ.
792    call setreg('"', getline(line('.') + 1), 'c')
793    normal! ""Pjdd
794  endif
795
796  let @" = r
797  call setpos('.', pos)
798endfunction
799
800
801function! s:SetShortIndent()
802  setlocal expandtab softtabstop=2 shiftwidth=2
803endfunction
804
805
806command! -bar -nargs=+ -range Echo  call <SID>Echo(<f-args>)
807function! s:Echo(hl_name, ...)
808  execute 'echohl' a:hl_name
809  execute 'echo' join(a:000)
810  echohl None
811endfunction
812
813
814function! s:GetTabVar(tabnr, varname)
815  " Wrapper for non standard (my own) built-in function gettabvar().
816  return exists('*gettabvar') ? gettabvar(a:tabnr, a:varname) : ''
817endfunction
818
819
820command! -bar -nargs=0 TabTitle
821      \ let t:title = input("Set tabpage's title to: ",'')
822
823
824" Set up the layout of my usual days.
825command! -bar -nargs=0 UsualDays  call s:UsualDays()
826function! s:UsualDays()
827  normal! 'T
828  execute 'CD' fnamemodify(expand('%'), ':p:h')
829
830  tabnew
831  normal! 'V
832  execute 'CD' fnamemodify(expand('%'), ':p:h:h')
833endfunction
834
835
836" :source with echo.
837command! -bar -nargs=1 Source  echo 'Sourcing ...' <args> | source <args>
838
839
840function! s:first_line(file)
841  let lines = readfile(a:file, '', 1)
842  return 1 <= len(lines) ? lines[0] : ''
843endfunction
844
845
846
847
848
849
850
851
852" Key Mappings  "{{{1
853" FIXME: many {rhs}s use : without <C-u> (clearing count effect).
854" FIXME: some mappings are not countable.
855" Tag jumping  "{{{2
856" FIXME: the target window of :split/:vsplit version.
857" Fallback  "{{{3
858
859" ``T'' is also disabled for consistency.
860noremap           t          <Nop>
861noremap           T          <Nop>
862
863" Alternatives for the original actions.
864noremap           [Space]t   t
865noremap           [Space]T   T
866
867
868" Basic  "{{{3
869
870nnoremap          tt         <C-]>
871vnoremap          tt         <C-]>
872nnoremap <silent> tj         :<C-u>tag<Return>
873nnoremap <silent> tk         :<C-u>pop<Return>
874nnoremap <silent> tl         :<C-u>tags<Return>
875nnoremap <silent> tn         :<C-u>tnext<Return>
876nnoremap <silent> tp         :<C-u>tprevious<Return>
877nnoremap <silent> tP         :<C-u>tfirst<Return>
878nnoremap <silent> tN         :<C-u>tlast<Return>
879
880" additions, like Web browsers
881nmap              <C-m>      tt
882vmap              <C-m>      tt
883
884" addition, interactive use.
885nnoremap          t<Space>   :<C-u>tag<Space>
886
887
888" With the preview window  "{{{3
889
890nnoremap          t't        <C-w>}
891vnoremap          t't        <C-w>}
892nnoremap <silent> t'n        :<C-u>ptnext<Return>
893nnoremap <silent> t'p        :<C-u>ptpevious<Return>
894nnoremap <silent> t'P        :<C-u>ptfirst<Return>
895nnoremap <silent> t'N        :<C-u>ptlast<Return>
896
897" although :pclose is not related to tag.
898" BUGS: t'' is not related to the default meaning of ''.
899nnoremap <silent> t'c        :<C-u>pclose<Return>
900nmap              t'z        t'c
901nmap              t''        t'c
902
903
904" With :split  "{{{3
905
906nnoremap          tst        <C-w>]
907vnoremap          tst        <C-w>]
908nnoremap <silent> tsn        :<C-u>split \| tnext<Return>
909nnoremap <silent> tsp        :<C-u>split \| tpevious<Return>
910nnoremap <silent> tsP        :<C-u>split \| tfirst<Return>
911nnoremap <silent> tsN        :<C-u>split \| tlast<Return>
912
913
914" With :vertical split  "{{{3
915
916  " |:vsplit|-then-|<C-]>| is simple
917  " but its modification to tag stacks is not same as |<C-w>]|.
918nnoremap <silent> tvt        <C-]>:<C-u>vsplit<Return><C-w>p<C-t><C-w>p
919vnoremap <silent> tvt        <C-]>:<C-u>vsplit<Return><C-w>p<C-t><C-w>p
920nnoremap <silent> tvn        :<C-u>vsplit \| tnext<Return>
921nnoremap <silent> tvp        :<C-u>vsplit \| tpevious<Return>
922nnoremap <silent> tvP        :<C-u>vsplit \| tfirst<Return>
923nnoremap <silent> tvN        :<C-u>vsplit \| tlast<Return>
924
925
926
927
928" Quickfix  "{{{2
929" Fallback  "{{{3
930
931" the prefix key.
932nnoremap          q          <Nop>
933
934" alternative key for the original action.
935" -- Ex-mode will be never used and recordings are rarely used.
936nnoremap          Q          q
937
938
939" For quickfix list  "{{{3
940
941nnoremap <silent> qj         :Execute cnext [count]<Return>
942nnoremap <silent> qk         :Execute cprevious [count]<Return>
943nnoremap <silent> qr         :Execute crewind [count]<Return>
944nnoremap <silent> qK         :Execute cfirst [count]<Return>
945nnoremap <silent> qJ         :Execute clast [count]<Return>
946nnoremap <silent> qfj        :Execute cnfile [count]<Return>
947nnoremap <silent> qfk        :Execute cpfile [count]<Return>
948nnoremap <silent> ql         :<C-u>clist<Return>
949nnoremap <silent> qq         :Execute cc [count]<Return>
950nnoremap <silent> qo         :Execute copen [count]<Return>
951nnoremap <silent> qc         :<C-u>cclose<Return>
952nnoremap <silent> qp         :Execute colder [count]<Return>
953nnoremap <silent> qn         :Execute cnewer [count]<Return>
954nnoremap <silent> qm         :<C-u>make<Return>
955nnoremap          qM         :<C-u>make<Space>
956nnoremap          q<Space>   :<C-u>make<Space>
957nnoremap          qg         :<C-u>grep<Space>
958
959
960" For location list (mnemonic: Quickfix list for the current Window)  "{{{3
961
962nnoremap <silent> qwj        :Execute lnext [count]<Return>
963nnoremap <silent> qwk        :Execute lprevious [count]<Return>
964nnoremap <silent> qwr        :Execute lrewind [count]<Return>
965nnoremap <silent> qwK        :Execute lfirst [count]<Return>
966nnoremap <silent> qwJ        :Execute llast [count]<Return>
967nnoremap <silent> qwfj       :Execute lnfile [count]<Return>
968nnoremap <silent> qwfk       :Execute lpfile [count]<Return>
969nnoremap <silent> qwl        :<C-u>llist<Return>
970nnoremap <silent> qwq        :Execute ll [count]<Return>
971nnoremap <silent> qwo        :Execute lopen [count]<Return>
972nnoremap <silent> qwc        :<C-u>lclose<Return>
973nnoremap <silent> qwp        :Execute lolder [count]<Return>
974nnoremap <silent> qwn        :Execute lnewer [count]<Return>
975nnoremap <silent> qwm        :<C-u>lmake<Return>
976nnoremap          qwM        :<C-u>lmake<Space>
977nnoremap          qw<Space>  :<C-u>lmake<Space>
978nnoremap          qwg        :<C-u>lgrep<Space>
979
980
981
982
983" Tab pages  "{{{2
984" The mappings defined here are similar to the ones for windows.
985" FIXME: sometimes, hit-enter prompt appears.  but no idea for the reason.
986" Fallback  "{{{3
987
988" the prefix key.
989" -- see Tag jumping subsection for alternative keys for the original action
990"    of <C-t>.
991nnoremap <C-t>  <Nop>
992
993
994" Basic  "{{{3
995
996  " Move new tabpage at the last.
997nnoremap <silent> <C-t>n  :<C-u>tabnew \| tabmove<Return>
998nnoremap <silent> <C-t>c  :<C-u>tabclose<Return>
999nnoremap <silent> <C-t>o  :<C-u>tabonly<Return>
1000nnoremap <silent> <C-t>i  :<C-u>tabs<Return>
1001
1002nmap <C-t><C-n>  <C-t>n
1003nmap <C-t><C-c>  <C-t>c
1004nmap <C-t><C-o>  <C-t>o
1005nmap <C-t><C-i>  <C-t>i
1006
1007nnoremap <silent> <C-t>T  :<C-u>TabTitle<Return>
1008
1009
1010" Moving around tabs.  "{{{3
1011
1012nnoremap <silent> <C-t>j  :<C-u>execute 'tabnext'
1013                         \ 1 + (tabpagenr() + v:count1 - 1) % tabpagenr('$')
1014                         \<Return>
1015nnoremap <silent> <C-t>k  :Execute tabprevious [count]<Return>
1016nnoremap <silent> <C-t>K  :<C-u>tabfirst<Return>
1017nnoremap <silent> <C-t>J  :<C-u>tablast<Return>
1018
1019nmap <C-t><C-j>  <C-t>j
1020nmap <C-t><C-k>  <C-t>k
1021nmap <C-t><C-t>  <C-t>j
1022
1023" GNU screen like mappings.
1024" Note that the numbers in {lhs}s are 0-origin.  See also 'tabline'.
1025for i in range(10)
1026  execute 'nnoremap <silent>' ('<C-t>'.(i))  ((i+1).'gt')
1027endfor
1028unlet i
1029
1030
1031" Moving tabs themselves.  "{{{3
1032
1033nnoremap <silent> <C-t>l  :<C-u>execute 'tabmove'
1034                         \ min([tabpagenr() + v:count1 - 1, tabpagenr('$')])
1035                         \<Return>
1036nnoremap <silent> <C-t>h  :<C-u>execute 'tabmove'
1037                         \ max([tabpagenr() - v:count1 - 1, 0])
1038                         \<Return>
1039nnoremap <silent> <C-t>L  :<C-u>tabmove<Return>
1040nnoremap <silent> <C-t>H  :<C-u>tabmove 0<Return>
1041
1042nmap <C-t><C-l>  <C-t>l
1043nmap <C-t><C-h>  <C-t>h
1044
1045
1046
1047
1048" Command-line editting  "{{{2
1049
1050" pseudo vi-like keys
1051cnoremap <Esc>h  <Left>
1052cnoremap <Esc>j  <Down>
1053cnoremap <Esc>k  <Up>
1054cnoremap <Esc>l  <Right>
1055cnoremap <Esc>H  <Home>
1056cnoremap <Esc>L  <End>
1057cnoremap <Esc>w  <S-Right>
1058cnoremap <Esc>b  <S-Left>
1059cnoremap <Esc>x  <Del>
1060
1061" escape Command-line mode if the command line is empty (like <C-h>)
1062cnoremap <expr> <C-u>  <SID>KeysToEscapeCommandlineModeIfEmpty("\<C-u>")
1063cnoremap <expr> <C-w>  <SID>KeysToEscapeCommandlineModeIfEmpty("\<C-w>")
1064
1065" Search slashes easily (too lazy to prefix backslashes to slashes)
1066cnoremap <expr> /  getcmdtype() == '/' ? '\/' : '/'
1067
1068
1069
1070
1071" Input: datetime  "{{{2
1072"
1073" Input the current date/time (Full, Date, Time).
1074"
1075" FIXME: use timezone of the system, instead of static one.
1076" FIXME: revise the {lhs}s, compare with the default keys of textobj-datetime.
1077
1078inoremap <Leader>dF  <C-r>=strftime('%Y-%m-%dT%H:%M:%S+09:00')<Return>
1079inoremap <Leader>df  <C-r>=strftime('%Y-%m-%dT%H:%M:%S')<Return>
1080inoremap <Leader>dd  <C-r>=strftime('%Y-%m-%d')<Return>
1081inoremap <Leader>dT  <C-r>=strftime('%H:%M:%S')<Return>
1082inoremap <Leader>dt  <C-r>=strftime('%H:%M')<Return>
1083
1084
1085
1086
1087" Section jumping  "{{{2
1088"
1089" Enable *consistent* ]] and other motions in Visual and Operator-pending
1090" mode.  Because some ftplugins provide these motions only for Normal mode and
1091" other ftplugins provide these motions with some faults, e.g., not countable.
1092
1093vnoremap <silent> ]]  :<C-u>call <SID>JumpSectionV(']]')<Return>
1094vnoremap <silent> ][  :<C-u>call <SID>JumpSectionV('][')<Return>
1095vnoremap <silent> [[  :<C-u>call <SID>JumpSectionV('[[')<Return>
1096vnoremap <silent> []  :<C-u>call <SID>JumpSectionV('[]')<Return>
1097onoremap <silent> ]]  :<C-u>call <SID>JumpSectionO(']]')<Return>
1098onoremap <silent> ][  :<C-u>call <SID>JumpSectionO('][')<Return>
1099onoremap <silent> [[  :<C-u>call <SID>JumpSectionO('[[')<Return>
1100onoremap <silent> []  :<C-u>call <SID>JumpSectionO('[]')<Return>
1101
1102
1103
1104
1105" The <Space>  "{{{2
1106"
1107" Various hotkeys prefixed by <Space>.
1108
1109" to show <Space> in the bottom line.
1110map               <Space>    [Space]
1111
1112" fallback
1113noremap           [Space]    <Nop>
1114
1115
1116nnoremap <silent> [Space]/   :<C-u>nohlsearch<Return>
1117
1118nnoremap <silent> [Space]?   :<C-u>call <SID>HelpWindowClose()<Return>
1119
1120" append one character
1121nnoremap          [Space]A   A<C-r>=<SID>KeysToInsertOneCharacter()<Return>
1122nnoremap          [Space]a   a<C-r>=<SID>KeysToInsertOneCharacter()<Return>
1123
1124nnoremap <silent> [Space]e   :<C-u>setlocal enc? tenc? fenc? fencs?<Return>
1125nnoremap <silent> [Space]f   :<C-u>setlocal ft? fenc? ff?<Return>
1126
1127" insert one character
1128nnoremap          [Space]I   I<C-r>=<SID>KeysToInsertOneCharacter()<Return>
1129nnoremap          [Space]i   i<C-r>=<SID>KeysToInsertOneCharacter()<Return>
1130
1131nnoremap <silent> [Space]J   :<C-u>call <SID>JoinHere(1)<Return>
1132nnoremap <silent> [Space]gJ  :<C-u>call <SID>JoinHere(0)<Return>
1133
1134" unjoin  " BUGS: side effect - destroy the last inserted text (".).
1135nnoremap          [Space]j   i<Return><Esc>
1136
1137nnoremap <silent> [Space]m   :<C-u>marks<Return>
1138
1139nnoremap          [Space]o   <Nop>
1140nnoremap <silent> [Space]ob  :<C-u>call <SID>ToggleBell()<Return>
1141nnoremap <silent> [Space]ow  :<C-u>call <SID>ToggleOption('wrap')<Return>
1142
1143nnoremap <silent> [Space]q   :<C-u>help quickref<Return>
1144
1145nnoremap <silent> [Space]r   :<C-u>registers<Return>
1146
1147nnoremap          [Space]s   <Nop>
1148nnoremap <silent> [Space]s.  :<C-u>Source $MYVIMRC<Return>
1149nnoremap <silent> [Space]ss  :<C-u>Source %<Return>
1150
1151vnoremap <silent> [Space]s   :sort<Return>
1152
1153" for backward compatibility
1154nmap              [Space]w   [Space]ow
1155
1156" for other use.
1157noremap           [Space]x   <Nop>
1158
1159
1160
1161
1162" Windows  "{{{2
1163
1164" Synonyms for the default mappings, with single key strokes.
1165nmap     <Tab>    <C-i>
1166nmap     <S-Tab>  <Esc>i
1167nnoremap <C-i>    <C-w>w
1168nnoremap <Esc>i   <C-w>W
1169  " For other mappings (<Esc>{x} to <C-w>{x}).
1170nmap     <Esc>    <C-w>
1171
1172
1173for i in ['H', 'J', 'K', 'L']
1174  execute 'nnoremap <silent> <Esc>'.i
1175        \ ':<C-u>call <SID>MoveWindowThenEqualizeIfNecessary("'.i.'")<Return>'
1176endfor
1177unlet i
1178
1179
1180" This {lhs} overrides the default action (Move cursor to top-left window).
1181" But I rarely use its {lhs}s, so this mapping is not problematic.
1182nnoremap <silent> <C-w><C-t>
1183       \ :<C-u>call <SID>MoveWindowIntoTabPage(<SID>AskTabPageNumber())<Return>
1184function! s:AskTabPageNumber()
1185  echon 'Which tabpage to move this window into?  '
1186
1187  let c = nr2char(getchar())
1188  if c =~# '[0-9]'
1189    " Convert 0-origin number (typed by user) into 1-origin number (used by
1190    " Vim's internal functions).  See also 'tabline'.
1191    return 1 + char2nr(c) - char2nr('0')
1192  elseif c =~# "[\<C-c>\<Esc>]"
1193    return -1
1194  else
1195    return 0
1196  endif
1197endfunction
1198
1199
1200" like GNU Emacs' (scroll-other-window),
1201" but the target to scroll is the previous window.
1202for i in ['f', 'b', 'd', 'u', 'e', 'y']
1203  execute 'nnoremap <silent> <Esc><C-'.i.'>'
1204        \ ':<C-u>call <SID>ScrollOtherWindow("<Bslash><LT>C-'.i.'>")<Return>'
1205endfor
1206unlet i
1207
1208
1209
1210
1211" Misc.  "{{{2
1212
1213nnoremap <C-h>  :h<Space>
1214nnoremap <C-o>  :e<Space>
1215nnoremap <C-w>.  :e .<Return>
1216
1217
1218" Jump list
1219nnoremap <C-j>  <C-i>
1220nnoremap <C-k>  <C-o>
1221
1222
1223" Switch to the previously edited file (like Vz)
1224nnoremap <Esc>2  :e #<Return>
1225nmap <F2>  <Esc>2
1226
1227
1228" Too lazy to press Shift key.
1229noremap ;  :
1230noremap :  ;
1231
1232
1233" Disable some dangerous key.
1234nnoremap ZZ  <Nop>
1235nnoremap ZQ  <Nop>
1236
1237
1238" Use a backslash (\) to repeat last change.
1239" Since a dot (.) is used as <LocalLeader>.
1240nnoremap \  .
1241
1242
1243" Complete or indent.
1244inoremap <expr> <C-i>  (<SID>ShouldIndentRatherThanCompleteP()
1245                      \ ? '<C-i>'
1246                      \ : <SID>KeysToComplete())
1247
1248function! s:ShouldIndentRatherThanCompleteP()
1249  let m = match(getline('.'), '\S')
1250  return m == -1 || col('.')-1 <= m
1251endfunction
1252
1253
1254" Swap ` and ' -- I prefer ` to ' and ` is not easy to type.
1255" <SID>jump-default and <SID>jump-another are the name for these actions
1256" to use other places in this file.
1257map '  <SID>jump-default
1258map `  <SID>jump-another
1259noremap <SID>jump-default  `
1260noremap <SID>jump-another  '
1261
1262
1263" To be able to undo these types of deletion in Insert mode.
1264inoremap <C-w>  <C-g>u<C-w>
1265inoremap <C-u>  <C-g>u<C-u>
1266
1267
1268" Search the word nearest to the cursor in new window.
1269nnoremap <C-w>*  <C-w>s*
1270nnoremap <C-w>#  <C-g>s#
1271
1272
1273" Synonyms for <> and [], same as plugin surround.
1274onoremap aa  a>
1275onoremap ia  i>
1276vnoremap aa  a>
1277vnoremap ia  i>
1278
1279onoremap ar  a]
1280onoremap ir  i]
1281vnoremap ar  a]
1282vnoremap ir  i]
1283
1284
1285" Delete the content of the current line (not the line itself).
1286" BUGS: not repeatable.
1287" BUGS: the default behavior is overridden, but it's still available via "x".
1288nnoremap dl  0d$
1289
1290
1291" Like gv, but select the last changed text.
1292nnoremap gc  `[v`]
1293
1294
1295" Make I/A available in characterwise-visual and linewise-visual.
1296vnoremap <silent> I  :<C-u>call <SID>ForceBlockwiseVisual('I')<Return>
1297vnoremap <silent> A  :<C-u>call <SID>ForceBlockwiseVisual('A')<Return>
1298
1299function! s:ForceBlockwiseVisual(next_key)
1300  if visualmode() ==# 'V'
1301    execute "normal! `<0\<C-v>`>$"
1302  else
1303    execute "normal! `<\<C-v>`>"
1304  endif
1305  call feedkeys(a:next_key, 'n')
1306endfunction
1307
1308
1309" Start Insert mode with [count] blank lines.
1310" The default [count] is 0, so no blank line is inserted.
1311" (I prefer this behavior to the default behavior of [count]o/O
1312"  -- repeat the next insertion [count] times.)
1313nnoremap <silent> o  :<C-u>call <SID>StartInsertModeWithBlankLines('o')<Return>
1314nnoremap <silent> O  :<C-u>call <SID>StartInsertModeWithBlankLines('O')<Return>
1315
1316function! s:StartInsertModeWithBlankLines(command)
1317  " Do "[count]o<Esc>o" and so forth.
1318  " BUGS: In map-<expr>, v:count and v:count1 don't hold correct values.
1319  " FIXME: improper indenting in comments.
1320  " FIXME: imperfect repeating (blank lines will not be repeated).
1321
1322  if v:count != v:count1  " [count] is not specified?
1323    call feedkeys(a:command, 'n')
1324    return
1325  endif
1326
1327  let script = v:count . a:command . "\<Esc>"
1328  if a:command ==# 'O'
1329    let script .= "\<Down>" . v:count . "\<Up>"  " Adjust the cursor position.
1330  endif
1331
1332  execute 'normal!' script
1333  redraw
1334  Echo ModeMsg '-- INSERT (open) --'
1335  echohl None
1336  let c = nr2char(getchar())
1337  call feedkeys((c != "\<Esc>" ? a:command : 'A'), 'n')
1338  call feedkeys(c, 'n')
1339
1340  " to undo the next inserted text and the preceding blank lines in 1 step.
1341  undojoin
1342endfunction
1343
1344
1345" Search for the selected text.
1346vnoremap *  :<C-u>call <SID>SearchForTheSelectedText()<Return>
1347
1348  " FIXME: escape to search the selected text literaly.
1349function! s:SearchForTheSelectedText()
1350  let reg_u = @"
1351  let reg_0 = @0
1352
1353  normal! gvy
1354  let @/ = @0
1355  call histadd('/', @0)
1356  normal! n
1357
1358  let @0 = reg_0
1359  let @" = reg_u
1360endfunction
1361
1362
1363" Pseudo :suspend with automtic cd.
1364" Assumption: Use GNU screen.
1365" Assumption: There is a window with the title "another".
1366noremap <silent> <C-z>  :<C-u>call <SID>PseudoSuspendWithAutomaticCD()<Return>
1367
1368if !exists('s:gnu_screen_availablep')
1369  " Check the existence of $WINDOW to avoid using GNU screen in Vim on
1370  " a remote machine (for example, "screen -t remote ssh example.com").
1371  let s:gnu_screen_availablep = len($WINDOW) != 0
1372endif
1373function! s:PseudoSuspendWithAutomaticCD()
1374  if s:gnu_screen_availablep
1375    " \015 = <C-m>
1376    " To avoid adding the cd script into the command-line history,
1377    " there are extra leading whitespaces in the cd script.
1378    silent execute '!screen -X eval'
1379         \         '''select another'''
1380         \         '''stuff "  cd \"'.getcwd().'\"  \#\#,vim-auto-cd\015"'''
1381    redraw!
1382    let s:gnu_screen_availablep = (v:shell_error == 0)
1383  endif
1384
1385  if !s:gnu_screen_availablep
1386    suspend
1387  endif
1388endfunction
1389
1390
1391" Show the lines which match to the last search pattern.
1392nnoremap g/  :g/<Return>
1393vnoremap g/  :g/<Return>
1394
1395
1396
1397
1398
1399
1400
1401
1402" Filetypes  "{{{1
1403" Any filetype   "{{{2
1404
1405autocmd MyAutoCmd FileType *
1406      \ call <SID>FileType_any()
1407function! s:FileType_any()
1408  " To use my global mappings for section jumping,
1409  " remove buffer local mappings defined by ftplugin.
1410  silent! vunmap <buffer>  ]]
1411  silent! vunmap <buffer>  ][
1412  silent! vunmap <buffer>  []
1413  silent! vunmap <buffer>  [[
1414  silent! ounmap <buffer>  ]]
1415  silent! ounmap <buffer>  ][
1416  silent! ounmap <buffer>  []
1417  silent! ounmap <buffer>  [[
1418
1419  " Make omni completion available for all filetypes.
1420  if &l:omnifunc == ''
1421    setlocal omnifunc=syntaxcomplete#Complete
1422  endif
1423endfunction
1424
1425
1426" Fix 'fileencoding' to use 'encoding'
1427" if the buffer only contains 7-bit characters.
1428" Note that if the buffer is not 'modifiable',
1429" its 'fileencoding' cannot be changed, so that such buffers are skipped.
1430autocmd MyAutoCmd BufReadPost *
1431      \   if &modifiable && !search('[^\x00-\x7F]', 'cnw')
1432      \ |   setlocal fileencoding=
1433      \ | endif
1434
1435
1436" although this is not a filetype settings.
1437autocmd MyAutoCmd ColorScheme *
1438      \   call <SID>ExtendHighlight('Pmenu', 'Normal', 'cterm=underline')
1439      \ | call <SID>ExtendHighlight('PmenuSel', 'Search', 'cterm=underline')
1440      \ | call <SID>ExtendHighlight('PmenuSbar', 'Normal', 'cterm=reverse')
1441      \ | call <SID>ExtendHighlight('PmenuThumb', 'Search', '')
1442      \
1443      \ | highlight TabLineSel
1444      \             term=bold,reverse
1445      \             cterm=bold,underline ctermfg=lightgray ctermbg=237
1446      \ | highlight TabLine
1447      \             term=reverse
1448      \             cterm=NONE           ctermfg=lightgray ctermbg=237
1449      \ | highlight TabLineFill
1450      \             term=reverse
1451      \             cterm=NONE           ctermfg=lightgray ctermbg=237
1452doautocmd MyAutoCmd ColorScheme because-colorscheme-has-been-set-above.
1453
1454
1455
1456
1457" css  "{{{2
1458
1459autocmd MyAutoCmd FileType css
1460      \ call <SID>SetShortIndent()
1461
1462
1463
1464
1465" dosini (.ini)  "{{{2
1466
1467autocmd MyAutoCmd FileType dosini
1468      \ call <SID>FileType_dosini()
1469
1470function! s:FileType_dosini()
1471  nnoremap <buffer> <silent> ]]  :<C-u>call <SID>JumpSectionN('/^\[')<Return>
1472  nnoremap <buffer> <silent> ][  :<C-u>call <SID>JumpSectionN('/\n\[\@=')<CR>
1473  nnoremap <buffer> <silent> [[  :<C-u>call <SID>JumpSectionN('?^\[')<Return>
1474  nnoremap <buffer> <silent> []  :<C-u>call <SID>JumpSectionN('?\n\[\@=')<CR>
1475endfunction
1476
1477
1478
1479
1480" help  "{{{2
1481
1482autocmd MyAutoCmd FileType help
1483      \ call textobj#user#define('|[^| \t]*|', '', '', {
1484      \                            'move-to-next': '<buffer> gj',
1485      \                            'move-to-prev': '<buffer> gk',
1486      \                          })
1487
1488
1489
1490
1491" lua  "{{{2
1492
1493autocmd MyAutoCmd FileType lua
1494      \ call <SID>SetShortIndent()
1495
1496
1497
1498
1499" netrw  "{{{2
1500"
1501" Consider these buffers have "another" filetype=netrw.
1502
1503autocmd MyAutoCmd BufReadPost {dav,file,ftp,http,rcp,rsync,scp,sftp}://*
1504      \ setlocal bufhidden=hide
1505
1506
1507
1508
1509" python  "{{{2
1510
1511autocmd MyAutoCmd FileType python
1512      \   call <SID>SetShortIndent()
1513      \ | let python_highlight_numbers=1
1514      \ | let python_highlight_builtins=1
1515      \ | let python_highlight_space_errors=1
1516
1517
1518
1519
1520" ruby  "{{{2
1521
1522autocmd MyAutoCmd FileType ruby
1523      \   call <SID>SetShortIndent()
1524
1525
1526
1527
1528" sh  "{{{2
1529
1530autocmd MyAutoCmd FileType sh
1531      \ call <SID>SetShortIndent()
1532
1533" FIXME: use $SHELL.
1534let g:is_bash = 1
1535
1536
1537
1538
1539" tex  "{{{2
1540
1541autocmd MyAutoCmd FileType tex
1542      \ call <SID>SetShortIndent()
1543
1544
1545
1546
1547" vcsicommit  "{{{2
1548" 'filetype' for commit log buffers created by vcsi.
1549
1550autocmd MyAutoCmd FileType {vcsicommit,*.vcsicommit}
1551      \ setlocal comments=sr:*,mb:\ ,ex:NOT_DEFINED
1552
1553
1554
1555
1556" vim  "{{{2
1557
1558autocmd MyAutoCmd FileType vim
1559      \ call <SID>FileType_vim()
1560
1561function! s:FileType_vim()
1562  call <SID>SetShortIndent()
1563  let vim_indent_cont = &shiftwidth
1564
1565  iabbr <buffer> jf  function!()<Return>
1566                    \endfunction<Return>
1567                    \<Up><Up><End><Left><Left>
1568  iabbr <buffer> ji  if<Return>
1569                    \endif<Return>
1570                    \<Up><Up><End>
1571  iabbr <buffer> je  if<Return>
1572                    \else<Return>
1573                    \endif<Return>
1574                    \<Up><Up><Up><End>
1575  iabbr <buffer> jw  while<Return>
1576                    \endwhile<Return>
1577                    \<Up><Up><End>
1578
1579  " Fix the default syntax to properly highlight
1580  " autoload#function() and dictionary.function().
1581  syntax clear vimFunc
1582  syntax match vimFunc
1583    \ "\%([sS]:\|<[sS][iI][dD]>\|\<\%(\I\i*[#.]\)\+\)\=\I\i*\ze\s*("
1584    \ contains=vimFuncName,vimUserFunc,vimCommand,vimNotFunc,vimExecute
1585  syntax clear vimUserFunc
1586  syntax match vimUserFunc contained
1587    \ "\%([sS]:\|<[sS][iI][dD]>\|\<\%(\I\i*[#.]\)\+\)\i\+\|\<\u\i*\>\|\<if\>"
1588    \ contains=vimNotation,vimCommand
1589endfunction
1590
1591
1592
1593
1594" XML/SGML and other applications  "{{{2
1595
1596autocmd MyAutoCmd FileType html,xhtml,xml,xslt
1597      \ call <SID>FileType_xml()
1598
1599function! s:FileType_xml()
1600  call <SID>SetShortIndent()
1601
1602  " To deal with namespace prefixes and tag-name-including-hyphens.
1603  setlocal iskeyword+=45  " hyphen (-)
1604  setlocal iskeyword+=58  " colon (:)
1605
1606  " Support to input some parts of tags.
1607  inoremap <buffer> <LT>?  </
1608  imap     <buffer> ?<LT>  <LT>?
1609  inoremap <buffer> ?>  />
1610  imap     <buffer> >?  ?>
1611
1612  " Support to input some blocks.
1613  inoremap <buffer> <LT>!C  <LT>![CDATA[]]><Left><Left><Left>
1614  inoremap <buffer> <LT>#  <LT>!----><Left><Left><Left><C-r>=
1615                          \<SID>FileType_xml_comment_dispatch()
1616                          \<Return>
1617
1618  " Complete proper end-tags.
1619  " In the following description, {|} means the cursor position.
1620
1621    " Insert the end tag after the cursor.
1622    " Before: <code{|}
1623    " After:  <code>{|}</code>
1624  inoremap <buffer> <LT><LT>  ><LT>/<C-x><C-o><C-r>=
1625                             \<SID>KeysToStopInsertModeCompletion()
1626                             \<Return><C-o>F<LT>
1627
1628    " Wrap the cursor with the tag.
1629    " Before: <code{|}
1630    " After:  <code>
1631    "           {|}
1632    "         </code>
1633  inoremap <buffer> >>  ><Return>X<Return><LT>/<C-x><C-o><C-r>=
1634                       \<SID>KeysToStopInsertModeCompletion()
1635                       \<Return><C-o><Up><BS>
1636endfunction
1637
1638
1639function! s:FileType_xml_comment_dispatch()
1640  let c = nr2char(getchar())
1641  return get(s:FileType_xml_comment_data, c, c)
1642endfunction
1643let s:FileType_xml_comment_data = {
1644  \   "\<Space>": "\<Space>\<Space>\<Left>",
1645  \   "\<Return>": "\<Return>X\<Return>\<Up>\<End>\<BS>",
1646  \   '_': '',
1647  \   '-': '',
1648  \   '{': '{{'. "{\<Esc>",
1649  \   '}': '}}'. "}\<Esc>",
1650  \   '1': '{{'."{1\<Esc>",
1651  \   '2': '{{'."{2\<Esc>",
1652  \   '3': '{{'."{3\<Esc>",
1653  \   '4': '{{'."{4\<Esc>",
1654  \   '5': '{{'."{5\<Esc>",
1655  \   '6': '{{'."{6\<Esc>",
1656  \   '7': '{{'."{7\<Esc>",
1657  \   '8': '{{'."{8\<Esc>",
1658  \   '9': '{{'."{9\<Esc>",
1659  \   '!': '{{'."{1\<Esc>",
1660  \   '@': '{{'."{2\<Esc>",
1661  \   '#': '{{'."{3\<Esc>",
1662  \   '$': '{{'."{4\<Esc>",
1663  \   '%': '{{'."{5\<Esc>",
1664  \   '^': '{{'."{6\<Esc>",
1665  \   '&': '{{'."{7\<Esc>",
1666  \   '*': '{{'."{8\<Esc>",
1667  \   '(': '{{'."{9\<Esc>",
1668  \ }
1669
1670
1671
1672
1673
1674
1675
1676
1677" Plugins  "{{{1
1678" ku  "{{{2
1679
1680autocmd MyAutoCmd User KuLoaded  call <SID>on_KuLoaded()
1681function! s:on_KuLoaded()
1682  function! s:ku_type_any_action_my_cd(item)
1683    " FIXME: escape special characters.
1684    if isdirectory(a:item.word)
1685      execute 'CD' a:item.word
1686    elseif filereadable(a:item.word)
1687      execute 'CD' fnamemodify(a:item.word, ':h')
1688    else
1689      echo printf('Item %s (type: %s) is not a file or directory.',
1690         \        a:item.word, a:item._ku_type.name)
1691    endif
1692  endfunction
1693
1694  call ku#custom_action('*fallback*', 'cd',
1695     \                  function(s:SID_PREFIX() . 'ku_type_any_action_my_cd'))
1696endfunction
1697
1698
1699autocmd MyAutoCmd User KuBufferInitialize  call <SID>on_KuBufferInitialize()
1700function! s:on_KuBufferInitialize()
1701  call ku#default_key_mappings()
1702endfunction
1703
1704
1705nnoremap [Space]ka  :<C-u>Ku<Return>
1706nnoremap [Space]kb  :<C-u>Ku buffer<Return>
1707nnoremap [Space]kf  :<C-u>Ku file<Return>
1708
1709
1710
1711
1712" narrow  "{{{2
1713
1714noremap [Space]xn  :Narrow<Return>
1715noremap [Space]xw  :<C-u>Widen<Return>
1716
1717
1718
1719
1720" scratch  "{{{2
1721
1722nmap <Leader>s  <Plug>(scratch-open)
1723
1724
1725" I already use <C-m> for tag jumping.
1726" But I don't use it in the scratch buffer, so it should be overridden.
1727autocmd MyAutoCmd User PluginScratchInitializeAfter
1728      \ map <buffer> <C-m>  <Plug>(scratch-evaluate)
1729
1730
1731
1732
1733" surround  "{{{2
1734
1735" The default mapping ys for <Plug>Ysurround is not consistent with
1736" the default mappings of vi -- y is for yank.
1737nmap s  <Plug>Ysurround
1738nmap ss  <Plug>Yssurround
1739
1740" See also ~/.vim/plugin/surround_config.vim .
1741
1742
1743
1744
1745" vcsi  "{{{2
1746
1747let g:vcsi_diff_in_commit_logp = 1
1748
1749
1750
1751
1752" xml_autons  "{{{2
1753
1754let g:AutoXMLns_Dict = {}
1755let g:AutoXMLns_Dict['http://www.w3.org/2000/svg'] = 'svg11'
1756
1757
1758
1759
1760
1761
1762
1763
1764" Fin.  "{{{1
1765
1766if !exists('s:loaded_my_vimrc')
1767  let s:loaded_my_vimrc = 1
1768  " autocmd MyAutoCmd VimEnter *
1769  "   \ doautocmd MyAutoCmd User DelayedSettings
1770else
1771  " doautocmd MyAutoCmd User DelayedSettings
1772endif
1773
1774
1775
1776
1777set secure  " must be written at the last.  see :help 'secure'.
1778
1779
1780
1781
1782
1783
1784
1785
1786" __END__  "{{{1
1787" vim: expandtab softtabstop=2 shiftwidth=2
1788" vim: foldmethod=marker
Note: See TracBrowser for help on using the browser.