Reordering methods using vim - vim

I have 2 methods in a source file:
def Foo
puts "hello"
puts "bar"
end
def Bar
puts "hello"
puts "bar"
end
I would like to swap the order of the methods, so Bar is first.
Assuming the cursor is on the d in def Foo, the simple way is to:
shift v -> jjjj -> d -> jjj -> p -> O -> esc
But that feels a little long winded and does not account well for arbitrarily long methods:
What is the most efficient way to do this in Vim, keystroke wise?
EDIT
Keep in mind, I would like the solution to account for a situation where the methods are in a context of a big class, so G is probably best avoided

Assuming the cursor is somewhere in the first method, press dap}p and they should be swapped.
What dap does is simply "delete a paragraph". Try :help object-select to learn other way of deleting/selecting text objects in VIM.
EDIT: Replaced G with } in the command.

Similar to Spatz's
d}}p
delete to the next blank line (below Foo), skip to the next blank line (below Bar), paste.

Found another method ( from godlygeek on #vim ):
with:
def function():
first
first
first
def lol():
second
second
second
From line 1, count up until the 'def lol', which is 5. Then:
:1,5m$

A couple of ways off the top of my head. You could say
5dd/end[enter key]pO
Deletes five lines, searches for end, places the lines underneath, adds a space.
If you have VimRuby installed, I believe you can use % to jump between def and end. In that case, you could say
v%x5jpO
Edit: I defer to spatz on this :P

From line 1, 5ddGp , or 5dd:5p is the most concise/shortest I can think of.

personally, I would go '4dd' then down under bar and press 'p', but I'm not a vim guru

Related

How to quickly edit determinate part of code inside different similar lines

I have this problem I'm adjusting a code I've made I have a structure like this:
Apple1 = Fruit("ss","ss",[0.1,0.4],'w')
PineApple = Fruit("ss","ss",[0.315,0.4],'w')
Banana = Fruit("ss","ss",[0.315,0.280],'w')
...
...
Instead of "ss"I would like to type further information like "Golden Delicious". For the moment I'm simply deleting "ss"clicking over it and then replacing it with the information I want to insert. I'm sure there is a faster way to do it, I've tried something with VIM macros but I can't figure out how to "Raw input" my data.
I've try simply to substitute it with Spyder, but is slow because I have to click substitute every time, with VIM for what I've try is the same.
Then I wonder how insert something else after 'w'...
This is an example of an final output only to understand better the question :
Apple1 = Fruit("Golden Delicous","red",[0.1,0.4],'w')
PineApple = Fruit("Ananas comosus","green",[0.315,0.4],'w')
Banana = Fruit(" Cavendish banana","yellow",[0.315,0.280],'w')
...
...
I reformulate the question: which is the faster way to change "ss", for the moment I'm clicking over "ss" delate "ss" and write e.g "Golden Delicous" but is very slow. What I would like is that for every single ss the editor ask me to insert something to replace the single ss.
e.g. first ssin the fist line: I want to replace it typing something else e.g. "Golden Delicous" second ssin the first line I want to replace it typing somethingelse e.g. red. First ssin the second line I want to replace it with s.e. e.g. Ananas comosussecond ssin the second line I want to replace with s.e. e.g. green and so on.
I'm sure there is an answer for this somewhere but I can't find it!
Please if you down vote explain me why so I can improve it!
As far as I understand, the data that you want to substitute for "ss" does not have regular structure, so you will need to enter it by hand.
In Vim you would do it like this:
Place the cursor over the first "ss", then press * and then N.
Press ce, enter the new data (e.g. "Golden Delicious"), then leave Insert mode by pressing Escape.
Press n to jump to the next instance of "ss".
Repeat steps 2 and 3 ad libitum.
Look up :h * and :h n for more information.
I would do it like that:
:%s/ss/\=input('Replacement: ')/gc
This queries you for each occurrence. With the /c flag, the display is even updated during the loop (at the cost of having to additionally answer y for each occurrence); without the flag, you would need to keep track of where you are yourself.
You can use a function that searches the whole file substituting all "ss" strings with values from arrays populated with the replacement data:
function! ChangeSS()
let ss1 = ['Golden Delicous', 'Ananas comosus', 'Cavendish banana']
let ss2 = ['red', 'green', 'yellow']
call cursor(1, 1)
let l = "ss2"
while search('"ss"', 'W') > 0
if l == "ss1"
let l = "ss2"
else
let l = "ss1"
endif
execute 'normal ci"' . remove({l}, 0)
endwhile
endfunction
It uses a reference variable (l) that exchanges which array you want to extract data from. ss1 is for first appearance of "ss" in the line and ss2 for the second one.
Run it like:
:call ChangeSS()
That (in my test) yields:
Apple1 = Fruit("Golden Delicous","red",[0.1,0.4],'w')
PineApple = Fruit("Ananas comosus","green",[0.315,0.4],'w')
Banana = Fruit("Cavendish banana","yellow",[0.315,0.280],'w')

Vim - delete until (inclusive) character in multiple lines

I have this code:
def foo(c: Char) = c match {
case 'a': 'B'
}
My cursor is on the space after =. I want to delete everything until, including, the }. How can I do that?
Can I do the same where the cursor is anywhere on the first line? Anywhere in the block (and place the cursor after the =)?
d/}/e
does the job.
d/} deletes until the } but adding the /e flag moves the cursor on the last char of the match, effectively deleting everything between the cursor and the }, inclusive.
Using visual selection works too, in a slightly more intuitive way:
v/}<CR>d
Try with this: d%.
The d is for delete and the % moves between braces.
This should work:
d}
This deletes one paragraph forward.
You can achieve something like this with the EasyMotion plugin.

