Skip to content

Instantly share code, notes, and snippets.

@tpope
Created January 26, 2010 19:51
Show Gist options
  • Select an option

  • Save tpope/287147 to your computer and use it in GitHub Desktop.

Select an option

Save tpope/287147 to your computer and use it in GitHub Desktop.
inoremap <silent> <Bar> <Bar><Esc>:call <SID>align()<CR>a
function! s:align()
let p = '^\s*|\s.*\s|\s*$'
if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
Tabularize/|/l1
normal! 0
call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
endif
endfunction
@Harsha9554
Copy link
Copy Markdown

@namjul hey thank you so much, worked like a charm.

@rockyzhang24
Copy link
Copy Markdown

@namjul it works perfectly. Thanks a lot.

@antoniopaolini
Copy link
Copy Markdown

In my case it doesn't works perfectly. The alignmet is correct but every pipe add a space at the start of the row.
For example, the first row is:

| pippo | pluto | paperino |

then I start the second row and hapens this:

␣ | pippo | pluto | paperino |
␣ |*

and when I start second column in the second row another space will be added:

␣ ␣ | pippo | pluto | paperino |
␣ ␣ | one   |* 

(I used " ␣ " to represent a single space and "*" to represent cursor position at the time)

Anyone could figure why?

@antoniopaolini
Copy link
Copy Markdown

I I thought that the space was inserted by Tabularize, then I solved with this little mod of the gist:

inoremap <silent> <Bar>   <Bar><Esc>:call <SID>align()<CR>a

function! s:align()
  let p = '^\s*|\s.*\s|\s*$'
  if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
    let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
    let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
	let ln = line('.')
    Tabularize/|/l1
	"normal! 0
	" Changed this row.
	"but I have also to check if the table row was the last, in order to not mess the table under the row edited:
	if getline('.') =~# '^\s*|' && getline(line('.')+1) =~# p
		execute "normal }k\<C-v>".ln."Gjhx".ln."G" 
	endif
	execute "normal {j\<C-v>".ln."Ghx".ln."G" 

    call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
  endif

endfunction

If someone would comment about mistakes or suggest anything I'll be happy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment