Open file with new tab but [no name] is always there in vim - nerdtree

Hello I open file in NERDTree using t but new files is always there. Before I use vim in folder. that mean when I located in ex: app folder, I run vim without type specific files to edit. when I open files in nerd tree, new file [No Name] is always there. is anyone know how to fix it?
this is my init.vim
" Specify a directory for plugins
call plug#begin('~/.vim/plugged')
Plug 'dense-analysis/ale'
Plug 'mattn/emmet-vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'scrooloose/nerdtree'
"Plug 'tsony-tsonev/nerdtree-git-plugin'
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'tiagofumo/vim-nerdtree-syntax-highlight'
Plug 'ryanoasis/vim-devicons'
Plug 'airblade/vim-gitgutter'
Plug 'ctrlpvim/ctrlp.vim' " fuzzy find files
Plug 'scrooloose/nerdcommenter'
"Plug 'prettier/vim-prettier', { 'do': 'yarn install' }"
Plug 'christoomey/vim-tmux-navigator'
Plug 'sheerun/vim-polyglot'
Plug 'morhetz/gruvbox'
Plug 'rafi/awesome-vim-colorschemes'
Plug 'vim-airline/vim-airline'
Plug 'Yggdroot/indentLine'
Plug 'HerringtonDarkholme/yats.vim' " TS Syntax
Plug 'tomasiser/vim-code-dark'
" Initialize plugin system
call plug#end()
inoremap jk <ESC>
nmap <C-n> :NERDTreeToggle<CR>
vmap ++ <plug>NERDCommenterToggle
nmap ++ <plug>NERDCommenterToggle
set mouse=a
set number
set hidden
set cursorline
set expandtab
set autoindent
set smartindent
set shiftwidth=4
set tabstop=4
set encoding=utf8
set history=5000
set clipboard=unnamedplus
" open NERDTree automatically
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * NERDTree
" Open the existing NERDTree on each new tab.
autocmd BufWinEnter * silent NERDTreeMirror
" Exit Vim if NERDTree is the only window left.
autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() |
\ quit | endif
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree")
\ && b:NERDTree.isTabTree()) | q | endif
let g:NERDTreeGitStatusWithFlags = 1
"let g:WebDevIconsUnicodeDecorateFolderNodes = 1
"let g:NERDTreeGitStatusNodeColorization = 1
"let g:NERDTreeColorMapCustom = {
"\ "Staged" : "#0ee375",
"\ "Modified" : "#d9bf91",
"\ "Renamed" : "#51C9FC",
"\ "Untracked" : "#FCE77C",
"\ "Unmerged" : "#FC51E6",
"\ "Dirty" : "#FFBD61",
"\ "Clean" : "#87939A",
"\ "Ignored" : "#808080"
"\ }
let g:NERDTreeIgnore = ['^node_modules$']
" vim-prettier
"let g:prettier#quickfix_enabled = 0
"let g:prettier#quickfix_auto_focus = 0
" prettier command for coc
command! -nargs=0 Prettier :CocCommand prettier.formatFile
" run prettier on save
"let g:prettier#autoformat = 0
"autocmd BufWritePre *.js,*.jsx,*.mjs,*.ts,*.tsx,*.css,*.less,*.scss,*.json,*.graphql,*.md,*.vue,*.yaml,*.html PrettierAsync
" ctrlp
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
" j/k will move virtual lines (lines that wrap)
noremap <silent> <expr> j (v:count == 0 ? 'gj' : 'j')
noremap <silent> <expr> k (v:count == 0 ? 'gk' : 'k')
nnoremap <C-s> :w<CR>
nnoremap <C-Q> :wq<CR>
" shift+arrow selection
nmap <S-Up> v<Up>
nmap <S-Down> v<Down>
nmap <S-Left> v<Left>
nmap <S-Right> v<Right>
vmap <S-Up> <Up>
vmap <S-Down> <Down>
vmap <S-Left> <Left>
vmap <S-Right> <Right>
imap <S-Up> <Esc>v<Up>
imap <S-Down> <Esc>v<Down>
imap <S-Left> <Esc>v<Left>
imap <S-Right> <Esc>v<Right>
vmap <C-c> y<Esc>i
vmap <C-x> d<Esc>i
map <C-v> pi
imap <C-v> <Esc>pi
set cindent
set t_Co=256
set t_ut=
colorscheme onedark
" sync open file with NERDTree
" " Check if NERDTree is open or active
function! IsNERDTreeOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
" Call NERDTreeFind iff NERDTree is active, current window contains a modifiable
" file, and we're not in vimdiff
function! SyncTree()
if &modifiable && IsNERDTreeOpen() && strlen(expand('%')) > 0 && !&diff
NERDTreeFind
wincmd p
endif
endfunction
" Highlight currently open buffer in NERDTree
autocmd BufEnter * call SyncTree()
" coc config
let g:coc_global_extensions = [
\ 'coc-snippets',
\ 'coc-pairs',
\ 'coc-tsserver',
\ 'coc-eslint',
\ 'coc-prettier',
\ 'coc-json',
\ 'coc-python',
\ ]
" from readme
" if hidden is not set, TextEdit might fail.
set hidden " Some servers have issues with backup files, see #649 set nobackup set nowritebackup " Better display for messages set cmdheight=2 " You will have bad experience for diagnostic messages when it's default 4000.
set updatetime=300
" don't give |ins-completion-menu| messages.
set shortmess+=c
" always show signcolumns
set signcolumn=yes
" Use tab for trigger completion with characters ahead and navigate.
" Use command ':verbose imap <tab>' to make sure tab is not mapped by other plugin.
inoremap <silent><expr> <TAB>
\ pumvisible() ? "\<C-n>" :
\ <SID>check_back_space() ? "\<TAB>" :
\ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" Use <c-space> to trigger completion.
inoremap <silent><expr> <c-space> coc#refresh()
" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current position.
" Coc only does snippet and additional edit on confirm.
inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
" Or use `complete_info` if your vim support it, like:
" inoremap <expr> <cr> complete_nfo()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"
" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" Remap keys for gotos
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gr <Plug>(coc-references)
" Use K to show documentation in preview window
nnoremap <silent> K :call <SID>show_documentation()<CR>
function! s:show_documentation()
if (index(['vim','help'], &filetype) >= 0)
execute 'h '.expand('<cword>')
else
call CocAction('doHover')
endif
endfunction
" Highlight symbol under cursor on CursorHold
autocmd CursorHold * silent call CocActionAsync('highlight')
" Remap for rename current word
nmap <F2> <Plug>(coc-rename)
" Remap for format selected region
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
augroup mygroup
autocmd!
" Setup formatexpr specified filetype(s).
autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
" Update signature help on jump placeholder
autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end
" Remap for do codeAction of selected region, ex: `<leader>aap` for current paragraph
xmap <leader>a <Plug>(coc-codeaction-selected)
nmap <leader>a <Plug>(coc-codeaction-selected)
" Remap for do codeAction of current line
nmap <leader>ac <Plug>(coc-codeaction)
" Fix autofix problem of current line
nmap <leader>qf <Plug>(coc-fix-current)
" Create mappings for function text object, requires document symbols feature of languageserver.
xmap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap if <Plug>(coc-funcobj-i)
omap af <Plug>(coc-funcobj-a)
" Use <C-d> for select selections ranges, needs server support, like: coc-tsserver, coc-python
nmap <silent> <C-d> <Plug>(coc-range-select)
xmap <silent> <C-d> <Plug>(coc-range-select)
" Use `:Format` to format current buffer
command! -nargs=0 Format :call CocAction('format')
" Use `:Fold` to fold current buffer
command! -nargs=? Fold :call CocAction('fold', <f-args>)
" use `:OR` for organize import of current buffer
command! -nargs=0 OR :call CocAction('runCommand', 'editor.action.organizeImport')
" Add status line support, for integration with other plugin, checkout `:h coc-status`
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" Using CocList
" Show all diagnostics
nnoremap <silent> <space>a :<C-u>CocList diagnostics<cr>
" Manage extensions
nnoremap <silent> <space>e :<C-u>CocList extensions<cr>
" Show commands
nnoremap <silent> <space>c :<C-u>CocList commands<cr>
" Find symbol of current document
nnoremap <silent> <space>o :<C-u>CocList outline<cr>
" Search workspace symbols
nnoremap <silent> <space>s :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent> <space>j :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent> <space>k :<C-u>CocPrev<CR>
" Resume latest coc list
nnoremap <silent> <space>p :<C-u>CocListResume<CR>i
set laststatus=2
let g:airline#extensions#tabline#enabled = 1
let g:airline_powerline_fonts = 1
let g:airline_statusline_ontop=0
let g:airline_theme='onedark'
let g:airline#extensions#tabline#formatter = 'default'
" navegação entre os buffers
nnoremap <M-Right> :bn<cr>
nnoremap <M-Left> :bp<cr>
nnoremap <c-x> :bp \|bd #<cr>
let g:ale_completion_enabled = 0
let g:ale_linters = {'python': ['flake8', 'pylint'], 'javascript': ['eslint']}

