[英]Vim: Convert map to command
我想將此map
轉換為command
。 我嘗試過“明顯的”,將map
行的命令部分復制到command
行:
command SortWords d:execute 'normal i' . join(sort(split(getreg('"'))), ' ')<CR>
但是,當使用選定的文本時,它只會失敗“ E481: No range allowed
”。 我的Google-fu不夠強大,而且手冊是...計算機可解析的,讓我們說。
command! -nargs=0 -range SortWords exe 'norm! gvd'|call setreg('"', join(sort(split(@")), ' '), visualmode()[0])|norm! P
這個命令很臟,因為它破壞了未命名的寄存器。
為避免這種情況,您必須保存寄存器並在完成后將其恢復。 最好的方法是使用一個函數。
command! -nargs=0 -range SortWords call VisualSortWords()
function! VisualSortWords()
let rv = @"
let rt = getregtype('"')
try
norm! gvy
call setreg('"', join(sort(split(@")), ' '), visualmode()[0])
norm! `>pgvd
finally
call setreg('"', rv, rt)
endtry
endfunction
這是一種不同的方法,只使用2個命令( :call和:delete )。 該過程解釋如下。
command! -range -nargs=0 Sort
\ call append(<line2>,join(sort(split(join(getline(<line1>,<line2>)))), ' ')) |
\ <line1>,<line2>d _
請注意,為了便於閱讀,我使用了3行和相應的連續符,但是你只能使用一行。
該命令定義為“排序”,具有兩個特殊特征:
-range
使它能夠接收范圍。 此外,它將默認范圍設置為當前行(請參閱help :command-range )。 -nargs=0
可以省略,因為它只能保證您或您未來的命令用戶不會傳遞任何參數。 在處理命令之前,標記為<line1>
的文本將替換為范圍start的行號。 類似地, <line2>
將被范圍結束的行號替換。 檢查<line1>和后續行的幫助,以了解有關命令中替換文本的更多信息。
該命令將在兩次執行中執行其任務。 第一個是可以從里到外讀取的一系列功能。 讓我們考慮使用視覺選擇范圍( '<
, '>
)調用命令,該范圍轉換為(1,3)。 這些功能將執行為:
append(3, join(sort(split(join(getline(1,3)))), ' '))
從不同的角度來看:
#1 getline(1,3) " the result is a list with text from lines 1 to 3
#2 join(#1) " joins that list into a string
#3 split(#2) " splits the string on whitespace, resulting in a list
#4 sort(#3) " sorts that list
#5 join(#4, ' ') " joins the elements into a string separated by single space
#6 append(3, #5) " insert that string after line 3
如果你開始使用這個文本:
f e
d c
b a
現在你應該有這個:
f e
d c
b a
a b c d e f
這只是刪除這些行的問題。 這正是命令的下一部分:
1,3d _
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.