DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on • Updated on

Access your vim v:oldfiles from zshell

Intro

I have always wanted to get my vim oldfiles (the most recent accessed files on vim/nvim) directly from my shell. Of course, in vim you can do:

:bro[wse] o[ldfiles][!]
Enter fullscreen mode Exit fullscreen mode

But I wanted something different, and today I figured it out, of course, with some help, see references, an elegant way to solve this issue:

function old(){
    [[ -f /tmp/oldfiles.txt ]] && \rm /tmp/oldfiles.txt
    vim -c 'redir >> /tmp/oldfiles.txt | silent oldfiles | redir end | q'

    local fname

    FILES=()
    for i in $(awk '!/man:/ {print $2}' /tmp/oldfiles.txt); do
        [[ -f $i ]] && FILES+=($i)
    done

    fname=$(printf "%s\n" "${FILES[@]}" | awk '!a[$0]++' | fzf) || return

    vim "$fname"
}
Enter fullscreen mode Exit fullscreen mode

Generating a list of oldfiles

vim -c 'redir >> /tmp/oldfiles.txt | silent oldfiles | redir end | q'
Enter fullscreen mode Exit fullscreen mode

To make sure the list is always updated I also have this test:

[[ -f /tmp/oldfiles.txt ]] && \rm /tmp/oldfiles.txt
Enter fullscreen mode Exit fullscreen mode

If the file exists we remove it

Creating a variable so we can send a file name to the FZF

local fname
Enter fullscreen mode Exit fullscreen mode

Creating an array to store the full list of v:oldfiles content

FILES=()
Enter fullscreen mode Exit fullscreen mode

Filtering the file list

for i in $(awk '!/man:/ {print $2}' /tmp/oldfiles.txt); do
    [[ -f $i ]] && FILES+=($i)
done

fname=$(printf "%s\n" "${FILES[@]}" | awk '!a[$0]++' | fzf) || return
Enter fullscreen mode Exit fullscreen mode

In the awk command we restrict our awk filtering getting rid of any manpage we have accessed !/man:/. Then we test if the item is a file [[ -f $i ]] and add them to the our arry FILES with FILES+=($i).

Passing an array to FZF in separate lines

printf "%s\n" "${FILES[@]}"
Enter fullscreen mode Exit fullscreen mode

Removing duplicated entries

awk '!a[$0]++'
Enter fullscreen mode Exit fullscreen mode

Bu if we give up our search?

|| return
Enter fullscreen mode Exit fullscreen mode

Keybind (zsh) to easily call this function:

# Ctrl-Alt-o
bindkey -s '^[^O' 'old^M'
Enter fullscreen mode Exit fullscreen mode

References:

Top comments (0)