2015-03-31 17 views
3

我試圖添加一個屬性到Java類,使用VIM作爲編輯器。 因此我想我可以使用一個命令來簡化我所有樣板代碼的工作。 如:如何複製匹配模式的行,並在一個命令中修改第二行?

含有 「atributeA」 所有的線,像這樣的

this.attributeA=attributeA //basic constructor 

應該變成

this.attributeA=attributeA //basic constructor 
this.attributeB=attributeB //basic constructor 

這可能嗎?

+1

太少的信息來回答這個問題。 – 2015-03-31 12:09:21

回答

4

具有解決方案是一個班輪的要求似乎 有點奇怪,因爲你可以,如果你喜歡的 任何按鍵序列或任何功能或命令分配給按鍵在Vim中 。

這就是說,這種類型的事情是Vi的麪包和黃油。嘗試:

:g/attributeA/ copy . | s//attributeB/g 

其中

:g/pattern/ command1 | command2 | ... 

在每一行匹配pattern執行命令(參見:help :global

copy . 

拷貝當前行(見:help :copy)之後的通過:g匹配地址.(意思是當前行)和

s/pattern/replacement/g 

然後在當前行上執行替換(請參閱:help :substitute),即您剛創建的副本。末尾的g標誌會導致對行中的所有匹配模式執行替換,而不僅僅是第一個。另請注意,我將搜索模式留空:Vim會記住上一個:global:substitute命令中使用的最後一個搜索模式,以方便起見。

+0

謝謝,它完成了我想象中的工作。 – sdaniel 2015-03-31 15:31:38

+0

不錯!不知道'複製'。 – bheeshmar 2015-04-08 21:58:24

0

你確切的樣品是很容易實現與:

yy 
p 
:s/A/B/g 

但它是完全可能的,你想要的東西更通用。如果是這種情況,你應該編輯你的問題。

+0

我需要一些能夠匹配我的模式的所有行,而不僅僅是一個。 – sdaniel 2015-03-31 12:15:23

+0

':g/attributeA/norm! yyp:s/A/B ' – romainl 2015-03-31 12:21:32

+0

Thansk!它根據需要進行復制,但不會運行「:s」。 – sdaniel 2015-03-31 13:05:46

0

看一看這個功能:

function AddAttribute() 
    exe "/this.attributeA=attributeA;" 
    exe "normal yyp" 
    exe "s/attributeA/" . input('New attribute: ') . "/g" 
endfunction 

當你打電話,你會被提示,這將像你的例子添加一個新的屬性功能call AddAttribute()。您可以將此鍵與:map <F5> :call AddAttribute<CR>之類的鍵綁定,因此您只需點擊F5即可添加此行。

編輯

如果你想複製與attributeA所有行(這沒有意義對我來說),你可以做到這一點與這個映射(^MCTRL +v然後進入):

:map <F5> :call inputsave()\|let newAttribute=input('new attribute: ')\|:call inputrestore()\|:g/attributeA/exe "normal! yyp"\|exe ":s/attributeA/" . newAttribute . "/g"^M 

當你點擊F5系統提示您輸入一個新的屬性和含0123全部行將被複制並替換爲您的輸入。

相關問題