Vim - Macro to expand verilog bus

穿精又带淫゛_ 提交于 2021-02-07 20:22:10

问题


I can't seem to be able to create a vim macro that does the following:

Source:

this_is_a_bus[10:0]
another_bus[2:0]

Required Dest:

this_is_a_bus[10]
this_is_a_bus[9]
this_is_a_bus[8]
this_is_a_bus[7]
this_is_a_bus[6]
this_is_a_bus[5]
this_is_a_bus[4]
this_is_a_bus[3]
this_is_a_bus[2]
this_is_a_bus[1]
this_is_a_bus[0]
another_bus[2]
another_bus[1]
another_bus[0]

What I tried to do: I can search for \d\+:\d\+ and put the cursor on the first number, then copy that with yw to the memory. However I can't seem to be able to tell vim to run the paste command on the basis of the number in the register.

Am I approaching this the wrong way? What's the suggested way to create something like this?


回答1:


Here is a function, which could do the expansion automatically by single keystroke. (<F6> in this case)

fun! ExpandIt()
    let pat = '^\([^][]\+\)\[\(\d\+\):\(\d\+\)\]\s*'
    let line = getline('.')
    let lnr = line('.')
    if line !~ pat
        return
    endif
    let exestr = substitute(line,pat,'range(\2,\3,-1)','g')
    let text = substitute(line,pat,'\1','g')
    exec 'let range='.exestr
    let result = []
    for i in range
        call add(result, text.'['.i.']')
    endfor
    call append(lnr, result)
    exec lnr'.d'    
endf
nnoremap <F6> :call ExpandIt()<cr>
  • source this file, or put it in your vimrc.
  • the last line creates a mapping, it allows you to press <F6> on that line to do expansion
  • if the line is not in xxxx[number:number] format, nothing would happen
  • I didn't check error case, like xxx[1:10] or xxx[000:000]

I did a little test, and it looks like:

enter image description here




回答2:


I would use a macro to accomplish this task. Start with the following line:

this_is_a_bus[10]

Then record the macro:

qqyyp<c-x>q

Then playback the macro via @q. Even better we can give it a count, 9@q.

Explanation of macro

  • q{reg} starts recording the macro and saves the macro into register, {reg}. e.g. qq
  • yy copies the whole line
  • p paste the newly copied line below the current line (the cursor is on the new line)
  • <c-x> will decrement the first number it finds from the current cursor position
  • q pressing q while recording a macro will end recording
  • @{reg} will playback a macro inside {reg}. e.g. @q to playback register q
  • [count]@{reg}: @ can take a count do playback the macro [count] times. e.g. 9@q
  • @@ will replay the last used @{reg} command. Optionally @@ can take a count as well

For more help see:

:h q
:h @
:h @@
:h ctrl-x


来源:https://stackoverflow.com/questions/27823265/vim-macro-to-expand-verilog-bus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!