0

It seems like I need to use a lot of shortcut tokens to do what I need in vimscript - which is making my code unreadable, so are there regular function calls for that?

For example, I need to write the following commands for their corresponding action:

Delete all the lines in the current buffer:

:%delete

Read all the files in the current directory:

:.!ls

(Omitting the . would lead to an extra line)

To write forcefully:

:write!

All these tokens like %, ., ! are slightly difficult to ready sometimes, so are there some functional equivalent to those?

Here is what I have so far:

function! InitDir(...)
    let g:previous_directory = g:current_directory
    let g:current_directory = a:0 >= 1 ? a:1 : getcwd()
    :%delete
    :execute ".!ls " . g:current_directory
    :write! 
endfunction

1

Firstly, the tokens have names:

  • % and . are ranges (:h [range])—they are a core part of vim’s ex-command language
  • ! is usually a command suffix to indicate really do it or do something different

Second, in functions, the leading : can be omitted.

Third, space is allowed between range and command—

% delete
. !ls

(I have found that vim’s syntax highlighting doesn’t like it, but the languag accepts it.)

Finally: I strongly recommend you become comfortable with the notation. I find %delete more readable than a mess of setline calls. There are functions that can be put together to do what you want (someone is free to edit them in—I don’t have their names handy). But using Ex as intended is typical for vimmers.

  • Yes, those spaces make it more readable! – Nishant Jun 15 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.