To fix it, navigate to the tab which has [No Name] open in it, and close that tab
ESC gt :tabclose
Why?
When you start Vim, Vim opens a buffer as a window in a tab. When you use NerdTree to open a new file — using t — in a new tab, …you're opening a new buffer as a new window in a new tab. The old one is still there. If you look at the top left of your Vim window 👇🏾 it shows two tabs open.
Now the confusing thing about Vim is that Vim Tabs don't work like IDE tabs. In Vim, tabs are more layouts. Using them as buffers is counterintuitive. I would suggest investing some time in understanding buffers.

This isn't ideal, but for the very first file, open it with "o" instead of "t" , this will replace the buffer instead

Related

Windows command prompt set clipboard without trailing newline

I need a command that sets the contents of the clipboard to whatever is piped to its input without adding a trailing newline. The following:
C:> *some_command* | clip.exe
adds a newline at the end, while:
C:> *some_command* | powershell.exe Set-Clipboard
does not seem to pass the standard input to Set-Clipboard. Invoking *some_command* via a powershell prompt is not an option. How can I do what I need?
Background: I am using WSL and I want to be able to copy/paste to the system clipboard from vim, tmux, etc. My current workaround uses clip.exe which adds a newline to whatever I yank. For example, in .vimrc I have:
let g:copy = 'clip.exe'
let g:paste = 'powershell.exe Get-Clipboard -Raw'
augroup myYank
autocmd!
autocmd TextYankPost * if v:event.operator == 'y' | call system(g:copy, #") | let g:lastyank='y' | else | let g:lastyank='' | endif
"autocmd TextYankPost * if v:event.operator ==# 'y' | call system(g:copy, #") | endif
"autocmd TextYankPost * call system(g:copy, #")
augroup END
function! Paste(mode)
if g:lastyank == 'y'
let #" = system(g:paste)
endif
return a:mode
endfunction
map <expr> p Paste('p')
map <expr> P Paste('P')
" map Ctrl-c and Ctrl-x as expected
func! GetSelectedText()
normal gv"xy
let result = getreg("x")
return result
endfunc
noremap <C-c> :call system(g:copy, GetSelectedText())<CR>
noremap <C-x> :call system(g:copy, GetSelectedText())<CR>gvx
output your command in a variable then use $var.trim() | Set-Clipboard, but the best would be to generate the proper output first rather than correcting it down the line so maybe the string builder could help you.
$SB = [System.Text.StringBuilder]::New()
Then you can try this depending on the result you want, the string builder will store everything in it's corresponding variable.
$SB.Append($Text)
$SB.AppendLine($Text)
Then finally
$SB | SCB
Sometime also
Out-String -NoNewLine
can help but certain commands will generate blank lines at the end by default so trimming can come in handy sometimes.

