Monday, July 16, 2012

Scripting the enter key

Hi all, I'm trying to write a function to make smarter line breaking when I split a pair of parentheses or braces.  For example, with the text:
func ()

(The cursor is on the closing parentheses), when I hi enter, I'd like to end with the following state:
func (
  _
)
In this case, the closing parentheses gets pushed down one line, and I end up on the following line with correct indentation following my settings.

I've written a script to accomplish this, but the indentation is always borked (It always starts at column 0).  Could anyone help me with pointers?


function BraceSpace()
  if col(".") < 2
    iunmap <CR>
    if col(".") == col("$")
      :execute "normal a\<CR>"
    else
      :execute "normal i\<CR>"
    endif
    imap <CR> <C-\><C-O>:call BraceSpace()<CR>
    return
  endif
  let l:cursorchar = getline(".")[col(".") - 1]
  if cursorchar != '}'
    iunmap <CR>
    if col(".") == col("$")
      :execute "normal a\<CR>"
    else
      :execute "normal i\<CR>"
    endif
    imap <CR> <C-\><C-O>:call BraceSpace()<CR>
    return
  endif
  let l:lastchar = getline(".")[col(".") - 2]
  if lastchar != '{'
    iunmap <CR>
    if col(".") == col("$")
      :execute "normal a\<CR>"
    else
      :execute "normal i\<CR>"
    endif
    imap <CR> <C-\><C-O>:call BraceSpace()<CR>
    return
  endif

  iunmap <CR>
  :execute "normal i\<CR>\<C-O>k\<C-O>o"
  imap <CR> <C-\><C-O>:call BraceSpace()<CR>
endfunction

imap <CR> <C-\><C-O>:call BraceSpace()<CR>

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment