2

I wonder how to open a file from a directory under the cursor.

I have managed to do it for simple directories, but it requires they are one single word and are located in the current working directory: In commandline mode, with :e and then <ctrl+r> <ctrl+w> for pasting the word under cursor, and then using tab for example for autocompletion, or <Enter> for opening the :Explore view of it.

However I have no idea for more complex directories.

Is there a solution ?

  • I'm not sure what you mean by "complex directories", but <c-r><c-a> will expand the WORD (where <c-r><c-w> expands a 'word'). Also, gf will open netrw if the file under the cursor is a directory. Of course, that only works if the file is in the path (:h path). – Biggybi May 28 at 12:35
  • 1
    Both of your suggestions answer my point. <c-r><c-a> is great. And gf is just exactly what I was searching for. – Stephane Rolland May 28 at 12:56
4

Biggybi mentions gf in the comments, and it is usually the best way to go. It takes you to the file (in your path) under the cursor. This should work for directories, too.

Alternately, you could use :edit <cfile> or alternatives, as explained here.

| improve this answer | |
  • Sorry, I saw your answer once I posted mine... <cfile> is so good! – Biggybi May 28 at 13:08
  • @Biggybi no problem :) I sniped you from the comments a bit anyway. Multiple good answers is usually a good thing! – D. Ben Knoble May 28 at 13:46
  • 3
    "Beware the man of one book." - Thomas Aquinas – Biggybi May 28 at 13:50
  • I upvoted both of your answers, but the :edit <cfile> won for the chosen answer. I started using it in parallel with other suggestions, and that's a great addition to my everyday commands. – Stephane Rolland May 29 at 11:39
2

The simple way to open a file under cursor is gf (if it's in your path). When the file is a directory, this will open netrw (the builtin file explorer) for that directory.

You can also use :wincmd f for the same result.

Thus, you can set a mapping to open the file in a vertical split for example:

nnoremap g :vertical wincmd f

This can be done with <c-w><c-f>.

A more useful one could be to open the folder in a vertical split on the far-left hand side:

nnoremap g<c-f> :Lexplore <cfile><cr>

From command line, you can use <c-r><c-a> to expand the WORD. A WORD is a word delimited by white spaces, as opposed to word which is delimited by -, _, and other special characters.

Edit: <cfile>, as mentionned by D. Ben Knoble, is way better.

| improve this answer | |
  • 1
    PS theres even <C-w>F! – D. Ben Knoble May 28 at 13:47
  • 1
    And even <c-w><c-f>... that mimics my mapping (or is it the other way around?). I'll give a twist to it to make it original. – Biggybi May 28 at 13:55

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.