Vim freezes after pressing CTRL-U in insert mode. Any suggestions? - vim

Recently I figured out that pressing CTRL-U locks/freezes vim in insert mode. The only CTRL-C helps to get it back. Terminal version and gvim have the same behaviour. Only in virtual console mode (CTRL-ALT-F1) the C-U works properly. Here is my .vimrc:
" This must be first, because it changes other options as a side effect.
set nocompatible
" Don't use Ex mode, use Q for formatting
map Q gq
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
imap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" Options
" =========================================================
colorscheme gruvbox
let g:gruvbox_contrast_dark = 'normal'
set background=dark
set t_Co=256
" spelling
set spell spelllang=ru_yo,en_us
set spellsuggest=10
set keymap=russian-jcukenwin
set iminsert=0
set imsearch=0
" backup
set writebackup " backup on write
set nobackup " keep a backup file
set undofile " keep an undo file
set swapfile " keep a swap file
" directories
" set autochdir
set backupdir=~/.vim/tmp/backup//
set undodir=~/.vim/tmp/undo//
set directory=~/.vim/tmp/swp//
" active editor
set nowrap
set nu
set backspace=indent,eol,start " backspacing over everything in im
set ruler " show the cursor position all the time
" cmd
set history=50 " keep 50 lines of command line history
set showcmd " display incomplete commands
" search
set ignorecase " ignore case using a search pattern.
set smartcase " override 'ignorecase' when pattern has upper case.
set incsearch " do incremental searching
" tab
" set tabstop=2 shiftwidth=2 noexpandtab " n-column tab
set tabstop=2 shiftwidth=2 expandtab " n-space character tab
" window
set splitbelow
set splitright
set winminheight=0
" folding settings
set foldmethod=indent " fold based on indent
set foldnestmax=10 " deepest fold is 10 levels
set nofoldenable " dont fold by default
set foldlevel=1 " this is just what i use
" invisible chars
set list " don't show invisible characters.
set listchars=tab:.\ ,trail:~,extends:>,precedes:<,eol:\ "¬
set nohidden " unload buffer when no longer shown in window.
set laststatus=2 " Display vim-lightline
" indent, cursor, width
set cursorline " Highlight the screen line of the cursor.
set colorcolumn=72 " Columan to highlight.
set autoindent " Automatically set the indent of a new line.
set textwidth=80
set completeopt=menuone,longest ",preview prevents immediate complete
" tab
set switchbuf=usetab " use window or tabs to find selected buff
" windows
set noea " fix window size after closing others
" sessions (^blank,help)
set sessionoptions=buffers,curdir,folds,help,options,tabpages,winsize
" Autocmd
" =========================================================
au BufReadPost *.tmpl set syntax=html
" Mappings
" =========================================================
" source and update file
nmap <F5> :so ~/.vimrc<CR>
nmap <leader>e :e<CR>
" copy filepath
nmap <silent> <F4> :let #+=expand("%:p")<CR>
" buffers
nmap <F2> :ls<CR>:b
nmap <c-w><c-t> :tabnew<CR>
nmap <c-w><c-e> :tab sp<CR>
nmap <c-w><c-b>n :tabnew %<Bar>:bNext<Bar><CR>
nmap <c-w><c-b><c-b> :bw %<CR>
nmap <c-w><c-b>w :bw! %<CR>
nmap <c-w><c-b>a :tab ball<CR>
" sessions
nmap <silent> <leader>ss :wa<Bar>exe "mksession! " . v:this_session<CR>
nmap <leader>sr :so .session.vim<CR>
nmap <leader>sc :msk .session.vim<CR>
" quit
nmap <leader>qd :qa!<CR> " quit & discard changes
nmap <leader>qq :xa<CR> " quit & write if changed
nmap <leader>qs <leader>s<leader>qd
" new vertical window
nmap <c-w><c-n> :vnew<CR>
" tab movement and switching
nmap <c-l> :tabnext<CR>
nmap <c-h> :tabprevious<CR>
nmap <c-j> :tabmove -1<CR>
nmap <c-k> :tabmove +1<CR>
" search and replace
nmap <leader>c :let #/=""<CR>
" trailing spaces
nmap <silent> <leader>dt mq:%s/\s\+$//e<Bar>:let #/=""<CR>`q:delm q<CR>
" update, write
nmap <leader>u <leader>dt:update<CR>
nmap <leader>w <leader>dt:write<CR>
cmap w!! w !sudo tee > /dev/null %
" window manipulation
nmap <c-w>== :set ead=ver ea noea<CR>
nmap <c-w>=- :set ead=hor ea noea<CR>
" shell
nmap <space> :sh<CR>
" Plugins
" =========================================================
call plug#begin('~/.vim/plugged')
Plug 'fatih/vim-go'
Plug 'mattn/emmet-vim'
Plug 'itchyny/lightline.vim'
Plug 'sheerun/vim-polyglot'
Plug 'scrooloose/syntastic'
call plug#end()
" Lightline.vim
let g:lightline = {
\ 'colorscheme': 'jellybeans',
\ 'active': {
\ 'left': [ [ 'mode', 'paste' ],
\ [ 'fugitive', 'filename', 'readonly', 'modified' ] ] },
\}
" Syntastic
" let g:syntastic_sass_checkers = ["sassc"]
" Netrw
nmap <leader>tr <Plug>NetrwRefresh
map <leader>tf :Ntree<CR>
map <silent> <leader>f <S-CR>
let g:netrw_liststyle=3
let g:netrw_banner=0
let g:netrw_mousemaps=0
let g:netrw_chgwin=1 " open files in left window by default
" let g:netrw_keepdir=0
" let g:netrw_silent= 1
" fire up the sidebar
nmap <silent> <C-#> :rightbelow 25vs<CR>:e .<CR>
" vim-go
" disable fmt on save
let g:go_fmt_autosave = 0
" format with goimports instead of gofmt
let g:go_fmt_command = "goimports"
" additional highlight
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_structs = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
" YouCompleteMe
let g:ycm_confirm_extra_conf=0
let g:ycm_autoclose_preview_window_after_completion=1
let g:ycm_min_num_of_chars_for_completion=1
" Emmet-vim
let g:user_emmet_leader_key='<c-m>'
" Formats the statusline
" set statusline=%f " file name
" set statusline+=[%{strlen(&fenc)?&fenc:'none'}, "file encoding
" set statusline+=%{&ff}] "file format
" set statusline+=%y "filetype
" set statusline+=%h "help file flag
" set statusline+=%m "modified flag
" set statusline+=%r "read only flag
"
" set statusline+=\ %= " align left
" set statusline+=Line:%l/%L[%p%%] " line X of Y [percent of file]
" set statusline+=\ Col:%c " current column
" set statusline+=\ Buf:%n " Buffer number
" set statusline+=\ [%b][0x%B]\ " ASCII and byte code under cursor
" Miscellaneous
" =========================================================
nmap <leader>t :call <SID>SynStack()<CR>
function! <SID>SynStack()
if !exists("*synstack")
return
endif
echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc
:set guioptions-=m "remove menu bar
:set guioptions-=T "remove toolbar
:set guioptions-=r "remove right-hand scroll bar
:set guioptions-=L "remove left-hand scroll bar
It's quite big, but the only one mapping related with C-U: imap <C-U> <C-G>u<C-U>. What's going on?