vim: execute shell command with variable and redirect output to new buffer

I want to call msbuild from the function below and redirect the output to a new buffer.
My problem is that I need to use a variable, for the filename, and therefore cant use '!' (can I?), and when I use exe or system() read complains that I'm not giving it a proper file.
func! myFunction()
let findstr = "findstr /s /m " . '"' . expand("%:t") . '"' . " *.vcxproj"
for project in split(system(findstr), nr2char(10))
echo "Building '" . project . "'"
let msbuild = "c:\\windows\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe" . " " . project . " " . "/t:rebuild /p:configuration=debug"
:tabnew | r system(msbuild) "<--THIS LINE HERE
endfor
endfunc
The :read command takes a file not a vim expression. However it can read in from standard output via :read !{cmd}. Example :%r!ls. Using the :execute command you can build your new command with your variable.
exe '%r!' . msbuild
Or you can use :put along with the expression register if you want to use an expression like system(). (Probably want to follow this with :0d_ to delete the first empty line)
put=system(msbuild)
Now it looks like you are trying to build your project and get a list of errors. I would recommend you look into :make, the 'makeprg' option, and the quickfix list as this is a more vim way of building a project.
For more help see:
:h :r!
:h :exe
:h :pu
:h #=
:h :make
:h 'makeprg'
:h quickfix
This is a function you can use to execute arbitrary shell commands and present their output in a new window ( you can put this in your _vimrc):
let s:lastcmd = ''
function! s:RunShellCommand(cmdline, bang)
" Support for repeating last cmd with bang:
let _ = a:bang != '' ? s:lastcmd : a:cmdline == '' ? '' : join(map(split(a:cmdline), 'expand(v:val)'))
if _ == ''
return
endif
let s:lastcmd = _
let bufnr = bufnr('%')
let winnr = bufwinnr(_)
" You can position the new window whenever you want, I chose below + right:
silent! execute winnr < 0 ? 'belowright new ' . fnameescape(_) : winnr . 'wincmd w'
" I could set buftype=nofile, but then no switching back and forth buffers.
" The results are presented just for viewing, not editing, modify at will:
setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile wrap number
setlocal modifiable
silent! :%d
" Useful for debugging, if you encounter issues with fnameescape():
call setline(1, 'You entered: ' . a:cmdline)
call setline(2, 'Expanded to: ' . _)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !' . _
silent! execute 'autocmd BufUnload <buffer> execute bufwinnr(' . bufnr . ') . ''wincmd w'''
" If resizing is unwanted for commands with too much output, remove this line:
silent! execute 'autocmd BufEnter <buffer> execute ''resize '' . line(''$'')'
" You can use <localleader>r to re-execute the last command:
silent! execute 'nnoremap <silent> <buffer> <localleader>r :call <SID>RunShellCommand(''' . _ . ''', '''')<CR>'
execute 'resize ' . line('$')
setlocal nomodifiable
1
endfunction " RunShellCommand(cmdline)
command! -complete=shellcmd -nargs=* -bang Shell call s:RunShellCommand(<q-args>, '<bang>')
Use like:
:Shell gcc -ggdb -o test test.c && ./test

