Vim: changing the formatting of variables in a script

I use vim to edit the shell script (did not use the correct coding standard). I need to change all my variables from camel notation startTimeto cap-and-underscore-notation START_TIME.

I do not want to change the way that method names are represented.

I thought one way to do this is to write a function and map it to a key. A function might do something like creating this on the command line:

s/<word under cursor>/<leave cursor here to type what to replace with>

I think this feature may be applicable to other situations that would be convenient. Two questions:

Question 1: . How can I create this function.

  • I created functions in vim before the biggest thing I don't know about is how to capture movement. Those. if you click dwin vim, this will delete the rest of the word. How to do it?
  • Also you can leave the incomplete command in the vim command line?

Question 2: Got the best solution for me? How do you approach this task?

+3
source share
2 answers
  • Use plugin

    Check out the COERCION section at the bottom of the page:

    http://www.vim.org/scripts/script.php?script_id=1545

  • Get the command: s at the command prompt

    :nnoremap \c :%s/<C-r><C-w>/

    <C-r><C-w> gets the word under the cursor on the command line

  • Change the word under the cursor to: s

    :nnoremap \c lb:s/\%#<C-r><C-w>/\=toupper(substitute(submatch(0), '\<\@!\u', '_&', 'g'))/<Cr>

    lb , . , , , . , b .

    \%#

    \= - "\ =", . :h sub-replace-\=

    submatch(0) : s,

    \<

    \@! (   . FooBar _FOO_BAR)

    & ,

  • ,

    :nnoremap \a :%s/<C-r><C-w>/\=toupper(substitute(submatch(0), '\<\@!\u', '_&', 'g'))/g<Cr>

    . 3..

  • /\u<Cr>

    i_ .

    nn ( , ).

    . , .

    nn., , FooBarBaz Foo_Bar_Baz

    gUiw

  • http://vim.wikia.com/wiki/Converting_variables_to_camelCase

+2

, " ". , - :

fu! ChangeWord()

  let l:the_word = expand('<cword>')

  " Modify according to your rules
  let l:new_var_name = toupper(l:the_word)

  normal b
  let l:col_b = col(".")

  normal e
  let l:col_e = col(".")

  let l:line = getline(".")

  let l:line = substitute(
  \ l:line, 
  \ '^\(' . repeat('.',  l:col_b-1) . '\)' . repeat('.', l:col_e - l:col_b+1), 
  \ '\1' . l:new_var_name, 
  \ '')

  call setline(".", l:line)

endfu

Vim , ,

:map ,x :call ChangeWord(

normal mode, ,x.

, :

fu! ChangeWordUnderCursor()

  let l:the_word = expand('<cword>')

  "" Modify according to your rules
  let l:new_var_name = '!' . toupper(l:the_word) . '!'

  normal b
  let l:col_b = col(".")

  normal e
  let l:col_e = col(".")

  let l:line = getline(".")

  exe 's/\%' . l:col_b . 'c.*\%' . (l:col_e+1) .'c/' . l:new_var_name . '/'

endfu
0

Source: https://habr.com/ru/post/1742328/


All Articles