3

I like to format my arrays like this:

myArray = [ "lorem"
          , "ipsum"
          , "dolor"
          , "sit"
          , "amet"
          ];

If I open a new line below the "amet" line, I would like vim to automatically insert a comma so that I end up with:

myArray = [ "lorem"
          , "ipsum"
          , "dolor"
          , "sit"
          , "amet"
          , 
          ];

Similar to how vim automatically insert comments with set formatoptions=ro

  • 1) Your question is not a question. It is not clear what you are asking. 2) The syntax for how you format arrays is strange, to say the least. Commas should follow the word without whitespace, i.e. "lorem", .... Of course, you're free to do as you like, but you should consider to follow more standard conventions, as that is better wrt. collaboration. – Karl Yngve Lervåg Dec 26 '18 at 20:11
  • You could map o and O for that filetype to consider context and do the right thing (e.g. via an <expr> mapping), but I imagine it will be troublesome – D. Ben Knoble Dec 26 '18 at 21:58
1

This works by checking if there is an opening and closing bracket inside the result of a yip. O does nothing if used at the top of the document.

function! CommaInList (eol)
  " enforce eol?
  let curLine = getline ('.')
  let curPos  = getpos  ('.')
  if a:eol && (curPos[2] < len(curLine))
    norm! a^M
    return
  endif

  " current line must contain , or [
  if (match(curLine, '^ *,[^,]*$') != 0) && (match(curLine, '\[[^\],]*$') == -1)
    norm! o
    return
  endif

  " Cursor must be inside an array
  norm! m""ayip'"
  if match(@a, '[^\[\]]*\[[^,\n]*\n[^\]]*\]') != 0
    norm! o
    return
  endif

  " Comma!
  let line = repeat(' ', match (curLine, '[,\[][^,\[]*$')).", "
  exec ('norm! "="'.line.'\n"^Mp$')
endfunction

nmap <silent>o :call CommaInList(0)<cr>a
nmap <silent>O k:call CommaInList(0)<cr>a
imap <silent><cr> <esc>:call CommaInList(1)<cr>a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.