Move lines matched by :g to the top of the file

I have a large text file with several calls to a specific function method_name.
I've matched them using :g/method_name.
How would I move them to the top of the file (with the first match being on the top)?
I tried :g/method_name/normal ddggP but that reverses the order. Is there a better way to directly cut and paste all the matching lines, in order?
Example input file:
method_name 1
foo
method_name 2
bar
method_name 3
baz
Example output file:
method_name 1
method_name 2
method_name 3
foo
bar
baz
How about trying it the other way around: moving the un-matched lines to the bottom:
:v/method_name/normal ddGp
This seems to achieve what you want.
I think you can achieve the desired result by first creating a variable assigned
to 0:
:let i=0
And then executing this command:
:g/method_name/exec "m ".i | let i+= 1
It basically calls :m passing as address the value of i, and then increments
that value by one so it can be used in the next match. Seems to work.
Of course, you can delete the variable when you don't need it anymore:
:unlet i
If the file is really large, count of matching entries is small, and you don't want to move around the entire file with solution v/<pattern>/ m$, you may do this:
Pick any mark you don't care about, say 'k. Now the following key sequence does what you want:
ggmk:g/method_name/ m 'k-1
ggmk marks first line with 'k.
m 'k-1 moves matching line to 1 line before the 'k mark (and mark moves down with the line it is attached to).
This will only move a few matching lines, not the entire file.
Note: this somehow works even if the first line contains the pattern -- and I don't have an explanation for that.
For scripts:
normal ggmk
g/method_name/ m 'k-1

How can I quickly add something to a few lines in vim?

