Search code examples
vimnetrw

how to make netrw list .h and .c files together as pairs?


Can netrw :E display .h and .c files together as pairs?

For example:

file1.h
file1.c
file2.h
file2.c
file3.h
file3.c

Currently my netrw :E list the files in this sequence:

file1.h
file2.h
file3.h
file1.c
file2.c
file3.c

Solution

  • From what I understand from :h netrw-sort-sequence, the g:netrw_sort_sequence setting by default prioritizes .h files over .c files.

    You can add the following to your vimrc file to change the default behavior:

    let g:netrew_sort_sequence = '[\/]$,\<core\%(\.\d\+\)\=,\.[a-np-z]$,\.cpp$,*,\.o$,\.obj$,\.info$,\.swp$,\.bak$,\~$'
    

    Note: the lack of .h and .c extensions.

    Aside about switching files

    There are many (nicer in my opinion) ways to switching between files apart from using a file explorer like netrw aka :Explore. To name a few:

    • Fuzzy Finder e.g. CtrlP
    • Projectionist for well structured projects
    • Using :find and 'path'
    • Using % to represent current file. See :h :_%
    • Using <tab> completion (as well as <c-d>) with :e (also accepts globs)

    For C projects you have some nice .c <-> .h switching options.

    Plugins

    Switching plugins like fswitch which is a C/C++ .h/.c switcher. Please see :h fswitch-setup for more information.

    There are a few other plugins that do similar things: altr and a.vim to name a few.

    Vanilla Vim

    If plugins are not your thing then you can use % tricks. e.g. :sp %<.h

    Or maybe a quick and dirty mapping:

    nnoremap <f4> :e %:p:s,.h$,.X123X,:s,.c$,.h,:s,.X123X$,.c,<cr>
    

    For more information see the following vim wiki page: Easily switch between source and header file