Why ctags doesn't work for me?

I try to work with ctags and it simply doesn't work.
I follow this screencast : http://www.youtube.com/watch?v=4f3AENLrdYo. When I press Ctrl + ], it does not matter.
This is my .vimrc :
" vim:set ts=2 sts=2 sw=2 expandtab:
call pathogen#runtime_append_all_bundles()
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" BASIC EDITING CONFIGURATION
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
scriptencoding utf-8
set encoding=utf-8
set fileencoding=utf-8
set number
set nocompatible
" allow unsaved background buffers and remember marks/undo for them
set hidden
" remember more commands and search history
set history=10000
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set autoindent
set laststatus=2
set showmatch
set incsearch
set hlsearch
" make searches case-sensitive only if they contain upper-case characters
set ignorecase smartcase
" highlight current line
set cursorline
set cmdheight=2
set switchbuf=useopen
set numberwidth=5
set showtabline=2
set winwidth=85
set shell=bash
" Prevent Vim from clobbering the scrollback buffer. See
" http://www.shallowsky.com/linux/noaltscreen.html
set t_ti= t_te=
" keep more context when scrolling off the end of a buffer
set scrolloff=3
" Store temporary files in a central spot
set backup
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
" display incomplete commands
set showcmd
" Enable highlighting for syntax
syntax on
" 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
" use emacs-style tab completion when selecting files, etc
set wildmode=longest,list
" make tab completion for files/buffers act like bash
set wildmenu
let mapleader=","
let g:ctrlp_max_height = 40
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" CUSTOM AUTOCMDS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
augroup vimrcEx
" Clear all autocmds in the group
autocmd!
autocmd FileType text setlocal textwidth=78
" Jump to last cursor position unless it's invalid or in an event handler
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal g`\"" |
\ endif
"for ruby, autoindent with two spaces, always expand tabs
autocmd FileType ruby,haml,eruby,yaml,html,javascript,sass,cucumber set ai sw=2 sts=2 et
autocmd FileType python set sw=4 sts=4 et
autocmd! BufRead,BufNewFile *.sass setfiletype sass
autocmd BufRead *.mkd set ai formatoptions=tcroqn2 comments=n:>
autocmd BufRead *.markdown set ai formatoptions=tcroqn2 comments=n:>
" Indent p tags
autocmd FileType html,eruby if g:html_indent_tags !~ '\\|p\>' | let g:html_indent_tags .= '\|p\|li\|dt\|dd' | endif
" Don't syntax highlight markdown because it's often wrong
autocmd! FileType mkd setlocal syn=off
augroup END
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" COLOR
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
:set t_Co=256 " 256 colors
:set background=dark
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" STATUS LINE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
:set statusline=%<%f\ (%{&ft})\ %-4(%m%)%=%-19(%3l,%02c%03V%)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MISC KEY MAPS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <leader>y "*y
" Move around splits with <c-hjkl>
nnoremap <c-j> <c-w>j
nnoremap <c-k> <c-w>k
nnoremap <c-h> <c-w>h
nnoremap <c-l> <c-w>l
" Insert a hash rocket with <c-l>
imap <c-l> <space>=><space>
" Can't be bothered to understand ESC vs <c-c> in insert mode
imap <c-c> <esc>
" Clear the search buffer when hitting return
:nnoremap <CR> :nohlsearch<cr>
nnoremap <leader><leader> <c-^>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" ARROW KEYS ARE UNACCEPTABLE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <Left> :echo "no!"<cr>
map <Right> :echo "no!"<cr>
map <Up> :echo "no!"<cr>
map <Down> :echo "no!"<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MULTIPURPOSE TAB KEY
" Indent if we're at the beginning of a line. Else, do completion.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! InsertTabWrapper()
let col = col('.') - 1
if !col || getline('.')[col - 1] !~ '\k'
return "\<tab>"
else
return "\<c-p>"
endif
endfunction
inoremap <tab> <c-r>=InsertTabWrapper()<cr>
inoremap <s-tab> <c-n>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" OPEN FILES IN DIRECTORY OF CURRENT FILE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
cnoremap %% <C-R>=expand('%:h').'/'<cr>
map <leader>e :edit %%
map <leader>v :view %%
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RENAME CURRENT FILE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" PROMOTE VARIABLE TO RSPEC LET
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! PromoteToLet()
:normal! dd
" :exec '?^\s*it\>'
:normal! P
:.s/\(\w\+\) = \(.*\)$/let(:\1) { \2 }/
:normal ==
endfunction
:command! PromoteToLet :call PromoteToLet()
:map <leader>p :PromoteToLet<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" EXTRACT VARIABLE (SKETCHY)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! ExtractVariable()
let name = input("Variable name: ")
if name == ''
return
endif
" Enter visual mode (not sure why this is needed since we're already in
" visual mode anyway)
normal! gv
" Replace selected text with the variable name
exec "normal c" . name
" Define the variable on the line above
exec "normal! O" . name . " = "
" Paste the original selected text to be the variable value
normal! $p
endfunction
vnoremap <leader>rv :call ExtractVariable()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" INLINE VARIABLE (SKETCHY)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! InlineVariable()
" Copy the variable under the cursor into the 'a' register
:let l:tmp_a = #a
:normal "ayiw
" Delete variable and equals sign
:normal 2daW
" Delete the expression into the 'b' register
:let l:tmp_b = #b
:normal "bd$
" Delete the remnants of the line
:normal dd
" Go to the end of the previous line so we can start our search for the
" usage of the variable to replace. Doing '0' instead of 'k$' doesn't
" work; I'm not sure why.
normal k$
" Find the next occurence of the variable
exec '/\<' . #a . '\>'
" Replace that occurence with the text we yanked
exec ':.s/\<' . #a . '\>/' . #b
:let #a = l:tmp_a
:let #b = l:tmp_b
endfunction
nnoremap <leader>ri :call InlineVariable()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MAPS TO JUMP TO SPECIFIC COMMAND-T TARGETS AND FILES
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <leader>gr :topleft :split config/routes.rb<cr>
function! ShowRoutes()
" Requires 'scratch' plugin
:topleft 100 :split __Routes__
" Make sure Vim doesn't write __Routes__ as a file
:set buftype=nofile
" Delete everything
:normal 1GdG
" Put routes output in buffer
:0r! rake -s routes
" Size window to number of lines (1 plus rake output length)
:exec ":normal " . line("$") . _ "
" Move cursor to bottom
:normal 1GG
" Delete empty trailing line
:normal dd
endfunction
map <leader>gR :call ShowRoutes()<cr>
map <leader>gv :CtrlPClearCache<cr>\|:CtrlP app/views<cr>
map <leader>gc :CtrlPClearCache<cr>\|:CtrlP app/controllers<cr>
map <leader>gm :CtrlPClearCache<cr>\|:CtrlP app/models<cr>
map <leader>gh :CtrlPClearCache<cr>\|:CtrlP app/helpers<cr>
map <leader>gl :CtrlPClearCache<cr>\|:CtrlP lib<cr>
map <leader>gp :CtrlPClearCache<cr>\|:CtrlP public<cr>
map <leader>gs :CtrlPClearCache<cr>\|:CtrlP spec<cr>
map <leader>gf :CtrlPClearCache<cr>\|:CtrlP features<cr>
map <leader>gg :topleft 100 :split Gemfile<cr>
map <leader>gt :CtrlPClearCache<cr>\|:CtrlPTag<cr>
map <leader>f :CtrlPClearCache<cr>\|:CtrlP<cr>
map <leader>F :CtrlPClearCache<cr>\|:CtrlP %%<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" SWITCH BETWEEN TEST AND PRODUCTION CODE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! OpenTestAlternate()
let new_file = AlternateForCurrentFile()
exec ':e ' . new_file
endfunction
function! AlternateForCurrentFile()
let current_file = expand("%")
let new_file = current_file
let in_spec = match(current_file, '^spec/') != -1
let going_to_spec = !in_spec
let in_app = match(current_file, '\<controllers\>') != -1 || match(current_file, '\<models\>') != -1 || match(current_file, '\<views\>') != -1
if going_to_spec
if in_app
let new_file = substitute(new_file, '^app/', '', '')
end
let new_file = substitute(new_file, '\.rb$', '_spec.rb', '')
let new_file = 'spec/' . new_file
else
let new_file = substitute(new_file, '_spec\.rb$', '.rb', '')
let new_file = substitute(new_file, '^spec/', '', '')
if in_app
let new_file = 'app/' . new_file
end
endif
return new_file
endfunction
nnoremap <leader>. :call OpenTestAlternate()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RUNNING TESTS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RunTests(filename)
" Write the file and run tests for the given filename
:w
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
:silent !echo;echo;echo;echo;echo;echo;echo;echo;echo;echo
if match(a:filename, '\.feature$') != -1
exec ":!script/features " . a:filename
else
if filereadable("script/test")
exec ":!script/test " . a:filename
elseif filereadable("Gemfile")
exec ":!bundle exec rspec --color " . a:filename
else
exec ":!rspec --color " . a:filename
end
end
endfunction
function! SetTestFile()
" Set the spec file that tests will be run for.
let t:grb_test_file=#%
endfunction
function! SetLineNumber()
" set the spec file that tests will be run for.
let t:spec_line_number=line('.')
endfunction
function! RunTestFileWithBacktrace(...)
if a:0
let command_suffix = a:1
else
let command_suffix = ""
endif
" Run the tests for the previously-marked file.
let in_test_file = match(expand("%"), '\(.feature\|_spec.rb\)$') != -1
if in_test_file
call SetTestFile()
elseif !exists("t:grb_test_file")
return
end
call RunTests(t:grb_test_file . command_suffix . " -b")
endfunction
function! RunTestFile(...)
if a:0
let command_suffix = a:1
else
let command_suffix = ""
endif
" Run the tests for the previously-marked file.
let in_test_file = match(expand("%"), '\(.feature\|_spec.rb\)$') != -1
if in_test_file
call SetTestFile()
elseif !exists("t:grb_test_file")
return
end
call RunTests(t:grb_test_file . command_suffix)
endfunction
function! RunNearestTest()
let in_test_file = match(expand("%"), '\(.feature\|_spec.rb\)$') != -1
if in_test_file
call SetLineNumber()
end
call RunTestFile(":" . t:spec_line_number )
endfunction
function! RunNearestTestWithBacktrace()
let spec_line_number = line('.')
call RunTestFile(":" . spec_line_number )
endfunction
map <leader>T :call RunTestFile()<cr>
map <leader>t :call RunNearestTest()<cr>
map <leader>B :call RunTestFileWithBacktrace()<cr>
map <leader>b :call RunNearestTestWithBacktrace()<cr>
map <leader>a :call RunTests('')<cr>
map <leader>c :w\|:!script/features<cr>
map <leader>w :w\|:!script/features --profile wip<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Md5 COMMAND
" Show the MD5 of the current buffer
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! -range Md5 :echo system('echo '.shellescape(join(getline(<line1>, <line2>), '\n')) . '| md5')
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" OpenChangedFiles COMMAND
" Open a split for each dirty file in git
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! OpenChangedFiles()
only " Close all windows, unless they're modified
let status = system('git status -s | grep "^ \?\(M\|A\)" | cut -d " " -f 3')
let filenames = split(status, "\n")
exec "edit " . filenames[0]
for filename in filenames[1:]
exec "sp " . filename
endfor
endfunction
command! OpenChangedFiles :call OpenChangedFiles()
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" InsertTime COMMAND
" Insert the current time
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! InsertTime :normal a<c-r>=strftime('%F %H:%M:%S.0 %z')<cr>
And this is my vim version :
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled May 5 2012 20:53:55)
Included patches: 1-154
Compiled by dougui#osacar
Huge version without GUI. Features included (+) or not (-):
+arabic +autocmd -balloon_eval -browse ++builtin_terms +byte_offset +cindent
-clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
+conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con +diff +digraphs
-dnd -ebcdic +emacs_tags +eval +ex_extra +extra_search +farsi +file_in_path
+find_in_path +float +folding -footer +fork() -gettext -hangul_input +iconv
+insert_expand +jumplist +keymap +langmap +libcall +linebreak +lispindent
+listcmds +localmap -lua +menu +mksession +modify_fname +mouse -mouseshape
+mouse_dec -mouse_gpm -mouse_jsbterm +mouse_netterm -mouse_sysmouse
+mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg -osfiletype
+path_extra -perl +persistent_undo +postscript +printer +profile -python
-python3 +quickfix +reltime +rightleft +ruby +scrollbind +signs +smartindent
-sniff +startuptime +statusline -sun_workshop +syntax +tag_binary
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
-toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo
+vreplace +wildignore +wildmenu +windows +writebackup -X11 -xfontset -xim -xsmp
-xterm_clipboard -xterm_save
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
user exrc file: "$HOME/.exrc"
fall-back for $VIM: "/usr/local/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -I/usr/local/include -g -O2 -D_FORTIFY_SOURCE=1
Linking: gcc -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -rdynamic -Wl,-export-dynamic -L/usr/local/lib -Wl,--as-needed -o vim -lm -ltinfo -lnsl -ldl -lruby1.8 -lpthread -lrt -ldl -lcrypt -lm
What can I do?
Thanks!
I apologize. It was just a problem with my key board. With my french canadian configuration I must to do Ctrl + Alt Car + ]. I will map this keys.
Some simple tests :
To use tags, you must first generate a tag file (which index all the symbols). This is done by executing ctags -R . from the command line or :!ctags -R .from Vim.
After you have executed the command, check that a tag file has been created in the directory. This is a test file, so you can check if the list of symbols looks sensible.
Lastly, you can only jump on a tag, if Vim find the tag file in the path. This is achieve by setting the tags option in your .vimrc
I use the following option:
" search first in current directory then file directory for tag file
set tags=tags,../tags

Copy and paste issue with Mac OS X

When I copy a text from a browser and paste it into a file I opened using vi in Terminal, I get the following unformatted text. Why does vi or the Terminal ignoring the newlines?
Instead of getting the following:
" Restore cursor position to where it was before
augroup JumpCursorOnEdit
au!
autocmd BufReadPost *
\ if expand("<afile>:p:h") !=? $TEMP |
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ let JumpCursorOnEdit_foo = line("'\"") |
\ let b:doopenfold = 1 |
\ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
\ let JumpCursorOnEdit_foo = JumpCursorO
I get this:
" Restore cursor position to where it was before
augroup JumpCursorOnEdit
au!
autocmd BufReadPost *
\ if expand("<afile>:p:h") !=? $TEMP |
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ let JumpCursorOnEdit_foo = line("'\"") |
\ let b:doopenfold = 1 |
\ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
This is the fault of vi, not Mac OS X or Terminal. Vi isn't ignoring the newlines; it's just accumulating indentation. You can fix this by turning autoindent off (:set noai) before pasting and turning it back on afterwards, or, if you're using Vim (which I believe vi is just a symlink to in Mac OS X) you can temporarily turn the paste option on, which disables autoindent along with several other features that can cause problems when pasting text.
Even better than :set paste is to just us the mac clipboard.
If you're using vim 7.3, you can add this to your ~/.vimrc file to get yank (y) and paste (p) to use the Mac`s cut and paste buffer:
if has("macunix")
if v:version >= 703
" Default yank and paste go to Mac's clipboard
set clipboard=unnamed
endif
endif
You can safely put it in your .vimrc even if you don't have Vim 7.3 -- it just won't work.
You can get the latest vim using homebrew and the homebrew-alt repositories. I recommend it!