I've copied your vimrc and used it. Same effect. It's this line:
imap <C-U> <C-G>u<C-U>
which apparently causes a recursion. When commented out, <C-u> erases back to start-of-line.

Given the problem that #Jens found... you, Timur, might want to try
inoremap <c-u> <c-g>u<c-u>
That will prevent remapping (ie. an infinite recursion) from taking place.

Related

Vim substitutes only first occurence in line (global tag not working) [duplicate]

I've been making a lot of changes to my .vimrc lately, and somewhere along the line I've introduced an undesirable feature. When performing a substitution command where the search token appears more than once per line, only the first token is changed (although the remaining tokens are highlighted as a result of the substitution). I have seen a few posts here about how to enable this behavior on a case-by-case basis, but I have yet to see something about what would cause this to be the default behavior or how to disable it. If anyone has any ideas, they would be appreciated.
For reference, my .vimrc (https://github.com/chpatton013/dotfiles/blob/master/vim/.vimrc):
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Autocommands
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Reread configuration of Vim if .vimrc is saved
augroup VimConfig
au!
au BufWritePost ~/.vimrc so ~/.vimrc
au BufWritePost _vimrc so ~/_vimrc
au BufWritePost vimrc so ~/.vimrc
augroup END
" Set colorcolumn to 80 chars, or (if not supported) highlight lines > 80 chars
augroup ColorColumnConfig
au!
if exists('+colorcolumn')
au BufWinEnter * set colorcolumn=80
au BufWinEnter * hi ColorColumn ctermbg=lightgrey guibg=lightgrey
else
au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\%>80v.\+', -1)
endif
augroup END
" Highlight over-length characters and trailing whitespace
augroup ExtraCharacters
au!
au ColorScheme * highlight ExtraWhitespace ctermbg=Red guibg=Red
au ColorScheme * highlight OverLength ctermbg=red ctermfg=white guibg=red guifg=white
au BufWinEnter * let w:whitespace_match_number =
\ matchadd('ExtraWhitespace', '\s\+$')
au BufWinEnter * call matchadd('OverLength',
\ '\(^\(\s\)\{-}\(*\|//\|/\*\)\{1}\(.\)*\(\%81v\)\)\#<=\(.\)\{1,}$')
au InsertEnter * call s:ToggleWhitespaceMatch('i')
au InsertLeave * call s:ToggleWhitespaceMatch('n')
augroup END
" Resize splits on window resize
au VimResized * exe "normal! \<c-w>="
" Restore the cursor when we can.
au BufWinEnter * call RestoreCursor()
" Change the statusline color based on current mode
augroup StatuslineColor
au!
au InsertEnter * call InsertStatuslineColor(v:insertmode)
au InsertLeave * hi statusline ctermfg=cyan ctermbg=black guifg=cyan guibg=black
augroup END
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugins
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pathogen - https://github.com/tpope/vim-pathogen
runtime bundle/vim-pathogen/autoload/pathogen.vim
call pathogen#infect()
call pathogen#helptags()
" Easymotion - https://github.com/Lokaltog/vim-easymotion/
" This is so much more convenient
let g:EasyMotion_leader_key=',m'
" Neocomplcache - https://github.com/Shougo/neocomplcache
" Enable at startup.
let g:neocomplcache_enable_at_startup=1
" Only display 'n' items in the list.
let g:neocomplcache_max_list=5
" Do not auto-select the first candidate.
let g:neocomplcache_enable_auto_select=1
" Do not try to match until 'n' characters have been typed
let g:neocomplcache_auto_completion_start_length=3
" Do not try to match to anything less than 'n' characters
let g:neocomplcache_min_keyword_length=6
let g:neocomplcache_min_syntax_length=6
" Only consider case if an uppercase character has been typed
let g:neocomplcache_enable_smart_case=1
" Syntastic - https://github.com/scrooloose/syntastic/
" Commands:
" :Errors // pop up location list and display errors
" :SyntasticToggleMode // toggles between active and passive mode
" :SyntasticCheck // forces a syntax check in passive mode
" check for syntax errors on file open
let g:syntastic_check_on_open=1
" echo errors to the command window
let g:syntastic_echo_current_error=1
" mark lines with errors and warnings
let g:syntastic_enable_signs=1
" set sign symbols
let g:syntastic_error_symbol='E>'
let g:syntastic_warning_symbol='W>'
let g:syntastic_style_error_symbol='S>'
let g:syntastic_style_warning_symbol='s>'
" open error balloons when moused over erroneous lines
let g:syntastic_enable_balloons=1
" customize Syntastic statusline
let g:syntastic_stl_format = '[%E{E: %fe #%e}%B{, }%W{W: %fw #%w}]'
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Strip trailing whitespace
function! <SID>StripTrailingWhitespaces()
let _s=#/
let l = line(".")
let c = col(".")
%s/\s\+$//e
let #/=_s
call cursor(l, c)
endfunction
" Toggle match of trailing whitespace
function! s:ToggleWhitespaceMatch(mode)
let pattern = (a:mode == 'i') ? '\s\+\%#\#<!$' : '\s\+$'
if exists('w:whitespace_match_number')
call matchdelete(w:whitespace_match_number)
call matchadd('ExtraWhitespace', pattern, 10, w:whitespace_match_number)
else
" Something went wrong, try to be graceful.
let w:whitespace_match_number = matchadd('ExtraWhitespace', pattern)
endif
endfunction
" Restore the cursor when we can
function! RestoreCursor()
if line("'\"") <= line("$")
normal! g`"
normal! zz
endif
endfunction
" Change the statusline color based on current mode
function! InsertStatuslineColor(mode)
if a:mode == 'i'
hi statusline ctermfg=darkmagenta ctermbg=black guifg=darkmagenta guibg=black
elseif a:mode == 'r'
hi statusline ctermfg=darkgreen ctermbg=black guifg=darkgreen guibg=black
else
hi statusline ctermfg=darkred ctermbg=black guifg=darkred guibg=black
endif
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Configuration customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" gui configuration (do not move from top of configurations)
set guioptions=am
set guifont=Consolas:h9
set encoding=utf-8
set fileencoding=utf-8
set nocompatible " No compatibility with vi.
filetype on " Recognize syntax by file extension.
filetype indent on " Check for indent file.
filetype plugin on " Allow plugins to be loaded by file type.
behave xterm " Maintain keybindings across enviornments
set autowrite " Write before executing the 'make' command.
set background=dark " Background light, so foreground not bold.
set backspace=indent,eol,start " Allow <BS> to go over indents, eol, and start of insert
set expandtab " Expand tabs with spaces.
set nofoldenable " Disable folds; toggle with zi.
set gdefault " Assume :s uses /g.
set hidden " Use hidden buffers so unsaved buffers can go to the background
set history=500 " Set number of lines for vim to remember
set hlsearch " Highlight all search matches
set ignorecase " Ignore case in regular expressions
set incsearch " Immediately highlight search matches.
set laststatus=2 " Show status line even where there is only one window
set lazyredraw " Redraw faster
set linespace=-1 " Bring lines closer together vertically
set modeline " Check for a modeline.
set noerrorbells " No beeps on errors.
set nohls " Don't highlight all regex matches.
set nowrap " Don't soft wrap.
set number " Display line numbers.
set path=~/Code/** " Set default path
set scrolloff=5 " Keep min of 'n' lines above/below cursor.
set shellslash " Use forward slashes regardless of OS
set shiftwidth=3 " >> and << shift 3 spaces.
set showcmd " Show partial commands in the status line.
set showmatch " Show matching () {} etc..
set showmode " Show current mode.
set sidescrolloff=10 " Keep min of 'n' columns right/left cursor.
set smartcase " Searches are case-sensitive if caps used.
set smarttab " Tabs and backspaces at the start of a line indent the line one level
set smartindent " Maintains most indentation and adds extra level when nesting
set softtabstop=3 " See spaces as tabs.
set splitright splitbelow " Open splits below and to the right
set synmaxcol=160 " Only matches syntax on first 'n' columns of each line ( faster)
set tabstop=3 " <Tab> move three characters
set textwidth=79 " Hard wrap at 79 characters
set title " Set the console title
set viminfo='20,\"500,% " Adjust viminfo contents
set virtualedit=block " Allow the cursor to go where it should not
set wildmenu " Tab completion opens a Tab- and arrow-navigable menu
set wildmode=longest,full " Tab completion works like bash.
set wrapscan " Searching wraps to start of file when end is reached
" Define statusline
set statusline=%f " Relative file path
set statusline+=%(\ [%M%R%H%W]%) " File flags (mod, RO, help, preview)
set statusline+=%(\ %<%) " Start truncation
set statusline+=%(\ %{fugitive#statusline()}%) " Git branch name (if applicable)
set statusline+=%= " Begin right justification
set statusline+=%#warningmsg# " Start warning highlighting
set statusline+=%(\ %{SyntasticStatuslineFlag()}%) " Show Syntastic errors and warnings
set statusline+=%* " End warning highlighting
set statusline+=\ [line\ %l\/%L,\ col\ %c%V,\ %p%%] " Line and column numbers and percentage through file
" Text formatting settings
" t: Auto-wrap text using textwidth. (default)
" c: Auto-wrap comments; insert comment leader. (default)
" q: Allow formatting of comments with "gq". (default)
" r: Insert comment leader after hitting <Enter>.
" o: Insert comment leader after hitting 'o' or 'O' in command mode.
" n: Auto-format lists, wrapping to text *after* the list bullet char.
" l: Don't auto-wrap if a line is already longer than textwidth.
set formatoptions+=ronl
" Enable mouse scrolling in selected modes
" a: All
" c: Command
" i: Insert
" n: Normal
" v: Visual
set mouse=a
" Set scrolling to be single-line
"map <MouseDown> <C-Y>
"map <S-MouseDown> <C-U>
"map <MouseUp> <C-E>
"map <S-MouseUp> <C-D>
" Highlighting
syntax enable
set t_Co=16
colorscheme solarized
" Configuration variables
let loaded_matchparen=0 " do automatic bracket highlighting.
let mapleader="," " Use , instead of \ for the map leader.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Command mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Make y behave like all other capitals
map Y y$
" Make Q reformat text.
noremap Q gq
" Toggle paste mode.
noremap <Leader>p :set paste!<CR>
" Open the file under the cursor in a new tab.
noremap <Leader>ot <C-W>gf
" Toggle highlighting of the last search.
noremap <Leader>h :set hlsearch! hlsearch?<CR>
" Open a scratch buffer.
noremap <Leader>s :Scratch<CR>
" Improve movement on wrapped lines
nnoremap j gj
nnoremap k gk
" Keep search pattern at the center of the screen
nnoremap <silent> n nzz
nnoremap <silent> N Nzz
nnoremap <silent> * *zz
nnoremap <silent> # #zz
nnoremap <silent> g* g*zz
nnoremap <silent> g# g#zz
" Use C-hjkl in to change windows
nnoremap <C-h> <C-w><Left>
nnoremap <C-j> <C-w><Down>
nnoremap <C-k> <C-w><Up>
nnoremap <C-l> <C-w><Right>
" Strip trailing whitespace
nnoremap <silent> <leader>W :call <SID>StripTrailingWhitespaces()<CR>
" Allow easy toggling of spaces / tabs mode
nnoremap <C-t><C-t> :set invexpandtab<CR>
" Create simple toggles for line numbers, paste mode, and word wrap.
nnoremap <C-N><C-N> :set invnumber<CR>
nnoremap <C-p><C-p> :set invpaste<CR>
nnoremap <C-w><C-w> :set invwrap<CR>
" Folding stuff
nnoremap <C-o> zo
nnoremap <C-c> zc
nnoremap <C-O> zO
nnoremap <C-O><C-O> zR
set foldmethod=indent
" Open file for class name under cursor
nnoremap <C-i> yiw:find <C-R>".php<CR>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Insert mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set up dictionary completion.
set dictionary+=~/.vim/dictionary/english-freq
set complete+=k
" Smash Esc
inoremap jk <Esc>
inoremap kj <Esc>
" Use hjkl in insert mode
imap <C-h> <Left>
imap <C-j> <Down>
imap <C-k> <Up>
imap <C-l> <Right>
" Make C-s write the buffer and return to insert mode when applicable
inoremap <C-s> <C-O>:w<CR>
nnoremap <C-s> :w<CR>
" auto-insert second braces and parynthesis
inoremap {<CR> {<CR>}<Esc>O
inoremap ({<CR> ({<CR>});<Esc>O
inoremap <<<<CR> <<<EOT<CR>EOT;<Esc>O<C-TAB><C-TAB><C-TAB>
set cpoptions+=$ "show dollar sign at end of text to be changed
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Visual mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" reselect visual block after indent/outdent
xnoremap < <gv
xnoremap > >gvo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
And the following plugins make up the contents of my bundle directory (https://github.com/chpatton013/dotfiles/tree/master/vim/.vim/bundle):
neocomplcache/
syntastic/
vim-abolish/
vim-colors-solarized/
vim-commentary/
vim-easymotion/
vim-fugitive/
vim-pathogen/
vim-repeat/
vim-surround/
Finally, I have disabled all plugins, but the issue was not resolved. I removed my .vimrc and the issue was resolved (so it is not some global setting outside of my control). I disabled several individual settings in my .vimrc, but I could not seem to eliminate the problem. Eventually, I got tired of playing whack-a-mole and decided to turn to the community. Any ideas?
EDIT: As an example,
I use the command :%s/foo/foobar/g
The text foo bar foo is converted to foobar bar foo
EDIT: Resolved by pb2q. set gdefault inverts the behavior of /g.
The substitute command accepts the switch g, for global, which causes the substitution to be made on all matches on the line:
:s/regex/replacement/g
The default is that only the first occurrence of the match is substituted, but there's a setting to switch the default to global: gdefault. So set gdefault in your vimrc if you want this as the default behavior. Try it out first in the current vim session with :set gdefault.
Note that when you set gdefault, this not only makes g the default behavior, but it changes the usage of the g flag so that using /g at the end of a substitute will cause the substitution to be made only once.
See: :help gdefault.

How to copy few lines of text from a vim editor to paste it somewhere on other editor?

I have started using vim editor from last 2 weeks and one problem the I face is I can't copy few bunch of codes to other editors or somewhere else however i can copy something to vim editor.
Below is my .vimrc file :-
" Automatic reloading of .vimrc
autocmd! bufwritepost .vimrc source %
" Better copy & paste
" When you want to paste large blocks of code into vim, press F2 before you
" paste. At the bottom you should see ``-- INSERT (paste) --``.
set pastetoggle=<F2>
set clipboard=unnamed
" Mouse and backspace
set mouse=a " on OSX press ALT and click
set bs=2 " make backspace behave like normal again
" Rebind <Leader> key
" I like to have it here becuase it is easier to reach than the default and
" it is next to ``m`` and ``n`` which I use for navigating between tabs.
let mapleader = ","
" Bind nohl
" Removes highlight of your last search
" ``<C>`` stands for ``CTRL`` and therefore ``<C-n>`` stands for ``CTRL+n``
noremap <C-n> :nohl<CR>
vnoremap <C-n> :nohl<CR>
inoremap <C-n> :nohl<CR>
" Quicksave command
noremap <C-Z> :update<CR>
vnoremap <C-Z> <C-C>:update<CR>
inoremap <C-Z> <C-O>:update<CR>
" Quick quit command
noremap <Leader>e :quit<CR> " Quit current window
noremap <Leader>E :qa!<CR> " Quit all windows
" bind Ctrl+<movement> keys to move around the windows, instead of using Ctrl+w + <movement>
" Every unnecessary keystroke that can be saved is good for your health :)
map <c-j> <c-w>j
map <c-k> <c-w>k
map <c-l> <c-w>l
map <c-h> <c-w>h
" easier moving between tabs
map <Leader>n <esc>:tabprevious<CR>
map <Leader>m <esc>:tabnext<CR>
" map sort function to a key
vnoremap <Leader>s :sort<CR>
" easier moving of code blocks
" Try to go into visual mode (v), thenselect several lines of code here and
" then press ``>`` several times.
vnoremap < <gv " better indentation
vnoremap > >gv " better indentation
" Show whitespace
" MUST be inserted BEFORE the colorscheme command
autocmd ColorScheme * highlight ExtraWhitespace ctermbg=red guibg=red
au InsertLeave * match ExtraWhitespace /\s\+$/
" Color scheme
" mkdir -p ~/.vim/colors && cd ~/.vim/colors
" wget -O wombat256mod.vim http://www.vim.org/scripts/download_script.php?src_id=13400
set t_Co=256
color wombat256mod
" Enable syntax highlighting
" You need to reload this file for the change to apply
filetype off
filetype plugin indent on
syntax on
" Showing line numbers and length
set number " show line numbers
set tw=79 " width of document (used by gd)
set nowrap " don't automatically wrap on load
set fo-=t " don't automatically wrap text when typing
set colorcolumn=80
highlight ColorColumn ctermbg=233
" easier formatting of paragraphs
vmap Q gq
nmap Q gqap
" Useful settings
set history=700
set undolevels=700
" Real programmers don't use TABs but spaces
set tabstop=4
set softtabstop=4
set shiftwidth=4
set shiftround
set expandtab
" Make search case insensitive
set hlsearch
set incsearch
set ignorecase
set smartcase
" Disable stupid backup and swap files - they trigger too many events
" for file system watchers
set nobackup
set nowritebackup
set noswapfile
" Setup Pathogen to manage your plugins
" mkdir -p ~/.vim/autoload ~/.vim/bundle
" curl -so ~/.vim/autoload/pathogen.vim https://raw.githubusercontent.com/tpope/vim-pathogen/master/autoload/pathogen.vim
" Now you can install any plugin into a .vim/bundle/plugin-name/ folder
call pathogen#infect()
" ============================================================================
" Python IDE Setup
" ============================================================================
" Settings for vim-powerline
" cd ~/.vim/bundle
" git clone git://github.com/Lokaltog/vim-powerline.git
set laststatus=2
" Settings for ctrlp
" cd ~/.vim/bundle
" git clone https://github.com/kien/ctrlp.vim.git
let g:ctrlp_max_height = 30
set wildignore+=*.pyc
set wildignore+=*_build/*
set wildignore+=*/coverage/*
" Settings for python-mode
" Note: I'm no longer using this. Leave this commented out
" and uncomment the part about jedi-vim instead
" cd ~/.vim/bundle
" git clone https://github.com/klen/python-mode
"" map <Leader>g :call RopeGotoDefinition()<CR>
""let ropevim_enable_shortcuts = 1
""let g:pymode_rope_goto_def_newwin = "vnew"
""let g:pymode_rope_extended_complete = 1
""let g:pymode_breakpoint = 0
""let g:pymode_syntax = 1
""let g:pymode_syntax_builtin_objs = 0
""let g:pymode_syntax_builtin_funcs = 0
""map <Leader>b Oimport ipdb; ipdb.set_trace() # BREAKPOINT<C-c>
" Settings for jedi-vim
" cd ~/.vim/bundle
""git clone git://github.com/davidhalter/jedi-vim.git
let g:jedi#usages_command = "<leader>z"
let g:jedi#popup_on_dot = 0
let g:jedi#popup_select_first = 0
map <Leader>b Oimport ipdb; ipdb.set_trace() # BREAKPOINT<C-c>
" Better navigating through omnicomplete option list
" See http://stackoverflow.com/questions/2170023/how-to-map-keys-for-popup-menu-in-vim
set completeopt=longest,menuone
function! OmniPopup(action)
if pumvisible()
if a:action == 'j'
return "\<C-N>"
elseif a:action == 'k'
return "\<C-P>"
endif
endif
return a:action
endfunction
inoremap <silent><C-j> <C-R>=OmniPopup('j')<CR>
inoremap <silent><C-k> <C-R>=OmniPopup('k')<CR>
" Python folding
" mkdir -p ~/.vim/ftplugin
" wget -O ~/.vim/ftplugin/python_editing.vim http://www.vim.org/scripts/download_script.php?src_id=5492
set nofoldenable
I added this to enable copy and paste things with use if F2
set pastetoggle=<F2>
set clipboard=unnamed
I want to enable that feature. Please help
Thank's
Normally, Vim yanks (copies) to it's own internal register.
If you want to yank to a specific register, prepend your yank operation with a denotion of that register.
For example to yank a line to register x use
"xyy
To yank your visual selection to register z, use
"zy
The global clipboard is in register * or register + depending on your system
So to yank to one of these registers, replace x and z with * or +
Similarly, to put (paste) from the global clipboard, use
"*p
or
"+p

Reloading .vimrc in autocmd breaks Powerline

I know this has already been discussed, but the proposed solution is not working for me.
I have this in my .vimrc:
autocmd! BufWritePost .vimrc nested source $MYVIMRC
Since I read that the correct way to source .vimrc inside an autocmd is using autocmd-nested.
Still, everytime I save it I lose colors in powerline
Edit:
here is my .vimrc
filetype off
set rtp+=~/.vim/vundle.git/
call vundle#rc()
set rtp+=~/.vim/bundle/powerline/powerline/bindings/vim
"set statusline+=%#warningmsg#
"set statusline+=%{SyntasticStatuslineFlag()}
"set statusline+=%*
let g:syntastic_enable_signs=1
let g:syntastic_auto_loc_list=1
let g:ctrlp_working_path_mode = 'ra'
" Bundles
"
" original repos on github
"Bundle 'vim-scripts/taglist.vim'
Bundle 'majutsushi/tagbar'
"Bundle 'joonty/vim-phpqa.git'
"Bundle 'joonty/vim-phpunitqf'
Bundle 'joonty/vdebug'
" Php
Bundle 'sumpygump/php-documentor-vim'
Bundle 'sophacles/vim-processing'
Bundle 'nelstrom/vim-visual-star-search'
Bundle 'Lokaltog/powerline'
Bundle 'spolu/dwm.vim'
Bundle 'tpope/vim-unimpaired'
Bundle 'airblade/vim-gitgutter'
Bundle 'kien/ctrlp.vim'
Bundle 'wikitopian/hardmode'
Bundle 'tpope/vim-fugitive'
Bundle 'sbl/scvim'
Bundle 'vim-scripts/bufexplorer'
Bundle 'aaronbieber/quicktask'
Bundle 'vim-scripts/The-NERD-Commenter'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-surround'
Bundle 'vim-scripts/HTML-AutoCloseTag'
Bundle 'scrooloose/nerdtree'
"Bundle 'scrooloose/syntastic'
Bundle 'vim-scripts/css_color.vim'
" Color schemes
Bundle 'tomasr/molokai'
Bundle 'altercation/vim-colors-solarized'
Bundle 'vim-scripts/OOP-javascript-indentation'
let g:gitgutter_enabled = 0
set nocompatible "Don't be compatible with vi
" Enable filetype plugin
filetype indent on
filetype plugin on
" Set to auto read when a file is changed from the outside
set autoread
set t_Co=16
set background=dark
set number "Show line numbering
set numberwidth=1 "Use 1 col + 1 space for numbers
" With a map leader it's possible to do extra key combinations
let mapleader = ","
let g:mapleader = ","
" Toggle NERDTree
map <leader>n :NERDTreeToggle<CR>
set backupdir=~/.vim/backup " where to put backup files
set directory=~/.vim/temp " where to put swap files
" Fast saving
nmap <leader>w :w!<cr>
" Fast editing of the .vimrc
map <leader>e :e $MYVIMRC<cr>
" When .vimrc is edited, reload it
augroup MyAutoCmd
autocmd!
augroup END
autocmd MyAutoCmd BufWritePost $MYVIMRC nested source $MYVIMRC
"au! BufWritePost .vimrc nested source %
set title
" Remap esc key
inoremap jk <esc>
" work more logically with wrapped lines
noremap j gj
noremap k gk
set smartcase " search case sensitive if caps on
set showcmd " Display what command is waiting for an operator
autocmd BufNewFile,BufRead /*apache* setfiletype apache
autocmd BufNewFile,BufRead /*lighttpd*.conf setfiletype lighty
autocmd BufNewFile,BufRead {.,_}vimrc set foldmethod=marker
" PhpDocumentor
au BufRead,BufNewFile *.php inoremap <buffer> <leader>p :call PhpDoc()<CR>
au BufRead,BufNewFile *.php nnoremap <buffer> <leader>p :call PhpDoc()<CR>
au BufRead,BufNewFile *.php vnoremap <buffer> <leader>p :call PhpDocRange()<CR>
" Nicer highlighting of completion popup
highlight Pmenu guibg=brown gui=bold
set scrolloff=7 "Set 7 lines to the cursors when moving vertical
set wildmenu "Autocomplete features in the status bar
set ruler "Always show current position
set cmdheight=2 "The commandbar height
set hidden "Change buffer without saving
" Backspae config
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
set ignorecase "Search is case insensitive
set hlsearch "Highlight matches to the search
set incsearch "Show best match so far
set magic "Set magic on for regular expressions
set showmatch "Show matching bracets when text indicator is over them
set mat=2 "How many tenths of a second to blink
" No sound on errors
set noerrorbells
set novisualbell
set t_vb=
" Colors and fonts {{{1
set term=screen-256color
syntax enable "Enable syntax hl
syntax on "Enable syntax hl
"colorscheme molokai
"let g:solarized_termcolors=256
colorscheme solarized
set guifont=Envy\ Code\ R\ for\ Powerline
set encoding=utf-8
filetype plugin on
"set guifont=Inconsolata\ for\ Powerline\
let g:Powerline_symbols="fancy"
" Text, tab and indent related {{{1
set expandtab "Transform tabs into spaces
set shiftwidth=4 "sw 4 spaces (used on auto indent)
set shiftwidth=4 "sw 4 spaces (used on auto indent)
set tabstop=4 "4 spaces as a tab for bs/del
set smarttab
set wrap linebreak tw=80 wm=0 "Wrap lines
set ai "Auto indent
set si "Smart indent
" }}}1
" Moving around, tabs and buffers {{{1
" Move to previous and next buffer
:nmap <C-n> :bnext<CR>
:nmap <C-p> :bprev<CR>
" Map space to / (search) and c-space to ? (backwards search)
map <space> /
map <c-space> ?
map <silent> <leader><cr> :noh<cr>
" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Mappings to access buffers (don't use "\p" because a
" delay before pressing "p" would accidentally paste).
" ,l : list buffers
" ,b ,f ,g : go back/forward/last-used
" ,1 ,2 ,3 : go to buffer 1/2/3 etc
nnoremap <Leader>l :ls<CR>
nnoremap <Leader>b :bp<CR>
nnoremap <Leader>f :bn<CR>
nnoremap <Leader>g :e#<CR>
nnoremap <Leader>1 :1b<CR>
nnoremap <Leader>2 :2b<CR>
nnoremap <Leader>3 :3b<CR>
nnoremap <Leader>4 :4b<CR>
nnoremap <Leader>5 :5b<CR>
nnoremap <Leader>6 :6b<CR>
nnoremap <Leader>7 :7b<CR>
nnoremap <Leader>8 :8b<CR>
nnoremap <Leader>9 :9b<CR>
nnoremap <Leader>0 :10b<CR>
" Close the current buffer. Bclose defined below.
" dovrebbe già esistere in bufkill.vim
" map <leader>bd :Bclose<cr>
" Use the arrows to do something useful
map <right> :bn<cr>
map <left> :bp<cr>
" MiniBufExplorer settings
let g:miniBufExplModSelTarget = 1
let g:miniBufExplorerMoreThanOne = 2
let g:miniBufExplModSelTarget = 0
let g:miniBufExplUseSingleClick = 1
let g:miniBufExplMapWindowNavVim = 1
" Change directory to the file I'm editing
"autocmd BufEnter * lcd %:p:h
" When pressing <leader>cd switch to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>
" Function to close buffer?
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
" Specify the behavior when switching between buffers
try
set switchbuf=usetab
set stal=2
catch
endtry
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>
" Always hide the statusline
set laststatus=2
" Format the statusline
set statusline=\ %F%m%r%h\ %w\ \ [%Y]\ \ CWD:\ %r%{CurDir()}%h\ \ \ Line:\ %l/%L:%c
"set statusline=%F%m%w\ Line:\ %l\/%L[%p%%]\ Col:\ %c\ Buf:\ #%n\ [%Y]\ [\%03.3b]\[\%02.2B]
function! CurDir()
let curdir = substitute(getcwd(), '/Users/amir/', "~/", "g")
return curdir
endfunction
" tab labels show the filename without path(tail)
set guitablabel=%N/\ %t\ %M
""" Windows
if exists(":tab") " Try to move to other windows if changing buf
set switchbuf=useopen,usetab
else " Try other windows & tabs if available
set switchbuf=useopen
endif
"""" Messages, Info, Status
set shortmess+=a " Use [+] [RO] [w] for modified, read-only, modified
set report=0 " Notify me whenever any lines have changed
set confirm " Y-N-C prompt if closing with unsaved changes
" we don't want to edit these type of files
set wildignore=*.o,*.obj,*.bak,*.exe,*.pyc,*.swp
"""" Coding
set history=1000 " 1000 Lines of history
set showfulltag " Show more information while completing tags
" taglist plugin settings
"nnoremap <silent> <F8> :TlistToggle<CR>
let Tlist_Exit_OnlyWindow = 1 "exit if taglist is last window open
let Tlist_Show_One_File = 1 "only show tags for current buffer
let Tlist_Enable_Fold_Column = 0 "no fold column (only showing one file)
" OmniCppComplete
let OmniCpp_NamespaceSearch = 1
let OmniCpp_GlobalScopeSearch = 1
let OmniCpp_ShowAccess = 1
let OmniCpp_ShowPrototypeInAbbr = 1 " show function parameters
let OmniCpp_MayCompleteDot = 1 " autocomplete after .
let OmniCpp_MayCompleteArrow = 1 " autocomplete after ->
let OmniCpp_MayCompleteScope = 1 " autocomplete after ::
let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"]
" automatically open and close the popup menu / preview window
au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif
set completeopt=menuone,menu,longest,preview
let g:sparkupNextMapping = '<c-x>'
" SuperTab settings
let g:SuperTabDefaultCompletionType = '<c-x><c-o>'
""""" Folding
set foldmethod=syntax " By default, use syntax to determine folds
set foldlevelstart=99 " All folds open by default
" Function to highlight character beyond column 79
" activate it with ,h
nnoremap <leader>h :call ToggleOverLengthHighlight()<CR>
let g:overlength_enabled = 0
" set the highlight color
highlight OverLength ctermbg=red guibg=red
function! ToggleOverLengthHighlight()
if g:overlength_enabled == 0
match OverLength /\%79v.*/
let g:overlength_enabled = 1
echo 'OverLength highlighting turned on'
else
match
let g:overlength_enabled = 0
echo 'OverLength highlighting turned off'
endif
endfunction
" in visual mode press Ctrl r to start substituting text
vnoremap <C-r> "hy:%s/<C-r>h//gc<left><left><left>
" PHP Code Sniffer binary (default = "phpcs")
let g:phpqa_codesniffer_cmd='vendor/bin/phpcs'
" PHP Mess Detector binary (default = "phpmd")
let g:phpqa_messdetector_cmd='vendor/bin/phpmd'
set relativenumber
" important
" moving around, searching and patterns
" tags
" displaying text
" syntax, highlighting and spelling
" multiple windows
" multiple tab pages
" terminal
" using the mouse
" printing
" messages and info
" selecting text
" editing text
" tabs and indenting
" folding
" diff mode
" mapping
" toggle the tag list
nmap <Leader>tl :TlistToggle<CR>
" reading and writing files
" the swap file
" command line editing
" executing external commands
" running make and jumping to errors
" language specific
" multi-byte characters
" various
" TagList options
" set the names of flags
let tlist_php_settings = 'php;c:class;f:function;d:constant;p:property'
" close all folds except for current file
let Tlist_File_Fold_Auto_Close = 1
" make tlist pane active when opened
let Tlist_GainFocus_On_ToggleOpen = 1
" width of window
let Tlist_WinWidth = 60
" close tlist when a selection is made
let Tlist_Close_On_Select = 1
" show the prototype
let Tlist_Display_Prototype = 1
" show tags only for current buffer
let Tlist_Show_One_File = 1
" Taglist variables
" Display function name in status bar:
let g:ctags_statusline=1
" Automatically start script
let generate_tags=1
" Displays taglist results in a vertical windows:
let Tlist_Use_Horiz_Window=0
" Shorter commands to toggle Taglist display
nnoremap TT :TlistToggle<CR>
map <F4> :TlistToggle<CR>
" Various Taglist display config:
let Tlist_Use_Right_Windows = 1
let Tlist_Compact_Format = 1
let Tlist_Exit_OnlyWindow = 1
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_File_Fold_Auto_Close = 1
" Ctags options
nmap <Leader>tf :call CtagsFind(expand('<cword>'))<CR>
com! -nargs=+ Tf :call CtagsFind("<args>")
" split window and search for tag
nmap <Leader>ts :exe('stj '.expand('<cword>'))<CR>
set tags=tags;/
" open new tab and search for tag
"
fun! CtagsFind(keyword)
tabe
exe "tj ".a:keyword
endfunction
" TagBar
nmap <F8> :TagbarToggle<CR>
" CtrlP
let g:ctrlp_map = ',t'
nnoremap <silent> ,t :CtrlP<CR>
Your autocmd will be appended to your vim events.
You need handle reload with using augroup.
augroup MyAutoCmd
autocmd!
autocmd MyAutoCmd BufWritePost $MYVIMRC nested source $MYVIMRC
augroup END

Vim: inoremap works in buffer, not in .vimrc

I'm really eager to include the following in my .vimrc file:
inoremap <Tab> <C-x><C-u>
If I set it within a buffer (via :inoremap <Tab> <C-x><C-u>) it works exactly as I'd hoped.
But, if I place it in my .vimrc, it doesn't seem to be acknowledged at all.
I've attached my .vimrc below. A few things:
Other changes to the .vimrc file are picked up, so it's not the wrong file
Have tried adding at the very bottom of the .vimrc & still doesn't work, so it's not being overwritten
Any ideas appreciated. Many thanks.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
finish
endif
" Word complete
" :autocmd BufEnter * call DoWordComplete()
" let g:WC_min_len = 4
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
map j gj
map k gk
set showmatch " Show matching brackets
set mat=5 " Bracket blinking
set noerrorbells " No noise
" Ruby autocomplete
" Autocomplete behaviour
set completeopt=longest,menuone
open omni completion menu closing previous if open and opening new menu without changing the text
inoremap <expr> <C-Space> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
\ '<C-x><C-o><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'
" open user completion menu closing previous if open and opening new menu without changing the text
inoremap <expr> <S-Space> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
\ '<C-x><C-u><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'
autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1
autocmd FileType ruby,eruby let g:rubycomplete_rails = 1
autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global = 1
" highlight Pmenu ctermbg=238 gui=bold "improve autocomplete menu color
" Colours
highlight Pmenu ctermfg=6 ctermbg=238 guibg=grey30
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
" if has("vms")
" set nobackup " do not keep a backup file, use versions instead
" else
" set backup " keep a backup file
" endif
" Set backupdir to tmp
" Do not let vim create <filename>~ backup files
set nobackup
" set nowritebackup
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
" Set tab to 2 spaces
set ts=2
set shiftwidth=2
" Ignore case
set ignorecase
set smartcase
" Menu autocomplete
set wildmode=longest,list
set wildmenu
" Call pathogen
call pathogen#infect()
" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries
" let &guioptions = substitute(&guioptions, "t", "", "g")
" Don't use Ex mode, use Q for formatting
map Q gq
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Turn syntax highlighting on (Added by John Bayne, 18/08/2012)
syntax on
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
\ | wincmd p | diffthis
endif
" My customisations
" No backup files
set nobackup
set nowritebackup
set noswapfile
" Whitespace identifier
:highlight ExtraWhitespace ctermbg=darkgreen guibg=lightgreen
:match ExtraWhitespace /\s\+$/
" Colour options
" color codeschool
" set guifont=Monaco:h12
" let g:NERDTreeWinPos = "right"
" set guioptions-=T " Removes top toolbar
" set guioptions-=r " Removes right hand scroll bar
" set go-=L " Removes left hand scroll bar
" autocmd User Rails let b:surround_{char2nr('-')} = "<% \r %>" " displays <% %> correctly
" :set cpoptions+=$ " puts a $ marker for the end of words/lines in cw/c$ commands
" Tab behaviour for ultisnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<s-tab>"
inoremap <Tab> <C-x><C-u>
In this case, :scriptnames, while useful, is not the best way to see where a mapping was last set.
:verbose map <tab>
is a lot more precise.
Maybe another script is overwriting it after your .vimrc is read.
You can use :scriptnames to see what files are read on startup.

What causes substitution in Vim to only match one element per line?

I've been making a lot of changes to my .vimrc lately, and somewhere along the line I've introduced an undesirable feature. When performing a substitution command where the search token appears more than once per line, only the first token is changed (although the remaining tokens are highlighted as a result of the substitution). I have seen a few posts here about how to enable this behavior on a case-by-case basis, but I have yet to see something about what would cause this to be the default behavior or how to disable it. If anyone has any ideas, they would be appreciated.
For reference, my .vimrc (https://github.com/chpatton013/dotfiles/blob/master/vim/.vimrc):
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Autocommands
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Reread configuration of Vim if .vimrc is saved
augroup VimConfig
au!
au BufWritePost ~/.vimrc so ~/.vimrc
au BufWritePost _vimrc so ~/_vimrc
au BufWritePost vimrc so ~/.vimrc
augroup END
" Set colorcolumn to 80 chars, or (if not supported) highlight lines > 80 chars
augroup ColorColumnConfig
au!
if exists('+colorcolumn')
au BufWinEnter * set colorcolumn=80
au BufWinEnter * hi ColorColumn ctermbg=lightgrey guibg=lightgrey
else
au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\%>80v.\+', -1)
endif
augroup END
" Highlight over-length characters and trailing whitespace
augroup ExtraCharacters
au!
au ColorScheme * highlight ExtraWhitespace ctermbg=Red guibg=Red
au ColorScheme * highlight OverLength ctermbg=red ctermfg=white guibg=red guifg=white
au BufWinEnter * let w:whitespace_match_number =
\ matchadd('ExtraWhitespace', '\s\+$')
au BufWinEnter * call matchadd('OverLength',
\ '\(^\(\s\)\{-}\(*\|//\|/\*\)\{1}\(.\)*\(\%81v\)\)\#<=\(.\)\{1,}$')
au InsertEnter * call s:ToggleWhitespaceMatch('i')
au InsertLeave * call s:ToggleWhitespaceMatch('n')
augroup END
" Resize splits on window resize
au VimResized * exe "normal! \<c-w>="
" Restore the cursor when we can.
au BufWinEnter * call RestoreCursor()
" Change the statusline color based on current mode
augroup StatuslineColor
au!
au InsertEnter * call InsertStatuslineColor(v:insertmode)
au InsertLeave * hi statusline ctermfg=cyan ctermbg=black guifg=cyan guibg=black
augroup END
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugins
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pathogen - https://github.com/tpope/vim-pathogen
runtime bundle/vim-pathogen/autoload/pathogen.vim
call pathogen#infect()
call pathogen#helptags()
" Easymotion - https://github.com/Lokaltog/vim-easymotion/
" This is so much more convenient
let g:EasyMotion_leader_key=',m'
" Neocomplcache - https://github.com/Shougo/neocomplcache
" Enable at startup.
let g:neocomplcache_enable_at_startup=1
" Only display 'n' items in the list.
let g:neocomplcache_max_list=5
" Do not auto-select the first candidate.
let g:neocomplcache_enable_auto_select=1
" Do not try to match until 'n' characters have been typed
let g:neocomplcache_auto_completion_start_length=3
" Do not try to match to anything less than 'n' characters
let g:neocomplcache_min_keyword_length=6
let g:neocomplcache_min_syntax_length=6
" Only consider case if an uppercase character has been typed
let g:neocomplcache_enable_smart_case=1
" Syntastic - https://github.com/scrooloose/syntastic/
" Commands:
" :Errors // pop up location list and display errors
" :SyntasticToggleMode // toggles between active and passive mode
" :SyntasticCheck // forces a syntax check in passive mode
" check for syntax errors on file open
let g:syntastic_check_on_open=1
" echo errors to the command window
let g:syntastic_echo_current_error=1
" mark lines with errors and warnings
let g:syntastic_enable_signs=1
" set sign symbols
let g:syntastic_error_symbol='E>'
let g:syntastic_warning_symbol='W>'
let g:syntastic_style_error_symbol='S>'
let g:syntastic_style_warning_symbol='s>'
" open error balloons when moused over erroneous lines
let g:syntastic_enable_balloons=1
" customize Syntastic statusline
let g:syntastic_stl_format = '[%E{E: %fe #%e}%B{, }%W{W: %fw #%w}]'
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Strip trailing whitespace
function! <SID>StripTrailingWhitespaces()
let _s=#/
let l = line(".")
let c = col(".")
%s/\s\+$//e
let #/=_s
call cursor(l, c)
endfunction
" Toggle match of trailing whitespace
function! s:ToggleWhitespaceMatch(mode)
let pattern = (a:mode == 'i') ? '\s\+\%#\#<!$' : '\s\+$'
if exists('w:whitespace_match_number')
call matchdelete(w:whitespace_match_number)
call matchadd('ExtraWhitespace', pattern, 10, w:whitespace_match_number)
else
" Something went wrong, try to be graceful.
let w:whitespace_match_number = matchadd('ExtraWhitespace', pattern)
endif
endfunction
" Restore the cursor when we can
function! RestoreCursor()
if line("'\"") <= line("$")
normal! g`"
normal! zz
endif
endfunction
" Change the statusline color based on current mode
function! InsertStatuslineColor(mode)
if a:mode == 'i'
hi statusline ctermfg=darkmagenta ctermbg=black guifg=darkmagenta guibg=black
elseif a:mode == 'r'
hi statusline ctermfg=darkgreen ctermbg=black guifg=darkgreen guibg=black
else
hi statusline ctermfg=darkred ctermbg=black guifg=darkred guibg=black
endif
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Configuration customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" gui configuration (do not move from top of configurations)
set guioptions=am
set guifont=Consolas:h9
set encoding=utf-8
set fileencoding=utf-8
set nocompatible " No compatibility with vi.
filetype on " Recognize syntax by file extension.
filetype indent on " Check for indent file.
filetype plugin on " Allow plugins to be loaded by file type.
behave xterm " Maintain keybindings across enviornments
set autowrite " Write before executing the 'make' command.
set background=dark " Background light, so foreground not bold.
set backspace=indent,eol,start " Allow <BS> to go over indents, eol, and start of insert
set expandtab " Expand tabs with spaces.
set nofoldenable " Disable folds; toggle with zi.
set gdefault " Assume :s uses /g.
set hidden " Use hidden buffers so unsaved buffers can go to the background
set history=500 " Set number of lines for vim to remember
set hlsearch " Highlight all search matches
set ignorecase " Ignore case in regular expressions
set incsearch " Immediately highlight search matches.
set laststatus=2 " Show status line even where there is only one window
set lazyredraw " Redraw faster
set linespace=-1 " Bring lines closer together vertically
set modeline " Check for a modeline.
set noerrorbells " No beeps on errors.
set nohls " Don't highlight all regex matches.
set nowrap " Don't soft wrap.
set number " Display line numbers.
set path=~/Code/** " Set default path
set scrolloff=5 " Keep min of 'n' lines above/below cursor.
set shellslash " Use forward slashes regardless of OS
set shiftwidth=3 " >> and << shift 3 spaces.
set showcmd " Show partial commands in the status line.
set showmatch " Show matching () {} etc..
set showmode " Show current mode.
set sidescrolloff=10 " Keep min of 'n' columns right/left cursor.
set smartcase " Searches are case-sensitive if caps used.
set smarttab " Tabs and backspaces at the start of a line indent the line one level
set smartindent " Maintains most indentation and adds extra level when nesting
set softtabstop=3 " See spaces as tabs.
set splitright splitbelow " Open splits below and to the right
set synmaxcol=160 " Only matches syntax on first 'n' columns of each line ( faster)
set tabstop=3 " <Tab> move three characters
set textwidth=79 " Hard wrap at 79 characters
set title " Set the console title
set viminfo='20,\"500,% " Adjust viminfo contents
set virtualedit=block " Allow the cursor to go where it should not
set wildmenu " Tab completion opens a Tab- and arrow-navigable menu
set wildmode=longest,full " Tab completion works like bash.
set wrapscan " Searching wraps to start of file when end is reached
" Define statusline
set statusline=%f " Relative file path
set statusline+=%(\ [%M%R%H%W]%) " File flags (mod, RO, help, preview)
set statusline+=%(\ %<%) " Start truncation
set statusline+=%(\ %{fugitive#statusline()}%) " Git branch name (if applicable)
set statusline+=%= " Begin right justification
set statusline+=%#warningmsg# " Start warning highlighting
set statusline+=%(\ %{SyntasticStatuslineFlag()}%) " Show Syntastic errors and warnings
set statusline+=%* " End warning highlighting
set statusline+=\ [line\ %l\/%L,\ col\ %c%V,\ %p%%] " Line and column numbers and percentage through file
" Text formatting settings
" t: Auto-wrap text using textwidth. (default)
" c: Auto-wrap comments; insert comment leader. (default)
" q: Allow formatting of comments with "gq". (default)
" r: Insert comment leader after hitting <Enter>.
" o: Insert comment leader after hitting 'o' or 'O' in command mode.
" n: Auto-format lists, wrapping to text *after* the list bullet char.
" l: Don't auto-wrap if a line is already longer than textwidth.
set formatoptions+=ronl
" Enable mouse scrolling in selected modes
" a: All
" c: Command
" i: Insert
" n: Normal
" v: Visual
set mouse=a
" Set scrolling to be single-line
"map <MouseDown> <C-Y>
"map <S-MouseDown> <C-U>
"map <MouseUp> <C-E>
"map <S-MouseUp> <C-D>
" Highlighting
syntax enable
set t_Co=16
colorscheme solarized
" Configuration variables
let loaded_matchparen=0 " do automatic bracket highlighting.
let mapleader="," " Use , instead of \ for the map leader.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Command mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Make y behave like all other capitals
map Y y$
" Make Q reformat text.
noremap Q gq
" Toggle paste mode.
noremap <Leader>p :set paste!<CR>
" Open the file under the cursor in a new tab.
noremap <Leader>ot <C-W>gf
" Toggle highlighting of the last search.
noremap <Leader>h :set hlsearch! hlsearch?<CR>
" Open a scratch buffer.
noremap <Leader>s :Scratch<CR>
" Improve movement on wrapped lines
nnoremap j gj
nnoremap k gk
" Keep search pattern at the center of the screen
nnoremap <silent> n nzz
nnoremap <silent> N Nzz
nnoremap <silent> * *zz
nnoremap <silent> # #zz
nnoremap <silent> g* g*zz
nnoremap <silent> g# g#zz
" Use C-hjkl in to change windows
nnoremap <C-h> <C-w><Left>
nnoremap <C-j> <C-w><Down>
nnoremap <C-k> <C-w><Up>
nnoremap <C-l> <C-w><Right>
" Strip trailing whitespace
nnoremap <silent> <leader>W :call <SID>StripTrailingWhitespaces()<CR>
" Allow easy toggling of spaces / tabs mode
nnoremap <C-t><C-t> :set invexpandtab<CR>
" Create simple toggles for line numbers, paste mode, and word wrap.
nnoremap <C-N><C-N> :set invnumber<CR>
nnoremap <C-p><C-p> :set invpaste<CR>
nnoremap <C-w><C-w> :set invwrap<CR>
" Folding stuff
nnoremap <C-o> zo
nnoremap <C-c> zc
nnoremap <C-O> zO
nnoremap <C-O><C-O> zR
set foldmethod=indent
" Open file for class name under cursor
nnoremap <C-i> yiw:find <C-R>".php<CR>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Insert mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set up dictionary completion.
set dictionary+=~/.vim/dictionary/english-freq
set complete+=k
" Smash Esc
inoremap jk <Esc>
inoremap kj <Esc>
" Use hjkl in insert mode
imap <C-h> <Left>
imap <C-j> <Down>
imap <C-k> <Up>
imap <C-l> <Right>
" Make C-s write the buffer and return to insert mode when applicable
inoremap <C-s> <C-O>:w<CR>
nnoremap <C-s> :w<CR>
" auto-insert second braces and parynthesis
inoremap {<CR> {<CR>}<Esc>O
inoremap ({<CR> ({<CR>});<Esc>O
inoremap <<<<CR> <<<EOT<CR>EOT;<Esc>O<C-TAB><C-TAB><C-TAB>
set cpoptions+=$ "show dollar sign at end of text to be changed
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Visual mode customization
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" reselect visual block after indent/outdent
xnoremap < <gv
xnoremap > >gvo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
And the following plugins make up the contents of my bundle directory (https://github.com/chpatton013/dotfiles/tree/master/vim/.vim/bundle):
neocomplcache/
syntastic/
vim-abolish/
vim-colors-solarized/
vim-commentary/
vim-easymotion/
vim-fugitive/
vim-pathogen/
vim-repeat/
vim-surround/
Finally, I have disabled all plugins, but the issue was not resolved. I removed my .vimrc and the issue was resolved (so it is not some global setting outside of my control). I disabled several individual settings in my .vimrc, but I could not seem to eliminate the problem. Eventually, I got tired of playing whack-a-mole and decided to turn to the community. Any ideas?
EDIT: As an example,
I use the command :%s/foo/foobar/g
The text foo bar foo is converted to foobar bar foo
EDIT: Resolved by pb2q. set gdefault inverts the behavior of /g.
The substitute command accepts the switch g, for global, which causes the substitution to be made on all matches on the line:
:s/regex/replacement/g
The default is that only the first occurrence of the match is substituted, but there's a setting to switch the default to global: gdefault. So set gdefault in your vimrc if you want this as the default behavior. Try it out first in the current vim session with :set gdefault.
Note that when you set gdefault, this not only makes g the default behavior, but it changes the usage of the g flag so that using /g at the end of a substitute will cause the substitution to be made only once.
See: :help gdefault.

Resources