Swap two words in Vim using text objects

Swap two words is a good exercise in Vim and its commands, including the text objects.

In this article I will try to solve two possible scenarios for the exchange of position of two words without using any changes to the basic Vim settings.

First scenario

Two words followed by other words or almost a space.

The example:

  TWO ONE THREE

In this scenario you can use the same text object solution from both the first and second word but followed by different commands.

  1. With the cursor on the first word you can use the following text sequence: dawwP
  2. With the cursor on the second word you use the other text sequence: dawbP

Let’s analize the two different text sequences.

The string daw is the text object command and it’s common to the two solutions.

More specifically:

  • d is the command for delete
  • a is the command for all (spaces included)
  • w is the object of the command: the word

Then the command deletes the word and all the spaces that follow it.

  • the first solution continues whit the letter w that moves the cursor to the beginning of the following word.

  • the second solution continues with the letter b that moves the cursor to the beginning of the previous word

  • both the solutions end with a P (uppercase) that’s for put the last deleted text object before the cursor.
    Remember that in the text object are contained also the spaces.

After both solutions you get the inversion of the first two words including the spaces:

    ONE TWO THREE

Second scenario

Two words NOT followed by other words or spaces.

This is a more challenging scenario because the words end immediately after the second one.

If we use the previous solutions we would have two words attached to each other.

So we have to use an expedient to add a space after the exchange of words.

We can, for this, take advantage of the properties of the J command and a different version of text object.

The example:

TWO ONE
  • With the cursor on the second word you can use the following sequence: diwOpJ in which

  • diw is the text object to delete che word without following spaces

  • O (letter o uppercase) adds a line above
  • “ enters the normal mode
  • p puts the text object in the upper (current) line
  • J joins the upper line to the lower one adding a space

The command diw deletes the word but not the spaces that follow it.

After this solution you get the inversion of the two words with a space added:

ONE TWO

If you need to delete che remaining space after the secondo word you can use $x.

That’s all.

Thank You.

Comments

Popular posts from this blog

Vim: Cut, Copy and Paste to and from the system clipboard

Vim: searching for text containing a slash or a question mark