I have a section in my .vimrc file that sets the title of the terminal to the name of the file that is opened with vim. However, this breaks down when using :edit to go from one file to the next from within vim, as it stays the same. I gather that this is because, by default, the .vimrc file is only run when vim is launched.
Is there a way to get vim to "watch" for the :edit, :e, and any other commands, and then run :so $MYVIMRC, which reloads the .vimrc?
Alternatively,is there some built in feature that set the terminal title to the file name which I've somehow overlooked?
Section mentioned in .vimrc
" Apply filename to terminal session title
"" Doesn't work when changing file using :edit
let path_list = reverse(split(expand("%:p"),"/"))
if len(path_list) > 0
let &titlestring = path_list[0]
if &term == "screen"
set t_ts=^[k
set t_fs=^[\
endif
if &term == "screen" || &term == "xterm"
set title
endif
endif
This does this job
autocmd BufEnter * :so $MYVIMRC
Update
As suggested by Doktor, it's better to do this in a function, and just call this upon BufEnter. Here's how that works.
function SetTitle()
let path_list = reverse(split(expand("%:p"),"/"))
if len(path_list) > 0
let &titlestring = path_list[1] . "/" . path_list[0]
if &term == "screen"
set t_ts=^[k
set t_fs=^[\
endif
if &term == "screen" || &term == "xterm"
set title
endif
endif
endfunction
autocmd BufEnter * :call SetTitle()
Related
I'd like the netrw explorer to automatically close after opening a file.
For example:
:Lex to open file explorer
Open file
Upon open, the file explorer automatically closes.
I've tried setting:
autocmd FileType netrw setl bufhidden=wipe
But it doesn't work.
Rest of relevant .vimrc settings:
let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_altv = 1
let g:netrw_winsize = 25
noremap <C-x> :Lex<CR>
autocmd FileType netrw setl bufhidden=wipe
I took this snippet from another Stack Overflow answer (linked below) and added it to the BufWinEnter event to solve this problem.
" Close after opening a file (which gets opened in another window):
let g:netrw_fastbrowse = 0
autocmd FileType netrw setl bufhidden=wipe
function! CloseNetrw() abort
for bufn in range(1, bufnr('$'))
if bufexists(bufn) && getbufvar(bufn, '&filetype') ==# 'netrw'
silent! execute 'bwipeout ' . bufn
if getline(2) =~# '^" Netrw '
silent! bwipeout
endif
return
endif
endfor
endfunction
augroup closeOnOpen
autocmd!
autocmd BufWinEnter * if getbufvar(winbufnr(winnr()), "&filetype") != "netrw"|call CloseNetrw()|endif
aug END
Original answer here:
https://vi.stackexchange.com/questions/14622/how-can-i-close-the-netrw-buffer
This one in particular https://vi.stackexchange.com/a/29004
Try using :Explore, :Sexplore, :Hexplore, or :Vexplore instead of :Lexplore. The primary reason for :Lexplore is to have a persistent explorer on one side or the other; the others already go away when you select a file with <cr>.
When I run vim it puts me in --REPLACE-- mode, how I put it in command mode or insertion mode.
( And how to activate these commands by default when I run vim?
- :set nu
- :set cc=80
)
vimrc
if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
set fileencodings=ucs-bom,utf-8,latin1
endif
set nocompatible " Use Vim defaults (much better!)
set bs=indent,eol,start " allow backspacing over everything in insert mode
"set ai " always set autoindenting on
"set backup " keep a backup file
set viminfo='20,\"50 " read/write a .viminfo file, don't store more
" than 50 lines of registers
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
" Only do this part when compiled with support for autocommands
if has("autocmd")
augroup redhat
autocmd!
" In text files, always limit the width of text to 78 characters
" autocmd BufRead *.txt set tw=78
" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal! g'\"" |
\ endif
" don't write swapfile on most commonly used directories for NFS mounts or USB sticks
autocmd BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set directory=~/tmp,/var/tmp,/tmp
" start with spec file template
autocmd BufNewFile *.spec 0r /usr/share/vim/vimfiles/template.spec
augroup END
endif
if has("cscope") && filereadable("/usr/bin/cscope")
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
" add any database in current directory
if filereadable("cscope.out")
cs add $PWD/cscope.out
" else add database pointed to by environment
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
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
filetype plugin on
if &term=="xterm"
set t_Co=8
set t_Sb=[4%dm
set t_Sf=[3%dm
endif
" Don't wake up system with blinking cursor:
" http://www.linuxpowertop.org/known.php
let &guicursor = &guicursor . ",a:blinkon0"
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Dec 21 2016 17:00:20)
Included patches: 1-160
I am trying to write a function to cause vim to open the relative header/source file in a split window.
What I have works (see below) apart from the file it opens in the split doesn't have syntax highlighting.
function! SplitOther()
let s:fname = expand("%:p:r")
if expand("%:e") == "h"
set splitright
exe "vsplit" fnameescape(s:fname . ".cpp")
elseif expand("%:e") == "cpp"
set nosplitright
exe "vsplit" fnameescape(s:fname . ".h")
endif
endfunction
autocmd! BufReadPost *.h,*.cpp call SplitOther()
I have tried appending syntax on to the command (just before the endfunction) but that doesn't seem to want to work.
I think it happens when the file isn't in a buffer before splitting? I'm not 100% sure though.
Edit
I change my function to have allow the definition of file pairs, I'm not sure if it will change my question at all so here's the extended version:
function! SplitOther()
let s:pairs = [ [ "h", "cpp" ], [ "vert", "frag" ] ]
let s:fname = expand("%:p:r")
for [s:left, s:right] in s:pairs
if expand("%:e") == s:left
set splitright
exe "vsplit" fnameescape(s:fname . "." . s:right)
elseif expand("%:e") == s:right
set nosplitright
exe "vsplit" fnameescape(s:fname . "." . s:left)
endif
endfor
endfunction
autocmd! BufReadPost * call SplitOther()
Got it!
When the file was being loaded into the vsplit it's filetype wasn't being set.
I noted that when vsplit is called the new split grabs focus and that is the window that does not have syntax highlighting so you can simply add exe "filetype" "detect" at the end of the function to tell vim to detect the filetype of the current window.
The result:
function! SplitOther()
let s:pairs = [ [ "h", "cpp" ], [ "vert", "frag" ] ]
let s:fname = expand("%:p:r")
for [s:left, s:right] in s:pairs
if expand("%:e") == s:left
set splitright
exe "vsplit" fnameescape(s:fname . "." . s:right)
break
elseif expand("%:e") == s:right
set nosplitright
exe "vsplit" fnameescape(s:fname . "." . s:left)
break
endif
endfor
exe "filetype" "detect"
endfunction
autocmd! BufRead * call SplitOther()
The problem is that filetype detection is triggered by an autocmd, but by default, autocommands do not nest (cp. :help autocmd-nested).
Also, by using :autocmd! with a bang, you're clearing all other such global autocmds; this might affect other customizations or plugins! You should define your own scope via :augroup, then it's safe. Taken together:
augroup MyAltSplitPlugin
autocmd! BufReadPost * nested call SplitOther()
augroup END
Over on askubuntu.com I was told how to run python on Vim. I am testing the set up which works with the code 1st or 2nd code python code at using python to solve a non linear equation.
The only thing I have done different was added print(a) as the last line. I ran this yesterday from the shell and it worked perfectly. Could someone let me know what is going wrong?
Ok so I corrected the vimrc with the appropriate question marks,
chmod +x ~/path/to/file/hw6problem2.py
Then from vim I ran
:Shell ./#
but I received the same syntax error again. (Does the file have to be saved as .sh because I can't get any .py files to run?)
dustin#dustin:~$ vim /home/dustin/Documents/School/UVM/Engineering/OrbitalMechanics/hw6problem2.py
File "hw6problem2.py", line 14
a0 = max(s/2, (s - c)/2)
^
SyntaxError: invalid syntax
shell returned 1
Press ENTER or type command to continue
vimrc
syntax on
au BufWinLeave * mkview "records settings
au BufWinEnter * silent loadview "reloads settings
set nu "puts line numbers on
set ic "case insensitive
set foldmethod=syntax "for the latex-suite
set autoread "autoload when files in the buffer have been modified
set autochdir "autochange directory
"set wrap
set wrap
" set lines=50 columns=80
" resizes window
:map g1 :set lines=20<CR>:set columns=80<CR>
:map g2 :set lines=50<CR>:set columns=80<CR>
:map g3 :set lines=50<CR>:set columns=170<CR>
:map <F6> :! firefox % &<CR>
:map E Ea
"set autoindent
set tabstop=4
set shiftwidth=2
set expandtab
set smartindent
"
" Stuff for latex-suite
" REQUIRED. This makes vim invoke Latex-Suite when you open a tex file.
" It also allows you to set different actions for different filetypes
" in ~/.vim/after/ftplugin/*.vim
filetype plugin on
set shellslash
" IMPORTANT: grep will sometimes skip displaying the file name if you
" search in a singe file. This will confuse Latex-Suite. Set your grep
" program to always generate a file-name.
set grepprg=grep\ -nH\ $*
" OPTIONAL: This enables automatic indentation as you type.
filetype indent on
" OPTIONAL: Starting with Vim 7, the filetype of empty .tex files defaults to
" 'plaintex' instead of 'tex', which results in vim-latex not being loaded.
" The following changes the default filetype back to 'tex':
let g:tex_flavor='latex'
let g:Tex_ViewRule_pdf = 'okular'
"""""""""""""""""""""""""""""""""""""""
" => Shell command
"""""""""""""""""""""""""""""""""""""""
command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
let isfirst = 1
let words = []
for word in split(a:cmdline)
if isfirst
let isfirst = 0 " don't change first word (shell command)
else
if word[0] =~ '\v[%#<]'
let word = expand(word)
endif
let word = shellescape(word, 1)
endif
call add(words, word)
endfor
let expanded_cmdline = join(words)
rightbelow new
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
call setline(1, 'You entered: ' . a:cmdline)
call setline(2, 'Expanded to: ' . expanded_cmdline)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !'. expanded_cmdline
1
endfunction
This is likely to be a python issue.
On a side not, there's a great shell function for executing scripts and redirecting output to vim buffer (split window).
Syntax to execute current script (you should have chmod +x and shebang line):
:Shell ./#
In order to add the function, add this to .vimrc:
command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
let isfirst = 1
let words = []
for word in split(a:cmdline)
if isfirst
let isfirst = 0 " don't change first word (shell command)
else
if word[0] =~ '\v[%#<]'
let word = expand(word)
endif
let word = shellescape(word, 1)
endif
call add(words, word)
endfor
let expanded_cmdline = join(words)
rightbelow new
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
call setline(1, 'You entered: ' . a:cmdline)
call setline(2, 'Expanded to: ' . expanded_cmdline)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !'. expanded_cmdline
1
endfunction
https://github.com/ruslanosipov/dotfiles/blob/master/.vimrc#L137
I can get the vim title to display on my window by doing this:
let &titlestring = expand("%:t") . " # " . hostname()
if &term == "screen"
set t_ts=^[k
set t_fs=^[\
endif
if &term == "screen" || &term == "xterm"
set title
endif
But the tabs will say "Default".
From the commandline I can do this:
echo -ne "\e]1;hello world\a"
And that'll show "Hello World" in my tabs.
Is there a way to have vim write this stuff to my tab instead of title instead?
This works for me:
" Set the title of the Terminal to the currently open file
function! SetTerminalTitle()
let titleString = expand('%:t')
if len(titleString) > 0
let &titlestring = expand('%:t')
" this is the format iTerm2 expects when setting the window title
let args = "\033];".&titlestring."\007"
let cmd = 'silent !echo -e "'.args.'"'
execute cmd
redraw!
endif
endfunction
autocmd BufEnter * call SetTerminalTitle()
Source: https://gist.github.com/bignimbus/1da46a18416da4119778
I don't have iTerm, so I can't test this, but try adding this to your .vimrc:
set t_ts=^[]1;
set t_fs=^G
Type CTRL-V Escape for ^[ and CTRL-V CTRL-G for ^G.
Just to piggy back on user2486953's comment above.
I was able to accomplish this with two super simple lines in my ~/.vimrc:
set title
set titlestring=%f
(Lower case 'f' gives me just the filename, whereas capital gives the full path too)
i.e. I didn't have to set anything with escape sequences like the accepted answer above. I am running gnome-terminal but I don't understand why iTerm2 would be any different for a VI setting.