vehomzzz
vehomzzz

Reputation: 44568

how to move a word to the beginning of the sentence in vim

say I have this line

= function (x, y, word);

and I want to convert it to

 word = function (x,y);

Thus far, I have been manually selecting the word, then 'x', and then paste it at the beginning. And then I would remove unnecessary comma.

Is there a more efficient way to accomplish the same thing?

Upvotes: 3

Views: 3524

Answers (6)

MBO
MBO

Reputation: 30985

Don't create weired functions or macros, as many advanced users may suggest you, but learn simple commands, which can help you when you would need to make similar, but slightly different substitution.

My solution would be: place cursor on the comma, and type: xxdw^Pa <C-[>

Description:

  • xx - delete comma and space
  • dw - delete word
  • ^ - place cursor on the beginning of text in line
  • P - place deleted text before cursor
  • a - add space after word
  • <C-[> - escape to return to normal mode, you can also press <ESC> if you like, or don't press at all

And how to place cursor in comma? Learn about f,, F,, t,, T,, w, b and e to move faster around your text.

Upvotes: 11

Habi
Habi

Reputation: 3300

Place cursor over word and type:

"0diw    delete word and store it in register 0
dF,      delete backwards up to and including ,
^        place cursor at first character in line
"0P      paste word

I would suggest to map this to a key.

Upvotes: 0

martsbradley
martsbradley

Reputation: 158

Or you could use a regular expression.

    :s/\(^.*\), \(\a\+\)\();\)/\2\1\3/

(Match up to the last comma) -> \1

(match last argument) -> \2

(Match closing brace and semicolon) -> \3

The reorder the matched terms as you need.

Upvotes: 1

Nir Levy
Nir Levy

Reputation: 4740

:%s/\(.*\),\([^)]*\)/\2\1/

EDIT:removed /g

EDIT2: the %s is only if you want to do this for the entire file. if you just want to do this for the current line then replace % with . (a dot)

Upvotes: 4

Randy Morris
Randy Morris

Reputation: 40927

I'd suggest recording a macro: (starting at the beginning of the line) qq2f,2xdw0Pa <esc>0jq, then running that macro wherever you need it: @q.

Upvotes: 1

John Feminella
John Feminella

Reputation: 311496

Try this: :dw to cut the current word, move to beginning of line, then :p to paste the buffer there.

Upvotes: 0

Related Questions