# How can I make the “gn” motion wrap to the beginning of the file?

gn is a very useful command that selects the next search result. For example, if I insert

foo bar baz


into a file, move to the beginning, type /[aeiou]., and press gn, it would select oo in a visual selection. Pressing dgn would delete that and then select ar in a visual selection.

However, let's say I have the following file (where [x] represents the cursor):

This is some text.

Blah blah blah.

Lorem ipsum.

Foo bar b[a]z quux.

and I've searched for . . (any character, a space, then any character). Pressing dgn would delete the z q, since it's the first search result after my cursor. However, pressing gn from here now has no effect, since this motion does not "wrap around" back to the beginning of the file like n does.

How can I make gn wrap to the first search result if there are no results after the cursor (but still have no effect (or give an error, without moving the cursor) if there are no more results in the entire file), just like the n command?

After discussion in the comments: This may be system-specific. I'm running Vim 7.4.52 on Ubuntu 14.04.

• Turns out gn wraps for me. Now I have to figure out what enables it. Ok - this wraps even with -u NONE. – muru Feb 7 '15 at 4:08
• @muru Weird... it still doesn't wrap with -u NONE for me. What platform/version? I'm on Vim 7.4.52 on Ubuntu 14.04. – Doorknob Feb 7 '15 at 4:16
• 7.4 (included patches 1-580), Arch Linux. I'll test on a Ubuntu system. - Yep, doesn't wrap on Ubuntu. – muru Feb 7 '15 at 4:17
• @muru Hmm, interesting... I've edited another line into the question. – Doorknob Feb 7 '15 at 4:21
• What about ggdgn? Or :%s/. ./gc? – romainl Feb 7 '15 at 10:21

Hopefully there would be a better solution, but one solution is to upgrade.

For Ubuntu-based systems there's a PPA you can try (if you're unfamiliar with PPAs, see What are PPAs and how do I use them?). It currently has Vim 7.4.589, and gn wraps at least as of 7.4.580.

sudo apt-add-repository ppa:pi-rho/dev
sudo apt-get update
sudo apt-get install vim


Looking at the README, I think the particular patch that introduced this was 76:

1894  7.4.076  "cgn" does not wrap around the end of the file


So if you're comfortable with recompiling vim to add a patch, this should be it.