Vim: gf opens directories, not files

I am trying to configure vim's 'path' and 'suffixesadd' so when I use gf over FILE_NAME, and pwd is /some/dir/, it opens /some/dir/FILE_NAME/File_Name.xml
In vimrc I put:
set suffixesadd=.xml
set path=.,dir/**
But, instead of opening File_Name.xml it opens the directory FILE_NAME
What should I do to configure vim so it looks for files before directories?
PS: Im using gvim in Windows and have NERD plugin active
I don't think this is possible with gf as standard, but you could always do:
" Mapping to make it easier to use - <C-R><C-W> inserts the Word under
" the cursor
nmap gx :call CustomGFOpen("<C-R><C-W>")<CR>
" The function that does the work
function! CustomGFOpen(cursor_word)
" The directory name (e.g. FILE_NAME) is passed as the parameter
let dirname = a:cursor_word
" This is a regular expression substitution to convert
" FILE_NAME to File_Name
let filename = substitute(a:cursor_word, '\(^\|_\)\#<=\([A-Z]\)\([A-Z]\+\)', '\=submatch(2) . tolower(submatch(3))', 'g')
" The extension
let extension = '.xml'
" Join the whole lot together to get FILE_NAME/File_Name.xml
let relative_path = dirname . '/' . filename . extension
" Open that file
exe 'e' relative_path
endfunction

Resources