created 2006 · complexity intermediate · author Suresh Govindachar · version 6.0
In an operating system's command-line terminal, one can get a quick peek at a file using commands such as
head etc. In Vim, one way to peek at a file would be to open it in a new buffer -- but there is a way to peek at a file from Vim without having to open it in a buffer, browse it and close the buffer -- one can just view it in Vim's command line! This mode of viewing is facilitated by Vim version 7's support for scrolling (see :help new-scroll-back).
So to peek at a file, we just echo its contents (:help :echo).
One way to implement the idea would be:
:new|r <file_name>|1d|exec 'normal "ayG'|q!|echo @a
One could also do
:echo system('cat foo.bat'), but we are trying to avoid explicit system calls. In version 7, Vim supports
readfile(). But the result of
readfile() is an array of lines -- and these lines would need to be joined to enable viewing; so we have:
:echo join(readfile('foo.bat'), "\n")
Here are two applications that build on the idea presented here.
Yasuhiro Matsumoto's calendar utility script#52 is written to display the calendar in a buffer. For a quick peek at the calendar, one can modify the plugin to support echoing the calendar in Vim's command line, and make a simple map (such as of a RightMouse click) to trigger the display on the command line.
I have the following in my vimfiles\after\ftplugin\index.vim to speed up previewing emails using my mail user agent utility script#1052.
if(v:version < 700) nnoremap <buffer> <Space> :exec "let @a='r '.expand('%:p:h').'/'.substitute( \getline('.'), '\\(^.*\|\\s*\\)\\\|\\(\\s\\s*$\\)', '', 'g') \\\|new\\|@a\\|1d\\| \silent exec 'normal\ d}\"ayG'\\|q!\\|echo\ @a"<CR> else nnoremap <buffer> <Space> :exec "let alist=readfile(expand('%:p:h').'/'. \substitute(getline('.'), '\\(^.*\|\\s*\\)\\\|\\(\\s\\s*$\\)', '', 'g') \)\\| \while(remove(alist, 0) != '') \\\|endwhile \\\|echo\ \substitute(getline('.'), '\\(^.*\|\\s*\\)\\\|\\(\\s\\s*$\\)', '', 'g').\"\n\n\" \\\|echo join(alist,\"\n\")"<CR> endif
Most normal mode commands have a command line counterpart. For example,
exec 'normal "ayG'
could be replaced by