I'm trying to get away from my arrow use but there is one thing I've yet to solve without using the arrow keys. Take this example:
var1 = "1"
var2 = "2"
var3 = "3"
var4 = "4"
Now I want this to be:
var_1 = "1"
var_2 = "2"
var_3 = "3"
var_4 = "4"
Using arrows I would just goto the var1, insert and add the underscore and then arrow down and do the same thing. The problem with using hjkl is I can't be in insert mode so I have to esc out, move down, insert...rinse repeat which required more work. Is there another way to accomplish this?
You can also use a visual block insert:
go to the "1" in "var1"
press CTRL+V
go down with j to select all the rows you wish to affect
I (that's capital i)
_
<ESC>
The underscore should now be inserted at the correct place in all the rows selected (for some reason it takes a second for it to happen on my machine)
There are many ways to do this. Using movement commands for example:
1G0 → Go to the start of the first line
f1 → go to the first occurence of "1"
i_<ESC> → insert "_" and go back to normal mode
j. → go down a line and repeat the insert command
j. → go down a line and repeat the insert command
...
Or, better yet, use an "ex" command:
:%s/var/var_/
Or even with the visual block command, as johusman notes.
Assuming you're at line 1, character 1...
Using a macro:
qqfra_<Esc>+q3#q
q Record macro
q Into register q
f find
r 'r'
a append
_ underscore
Esc Normal mode
+ Start of next line
3 Three times
# Play macro
q from register q
Par 11.
Or (better) using substitute:
:%s!r!&_<CR>
Par 9!
[Sorry... too much VimGolf!]
I tend to prefer :substitute over the visual block mode.
%s/var\zs\ze\d/_/
I always have line numbers turned on, so I'd do e.g.
1,4 s/var/var_/
This is similar to the
% s/var/var_/
answer, but it only functions on the named lines. You can use visual mode to mark the lines, if you don't like typing the range (the 1,4 prefix) in your command.

How do you select the entire PHP function definition?

In PHP, if I have a function such as:
function test($b) {
var $a = 0;
while ($a < b) {
$a += 3;
}
return $a;
}
and the cursor is on the $a += 3 line, is it possible to quickly select the entire function?
"v2aB" would select everything including the function braces but not the declaration function test($b)
Press V after the selection command you post, to convert the selection to line selection, and it will select the function declaration:
v2aBV
It's been a long time since this question was asked and answered, but I will add my own answer because it's the one I was looking for and none of the others work exactly like this one:
nnoremap vaf ?func.*\n*\s*{<cr>ma/{<cr>%mb`av`b
vmap af o<esc>kvaf
The first mapping, "Visual around function" or vaf, will jump back to the start of the function definition, regardless that the { is in the same line or the next one, and even if it's a lambda function, and visually select it characterwise to it's ending bracket. This works in PHP, Javascript and Go.
The user can then press V to turn to linewise select mode if she wants to.
The only problem that I found is that when I am in the body of a big function, but below a line that uses a lambda (let's say "small") function, this will stop searching at the beginning of the small function and select it's body instead of reaching the start of the big function and select all of its body.
function show_video_server(v_server) {
// this whole function should get selected
var something = function(){ /* this function gets selected */ };
// | the cursor is here when I type "vaf"
}
As a workaround I use the second mapping: vmap af o<esc>kvaf. It feels like a repetition or expansion of the selection. What it really does is abandon the selection and go to the line before it, and then try it agan. If the "big" function uses several lambda functions the user has to repeat the af several times to reach the big one.
Usually, vaf es enough. Sometimes vaf af or vaf af af is needed. Anyway, it's the closest I could get to what I wanted, so this is the version I'm using.
Here's a mapping that seems to work very well, no matter the nesting level.
:map t ? function <CR>f{vaBV
Here's another method that will work if you have function-level folding turned on: z c v
That closes the current fold and selects it, but it leaves it closed. If you want it to remain open: z c v $
If you have block-level folding turned on, you would have to close twice, since you're inside the while loop, so: 2 z c v
To enable PHP class/function folding: let php_folding = 1
simple way
nmap vaf va}V
I like this
nmap vaf [{?function<CR>:nohl<CR>vf{]}
if ‘{’ is in new line
nmap vaF [{?function<CR>:nohl<CR>v/{<CR>]}
Yet another way. This should select the entire function definition regardless of your cursor position within the definition, not just when you're at the $a += 3 line.
Use this in normal mode (<CR> means press enter)
?func<CR>V/{%
Explanation of each part:
?func search backward for the word "func" (the idea is to get to the first line of the function definition)
V go to visual line mode
/{ search forward for the opening brace (I didn't use f{ because the opening brace might be on a separate line)
% go to the matching brace
If you are using OOP programming this works (it looks for extra words before function[public, private, protected])
nmap vaf [{?\S* function<CR>:nohl<CR>v/{<CR>]}
As a bonus here is a wrapper around if
nmap vai [{?if<CR>:nohl<CR>v/{<CR>]}

Resources