From af55d03e147396d57e1d6359de796b8854e83d66 Mon Sep 17 00:00:00 2001 From: Marco Hinz Date: Tue, 7 May 2013 14:45:16 +0200 Subject: [PATCH 1/7] Adhere to common conventions --- after/plugin/table-mode.vim | 4 ++-- autoload/tablemode.vim | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/after/plugin/table-mode.vim b/after/plugin/table-mode.vim index a5c37b4..4ff9834 100644 --- a/after/plugin/table-mode.vim +++ b/after/plugin/table-mode.vim @@ -20,10 +20,10 @@ " ============================================================================= " Finish if already loaded {{{1 -if exists('g:table_mode_loaded') +if exists('g:loaded_table_mode') finish endif -let g:table_mode_loaded = 1 +let g:loaded_table_mode = 1 "}}}1 " " Finish if Tabularize plugin is not available {{{1 diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 3a2e074..5d816bd 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -21,6 +21,11 @@ " Private Functions {{{1 +if exists('g:autoloaded_table_mode') + finish +endif +let g:autoloaded_table_mode = 1 + function! s:SetBufferOptDefault(opt, val) "{{{2 if !exists('b:' . a:opt) let b:{a:opt} = a:val From 57a49efe7e34eecd62b2b510be2e303fa7eebd86 Mon Sep 17 00:00:00 2001 From: Marco Hinz Date: Tue, 7 May 2013 14:47:56 +0200 Subject: [PATCH 2/7] Improve modeline settings --- after/plugin/table-mode.vim | 2 +- autoload/tablemode.vim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/after/plugin/table-mode.vim b/after/plugin/table-mode.vim index 4ff9834..6e7afd1 100644 --- a/after/plugin/table-mode.vim +++ b/after/plugin/table-mode.vim @@ -109,4 +109,4 @@ let &cpo = s:save_cpo " }}}1 " ModeLine {{{ -" vim:fdl=0 fdm=marker +" vim: sw=2 sts=2 fdl=0 fdm=marker diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 5d816bd..4442fbe 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -493,4 +493,4 @@ function! tablemode#DeleteRow() "{{{2 endfunction " }}}2 -" }}}1 +" vim: sw=2 sts=2 fdl=0 fdm=marker From 2bde4445757b8d1319b4772c26939f90fbdf08bb Mon Sep 17 00:00:00 2001 From: Dhruva Sagar Date: Mon, 13 May 2013 18:34:00 +0530 Subject: [PATCH 3/7] First Cut of Table Formulas --- after/plugin/table-mode.vim | 44 ++++- autoload/tablemode.vim | 350 +++++++++++++++++++++++++++++++----- 2 files changed, 343 insertions(+), 51 deletions(-) diff --git a/after/plugin/table-mode.vim b/after/plugin/table-mode.vim index a5c37b4..88770f2 100644 --- a/after/plugin/table-mode.vim +++ b/after/plugin/table-mode.vim @@ -71,6 +71,44 @@ function! s:TableMotion() "{{{1 endfunction " }}}1 +let s:tables = {} + +function! s:AddFormula(formula, range) abort "{{{1 + let line = line('.') + let colm = tablemode#ColumnNr('.') + let bufnr = bufnr('%') + let formula = 'tablemode#'.a:formula.'('.a:range.','.line.','.colm.')' + + if has_key(s:tables, bufnr) + if has_key(s:tables[bufnr], line) + let s:tables[bufnr][line][colm] = formula + else + let s:tables[bufnr][line] = { colm: formula } + endif + else + let s:tables[bufnr] = {} + let s:tables[bufnr][line] = {} + let s:tables[bufnr][line][colm] = formula + endif +endfunction +" }}}1 + +function! s:RecalculateFormulas() "{{{1 + let bufnr = bufnr('%') + if has_key(s:tables, bufnr) + let formulas = s:tables[bufnr] + for [line, cform] in items(formulas) + let line = str2nr(line) + for [colm, formula] in items(cform) + let colm = str2nr(colm) + let row = tablemode#RowNr(line) + call tablemode#SetCell(eval(formula), line, row, colm) + endfor + endfor + endif +endfunction +" }}}1 + " Define Commands & Mappings {{{1 if !g:table_mode_always_active "{{{2 exec "nnoremap " . g:table_mode_toggle_map . @@ -94,14 +132,14 @@ command! -nargs=? -range Tableize ,call tablemode#TableizeRange( " . g:table_mode_tableize_map . " :Tableize" execute "nnoremap " . g:table_mode_tableize_map . " :Tableize" execute "xnoremap " . g:table_mode_tableize_op_map . " :call tablemode#TableizeByDelimiter()" - execute "nnoremap " . g:table_mode_realign_map . " :call tablemode#TableRealign('.')" execute "nnoremap " . g:table_mode_motion_prefix . " :call TableMotion()" - execute "onoremap " . g:table_mode_cell_text_object . " :call tablemode#CellTextObject()" - execute "nnoremap " . g:table_mode_delete_row_map . " :call tablemode#DeleteRow()" execute "nnoremap " . g:table_mode_delete_column_map . " :call tablemode#DeleteColumn()" + +command! -nargs=* TableForumla call s:AddFormula() +command! TableRecalc call s:RecalculateFormulas() "}}}1 " Avoiding side effects {{{1 diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index e304411..7257f66 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -1,5 +1,4 @@ " ============================================================================= -" File: autoload/tablemode.vim " Description: Table mode for vim for creating neat tables. " Author: Dhruva Sagar " License: MIT (http://www.opensource.org/licenses/MIT) @@ -21,21 +20,73 @@ " Private Functions {{{1 -function! s:SetBufferOptDefault(opt, val) "{{{2 +" Utility Functions {{{2 + +function! s:throw(string) abort "{{{3 + let v:errmsg = 'table-mode: ' . a:string + throw v:errmsg +endfunction +" }}}3 + +function! s:sub(str,pat,rep) abort "{{{3 + return substitute(a:str,'\v\C'.a:pat,a:rep,'') +endfunction +" }}}3 + +function! s:gsub(str,pat,rep) abort "{{{3 + return substitute(a:str,'\v\C'.a:pat,a:rep,'g') +endfunction +" }}}3 + +function! s:SetBufferOptDefault(opt, val) "{{{3 if !exists('b:' . a:opt) let b:{a:opt} = a:val endif endfunction -" }}}2 +" }}}3 -" s:Strlen(text) For counting multibyte characters accurately {{{2 +function! s:Line(line) "{{{3 + if type(a:line) == type('') + return line(a:line) + else + return a:line + endif +endfunction +" }}}3 + +" s:Strlen(text) For counting multibyte characters accurately {{{3 " See :h strlen() for more details function! s:Strlen(text) return strlen(substitute(a:text, '.', 'x', 'g')) endfunction -" }}}2 +" }}}3 -function! s:GetCommentStart() "{{{2 +function! s:Strip(input_string) "{{{3 + return substitute(a:input_string, '^\s*\(.\{-}\)\s*$', '\1', '') +endfunction +" }}}3 + +function! s:Sum(list) "{{{3 + let result = 0 + for item in a:list + if type(item) == type(1) + let result = result + item + elseif type(item) == type('') + let result = result + str2nr(item) + elseif type(item) == type([]) + let result = result + s:Sum(item) + endif + endfor + return result +endfunction +" }}}3 + +function! s:Average(list) "{{{3 + return s:Sum(a:list)/len(a:list) +endfunction +" }}}3 + +function! s:GetCommentStart() "{{{3 let cstring = &commentstring if s:Strlen(cstring) > 0 return substitute(split(substitute(cstring, '%s', ' ', 'g'))[0], '.', '\\\0', 'g') @@ -43,9 +94,9 @@ function! s:GetCommentStart() "{{{2 return '' endif endfunction -" }}}2 +" }}}3 -function! s:StartExpr() "{{{2 +function! s:StartExpr() "{{{3 let cstart = s:GetCommentStart() if s:Strlen(cstart) > 0 return '^\s*\(' . cstart . '\)\?\s*' @@ -53,9 +104,9 @@ function! s:StartExpr() "{{{2 return '^\s*' endif endfunction -" }}}2 +" }}}3 -function! s:StartCommentExpr() "{{{2 +function! s:StartCommentExpr() "{{{3 let cstartexpr = s:GetCommentStart() if s:Strlen(cstartexpr) > 0 return '^\s*' . cstartexpr . '\s*' @@ -63,14 +114,25 @@ function! s:StartCommentExpr() "{{{2 return '' endif endfunction -" }}}2 +" }}}3 -function! s:IsTableModeActive() "{{{2 +function! s:IsTableModeActive() "{{{3 if g:table_mode_always_active | return 1 | endif call s:SetBufferOptDefault('table_mode_active', 0) return b:table_mode_active endfunction +" }}}3 + +function! s:RowGap() "{{{3 + if g:table_mode_border + return 2 + else + return 1 + endif +endfunction +" }}}3 + " }}}2 function! s:ToggleMapping() "{{{2 @@ -93,27 +155,16 @@ function! s:SetActive(bool) "{{{2 endfunction " }}}2 -function! s:Line(line) "{{{2 - if type(a:line) == type('') - return line(a:line) - else - return a:line - endif -endfunction -" }}}2 - function! s:GenerateBorder(line) "{{{2 - let line = s:Line(a:line) - - let border = substitute(getline(line)[stridx(getline(line), g:table_mode_separator):-1], g:table_mode_separator, g:table_mode_corner, 'g') + let border = substitute(getline(a:line)[stridx(getline(a:line), g:table_mode_separator):-1], g:table_mode_separator, g:table_mode_corner, 'g') let border = substitute(border, '[^' . g:table_mode_corner . ']', g:table_mode_fillchar, 'g') let cstartexpr = s:StartCommentExpr() - if s:Strlen(cstartexpr) > 0 && getline(line) =~# cstartexpr - let indent = matchstr(getline(line), s:StartCommentExpr()) + if s:Strlen(cstartexpr) > 0 && getline(a:line) =~# cstartexpr + let indent = matchstr(getline(a:line), s:StartCommentExpr()) return indent . border - elseif getline(line) =~# s:StartExpr() - let indent = matchstr(getline(line), s:StartExpr()) + elseif getline(a:line) =~# s:StartExpr() + let indent = matchstr(getline(a:line), s:StartExpr()) return indent . border else return border @@ -181,30 +232,44 @@ function! s:IsLastCell() "{{{2 endfunction " }}}2 -function! s:MoveToFirstRow() "{{{2 - if tablemode#IsATableRow('.') - let line = s:Line('.') +function! s:GetFirstRow(line) "{{{2 + if tablemode#IsATableRow(a:line) + let line = s:Line(a:line) + while line > 0 - if !tablemode#IsATableRow(line) - break - endif + if !tablemode#IsATableRow(line - s:RowGap()) | break | endif let line = line - s:RowGap() endwhile - call cursor(line + s:RowGap(), col('.')) + + return line + endif +endfunction +" }}}2 + +function! s:MoveToFirstRow() "{{{2 + if tablemode#IsATableRow('.') + call cursor(s:GetFirstRow('.'), col('.')) + endif +endfunction +" }}}2 + +function! s:GetLastRow(line) "{{{2 + if tablemode#IsATableRow(a:line) + let line = s:Line(a:line) + + while line <= line('$') + if !tablemode#IsATableRow(line + s:RowGap()) | break | endif + let line = line + s:RowGap() + endwhile + + return line endif endfunction " }}}2 function! s:MoveToLastRow() "{{{2 if tablemode#IsATableRow('.') - let line = s:Line('.') - while line <= line('$') - if !tablemode#IsATableRow(line) - break - endif - let line = line + s:RowGap() - endwhile - call cursor(line - s:RowGap(), col('.')) + call cursor(s:GetLastRow('.'), col('.')) endif endfunction " }}}2 @@ -218,15 +283,169 @@ function! s:MoveToStartOfCell() "{{{2 endfunction " }}}2 -function! s:RowGap() "{{{2 - if g:table_mode_border - return 2 - else - return 1 +" s:GetCells() - Function to get values of cells in a table {{{2 +" s:GetCells(row) - Get values of all cells in a row as a List. +" s:GetCells(0, col) - Get values of all cells in a column as a List. +" s:GetCells(row, col) - Get the value of table cell by given row, col. +function! s:GetCells(line, ...) abort + let line = s:Line(a:line) + + if tablemode#IsATableRow(line) + if a:0 < 1 + let [row, colm] = [line, 0] + elseif a:0 < 2 + let [row, colm] = [a:1, 0] + elseif a:0 < 3 + let [row, colm] = a:000 + endif + + if row > 0 + let line = line + (row - tablemode#RowNr(line)) * s:RowGap() + + if colm > 0 + return s:Strip(split(getline(line), g:table_mode_separator)[colm-1]) + else + return map(split(getline(line), g:table_mode_separator), 's:Strip(v:val)') + endif + elseif colm > 0 + let values = [] + let line = s:GetFirstRow(line) + while line <= line('$') + if tablemode#IsATableRow(line) + call add(values, s:Strip(split(getline(line), g:table_mode_separator)[colm-1])) + else + break + endif + let line = line + s:RowGap() + endwhile + return values + endif endif endfunction " }}}2 +function! s:GetCell(...) "{{{2 + if a:0 == 0 + let [row, colm] = [tablemode#RowNr('.'), tablemode#ColumnNr('.')] + elseif a:0 == 2 + let [row, colm] = [a:1, a:2] + endif + + return s:GetCells('.', row, col) +endfunction +" }}}2 + +function! s:SetCell(val, ...) abort "{{{2 + if a:0 == 0 + let [line, row, colm] = ['.', tablemode#RowNr('.'), tablemode#ColumnNr('.')] + elseif a:0 == 2 + let [line, row, colm] = ['.', a:1, a:2] + elseif a:0 == 3 + let [line, row, colm] = a:000 + endif + + if tablemode#IsATableRow(line) + let line = s:Line(line) + (row - tablemode#RowNr(line)) * s:RowGap() + let values = split(getline(line), g:table_mode_separator) + let values[colm-1] = a:val + let line_value = g:table_mode_separator . join(values, g:table_mode_separator) . g:table_mode_separator + call setline(line, line_value) + call tablemode#TableRealign(line) + endif +endfunction +" }}}2 + +function! s:GetRow(row, ...) abort "{{{2 + if a:0 < 1 + let line = '.' + elseif a:0 < 2 + let line = a:1 + endif + + return s:GetCells(line, a:row) +endfunction +" }}}2 + +function! s:GetColumn(col, ...) "{{{2 + if a:0 < 1 + let line = '.' + elseif a:0 < 2 + let line = a:1 + endif + return s:GetCells(line, 0, a:col) +endfunction +" }}}2 + +function! s:ParseRange(range, ...) "{{{2 + if a:0 < 1 + let default_col = tablemode#ColumnNr('.') + elseif a:0 < 2 + let default_col = a:1 + endif + + let [rowcol1, rowcol2] = split(a:range, ':') + let [rcs1, rcs2] = [map(split(rowcol1, ','), 'str2nr(v:val)'), map(split(rowcol2, ','), 'str2nr(v:val)')] + + if len(rcs1) == 2 + let [row1, col1] = rcs1 + else + let [row1, col1] = [rcs1[0], default_col] + endif + + if len(rcs2) == 2 + let [row2, col2] = rcs2 + else + let [row2, col2] = [rcs2[0], default_col] + endif + + return [row1, col1, row2, col2] +endfunction +" }}}2 + +" function! s:GetCellRange(range, ...) {{{2 +" range: A string representing range of cells. +" - Can be row1:row2 for values in the current columns in those rows. +" - Can be row1,col1:row2,col2 for range between row1,col1 till +" row2,col2. +function! s:GetCellRange(range, ...) abort + if a:0 < 1 + let [line, colm] = ['.', tablemode#ColumnNr('.')] + elseif a:0 < 2 + let [line, colm] = [a:1, tablemode#ColumnNr('.')] + elseif a:0 < 3 + let [line, colm] = [a:1, a:2] + else + call s:throw('Invalid Range') + endif + + let values = [] + + if tablemode#IsATableRow(line) + let [row1, col1, row2, col2] = s:ParseRange(a:range, colm) + + if row1 == row2 + if col1 == col2 + call add(values, s:GetCells(line, row1, col1)) + else + let values = s:GetRow(row1, line)[(col1-1):(col2-1)] + endif + else + if col1 == col2 + let values = s:GetColumn(col1, line)[(row1-1):(row2-1)] + else + let tcol = col1 + while tcol <= col2 + call add(values, s:GetColumn(tcol, line)[(row1-1):(row2-1)]) + let tcol = tcol + 1 + endwhile + endif + endif + endif + + return values +endfunction +" }}}2 + " }}}1 " Public API {{{1 @@ -484,4 +703,39 @@ function! tablemode#DeleteRow() "{{{2 endfunction " }}}2 +function! tablemode#GetCells(...) abort "{{{2 + let args = copy(a:000) + call insert(args, '.') + return call('s:GetCells', args) +endfunction +" }}}2 + +function! tablemode#SetCell(val, ...) "{{{2 + let args = copy(a:000) + call insert(args, a:val) + call call('s:SetCell', args) +endfunction +" }}}2 + +function! tablemode#GetCellRange(range, ...) abort "{{{2 + let args = copy(a:000) + call insert(args, a:range) + return call('s:GetCellRange', args) +endfunction +" }}}2 + +function! tablemode#Sum(range, ...) abort "{{{2 + let args = copy(a:000) + call insert(args, a:range) + return s:Sum(call('s:GetCellRange', args)) +endfunction +" }}}2 + +function! tablemode#Average(range, ...) abort "{{{2 + let args = copy(a:000) + call insert(args, a:range) + return s:Average(call('s:GetCellRange', args)) +endfunction +" }}}2 + " }}}1 From e9d9030cbb60a8395ae215d4609dcb7ecd4ba63a Mon Sep 17 00:00:00 2001 From: Dhruva Sagar Date: Tue, 14 May 2013 19:35:00 +0530 Subject: [PATCH 4/7] Updated Table Formulas - Added single function for both command & mapping to take formula from input. - Reusing g:table_mode_align for formatting table content, which was missed when moving from :Tableize to tabular#TabularizeStrings - Correctly parsing ranges as strings. --- after/plugin/table-mode.vim | 79 ++++++++++++++++++++----------------- autoload/tablemode.vim | 10 ++++- 2 files changed, 50 insertions(+), 39 deletions(-) diff --git a/after/plugin/table-mode.vim b/after/plugin/table-mode.vim index 88770f2..ecf16d4 100644 --- a/after/plugin/table-mode.vim +++ b/after/plugin/table-mode.vim @@ -61,6 +61,8 @@ call s:SetGlobalOptDefault('table_mode_motion_prefix', 't') call s:SetGlobalOptDefault('table_mode_cell_text_object', 'tc') call s:SetGlobalOptDefault('table_mode_delete_row_map', 'tdd') call s:SetGlobalOptDefault('table_mode_delete_column_map', 'tdc') +call s:SetGlobalOptDefault('table_mode_add_formula_map', 'tfa') +call s:SetGlobalOptDefault('table_mode_recalculate_map', 'tfr') "}}}1 function! s:TableMotion() "{{{1 @@ -73,39 +75,31 @@ endfunction let s:tables = {} -function! s:AddFormula(formula, range) abort "{{{1 - let line = line('.') - let colm = tablemode#ColumnNr('.') - let bufnr = bufnr('%') - let formula = 'tablemode#'.a:formula.'('.a:range.','.line.','.colm.')' +function! s:AddTableFormula() abort "{{{1 + let fr = input('f=') - if has_key(s:tables, bufnr) - if has_key(s:tables[bufnr], line) - let s:tables[bufnr][line][colm] = formula - else - let s:tables[bufnr][line] = { colm: formula } - endif - else - let s:tables[bufnr] = {} - let s:tables[bufnr][line] = {} - let s:tables[bufnr][line][colm] = formula + if fr !=# '' + let [formula, range] = split(fr) + + let [line, colm] = [line('.'), tablemode#ColumnNr('.')] + let key = join([bufnr('%'), line, colm], ':') + let formula = 'tablemode#'.formula.'('.string(range).','.line.','.colm.')' + + let row = tablemode#RowNr(line) + call tablemode#SetCell(eval(formula), line, row, colm) + + let s:tables[key] = formula endif endfunction " }}}1 function! s:RecalculateFormulas() "{{{1 - let bufnr = bufnr('%') - if has_key(s:tables, bufnr) - let formulas = s:tables[bufnr] - for [line, cform] in items(formulas) - let line = str2nr(line) - for [colm, formula] in items(cform) - let colm = str2nr(colm) - let row = tablemode#RowNr(line) - call tablemode#SetCell(eval(formula), line, row, colm) - endfor - endfor - endif + let formulas = filter(s:tables, 'split(v:key, ":")[0] == string(bufnr("%"))') + for [key, formula] in items(formulas) + let [bufnr, line, colm] = map(split(key, ':'), 'str2nr(v:val)') + let row = tablemode#RowNr(line) + call tablemode#SetCell(eval(formula), line, row, colm) + endfor endfunction " }}}1 @@ -129,17 +123,28 @@ endif command! -nargs=? -range Tableize ,call tablemode#TableizeRange() -execute "xnoremap " . g:table_mode_tableize_map . " :Tableize" -execute "nnoremap " . g:table_mode_tableize_map . " :Tableize" -execute "xnoremap " . g:table_mode_tableize_op_map . " :call tablemode#TableizeByDelimiter()" -execute "nnoremap " . g:table_mode_realign_map . " :call tablemode#TableRealign('.')" -execute "nnoremap " . g:table_mode_motion_prefix . " :call TableMotion()" -execute "onoremap " . g:table_mode_cell_text_object . " :call tablemode#CellTextObject()" -execute "nnoremap " . g:table_mode_delete_row_map . " :call tablemode#DeleteRow()" -execute "nnoremap " . g:table_mode_delete_column_map . " :call tablemode#DeleteColumn()" +execute "xnoremap " . g:table_mode_tableize_map . + \ " :Tableize" +execute "nnoremap " . g:table_mode_tableize_map . + \ " :Tableize" +execute "xnoremap " . g:table_mode_tableize_op_map . + \ " :call tablemode#TableizeByDelimiter()" +execute "nnoremap " . g:table_mode_realign_map . + \ " :call tablemode#TableRealign('.')" +execute "nnoremap " . g:table_mode_motion_prefix . + \ " :call TableMotion()" +execute "onoremap " . g:table_mode_cell_text_object . + \ " :call tablemode#CellTextObject()" +execute "nnoremap " . g:table_mode_delete_row_map . + \ " :call tablemode#DeleteRow()" +execute "nnoremap " . g:table_mode_delete_column_map . + \ " :call tablemode#DeleteColumn()" -command! -nargs=* TableForumla call s:AddFormula() -command! TableRecalc call s:RecalculateFormulas() +command! TableFormula call s:AddTableFormula() +command! TableRecalc call s:RecalculateFormulas() + +execute "nnoremap " . g:table_mode_add_formula_map . " :TableFormula" +execute "nnoremap " . g:table_mode_recalculate_map . " :TableRecalc" "}}}1 " Avoiding side effects {{{1 diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 7257f66..8529c1e 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -383,7 +383,13 @@ function! s:ParseRange(range, ...) "{{{2 let default_col = a:1 endif - let [rowcol1, rowcol2] = split(a:range, ':') + if type(a:range) != type('') + let range = string(a:range) + else + let range = a:range + endif + + let [rowcol1, rowcol2] = split(range, ':') let [rcs1, rcs2] = [map(split(rowcol1, ','), 'str2nr(v:val)'), map(split(rowcol2, ','), 'str2nr(v:val)')] if len(rcs1) == 2 @@ -535,7 +541,7 @@ function! tablemode#TableRealign(line) "{{{2 let tline = tline + s:RowGap() endwhile - call tabular#TabularizeStrings(lines, g:table_mode_separator) + call tabular#TabularizeStrings(lines, g:table_mode_separator, g:table_mode_align) for lnum in lnums let index = index(lnums, lnum) From edfb221b3eda65360666857dafc2448e2eb56c74 Mon Sep 17 00:00:00 2001 From: Dhruva Sagar Date: Wed, 15 May 2013 23:16:34 +0530 Subject: [PATCH 5/7] Removed dependence on Tabular for more control. - Right align numbers automatically. --- autoload/tablemode.vim | 114 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 110 insertions(+), 4 deletions(-) diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 8529c1e..7d4e2a2 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -376,7 +376,9 @@ function! s:GetColumn(col, ...) "{{{2 endfunction " }}}2 -function! s:ParseRange(range, ...) "{{{2 +" Borrowed from Tabular : {{{2 + +function! s:ParseRange(range, ...) "{{{3 if a:0 < 1 let default_col = tablemode#ColumnNr('.') elseif a:0 < 2 @@ -406,9 +408,9 @@ function! s:ParseRange(range, ...) "{{{2 return [row1, col1, row2, col2] endfunction -" }}}2 +" }}}3 -" function! s:GetCellRange(range, ...) {{{2 +" function! s:GetCellRange(range, ...) {{{3 " range: A string representing range of cells. " - Can be row1:row2 for values in the current columns in those rows. " - Can be row1,col1:row2,col2 for range between row1,col1 till @@ -450,6 +452,109 @@ function! s:GetCellRange(range, ...) abort return values endfunction +" }}}3 + +function! s:Padding(string, length, where) "{{{3 + let gap_length = a:length - s:Strlen(a:string) + if a:where =~# 'l' + return a:string . repeat(" ", gap_length) + elseif a:where =~# 'r' + return repeat(" ", gap_length) . a:string + elseif a:where =~# 'c' + let right = spaces / 2 + let left = right + (right * 2 != gap_length) + return repeat(" ", left) . a:string . repeat(" ", right) + endif +endfunction +" }}}3 + +" Split a string into fields and delimiters {{{3 +" Like split(), but include the delimiters as elements +" All odd numbered elements are delimiters +" All even numbered elements are non-delimiters (including zero) +function! s:SplitDelim(string, delim) + let rv = [] + let beg = 0 + + let len = len(a:string) + let searchoff = 0 + + while 1 + let mid = match(a:string, a:delim, beg + searchoff, 1) + if mid == -1 || mid == len + break + endif + + let matchstr = matchstr(a:string, a:delim, beg + searchoff, 1) + let length = strlen(matchstr) + + if length == 0 && beg == mid + " Zero-length match for a zero-length delimiter - advance past it + let searchoff += 1 + continue + endif + + if beg == mid + let rv += [ "" ] + else + let rv += [ a:string[beg : mid-1] ] + endif + + let rv += [ matchstr ] + + let beg = mid + length + let searchoff = 0 + endwhile + + let rv += [ strpart(a:string, beg) ] + + call filter(rv, 'len(v:val) > 0') + + return rv +endfunction +" }}}3 + +function! s:Align(lines) "{{{3 + let lines = map(a:lines, 's:SplitDelim(v:val, g:table_mode_separator)') + + for line in lines + if len(line) <= 1 | continue | endif + for i in range(len(line)) + let line[i] = s:Strip(line[i]) + endfor + endfor + + let maxes = [] + for line in lines + if len(line) <= 1 | continue | endif + for i in range(len(line)) + if i == len(maxes) + let maxes += [ s:Strlen(line[i]) ] + else + let maxes[i] = max([ maxes[i], s:Strlen(line[i]) ]) + endif + endfor + endfor + + for idx in range(len(lines)) + let line = lines[idx] + + if len(line) <= 1 | continue | endif + for i in range(len(line)) + if line[i] !~# '[^0-9]' + let line[i] = s:Padding(line[i], maxes[i], 'r') + else + let line[i] = s:Padding(line[i], maxes[i], 'l') + endif + endfor + + let lines[idx] = join(line) + endfor + + return lines +endfunction +" }}}3 + " }}}2 " }}}1 @@ -541,7 +646,8 @@ function! tablemode#TableRealign(line) "{{{2 let tline = tline + s:RowGap() endwhile - call tabular#TabularizeStrings(lines, g:table_mode_separator, g:table_mode_align) + " call tabular#TabularizeStrings(lines, g:table_mode_separator, g:table_mode_align) + let lines = s:Align(lines) for lnum in lnums let index = index(lnums, lnum) From eba248179808d1f03fa74c7bbb17af0560cf0b00 Mon Sep 17 00:00:00 2001 From: Dhruva Sagar Date: Thu, 16 May 2013 14:49:03 +0530 Subject: [PATCH 6/7] Fine tuning & formatting --- autoload/tablemode.vim | 53 ++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 7d4e2a2..513d1ab 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -1,4 +1,4 @@ -" ============================================================================= +" ============================== Header ==================================={{{ " Description: Table mode for vim for creating neat tables. " Author: Dhruva Sagar " License: MIT (http://www.opensource.org/licenses/MIT) @@ -16,7 +16,7 @@ " of any kind, either expressed or implied. In no event will " the copyright holder be liable for any damamges resulting " from the use of this software. -" ============================================================================= +" ==========================================================================}}} " Private Functions {{{1 @@ -54,15 +54,15 @@ function! s:Line(line) "{{{3 endfunction " }}}3 -" s:Strlen(text) For counting multibyte characters accurately {{{3 +" function! s:Strlen(text) - Count multibyte characters accurately {{{3 " See :h strlen() for more details function! s:Strlen(text) return strlen(substitute(a:text, '.', 'x', 'g')) endfunction " }}}3 -function! s:Strip(input_string) "{{{3 - return substitute(a:input_string, '^\s*\(.\{-}\)\s*$', '\1', '') +function! s:Strip(string) "{{{3 + return matchstr(a:string, '^\s*\zs.\{-}\ze\s*$') endfunction " }}}3 @@ -283,7 +283,7 @@ function! s:MoveToStartOfCell() "{{{2 endfunction " }}}2 -" s:GetCells() - Function to get values of cells in a table {{{2 +" function! s:GetCells() - Function to get values of cells in a table {{{2 " s:GetCells(row) - Get values of all cells in a row as a List. " s:GetCells(0, col) - Get values of all cells in a column as a List. " s:GetCells(row, col) - Get the value of table cell by given row, col. @@ -376,9 +376,7 @@ function! s:GetColumn(col, ...) "{{{2 endfunction " }}}2 -" Borrowed from Tabular : {{{2 - -function! s:ParseRange(range, ...) "{{{3 +function! s:ParseRange(range, ...) "{{{2 if a:0 < 1 let default_col = tablemode#ColumnNr('.') elseif a:0 < 2 @@ -408,9 +406,9 @@ function! s:ParseRange(range, ...) "{{{3 return [row1, col1, row2, col2] endfunction -" }}}3 +" }}}2 -" function! s:GetCellRange(range, ...) {{{3 +" function! s:GetCellRange(range, ...) {{{2 " range: A string representing range of cells. " - Can be row1:row2 for values in the current columns in those rows. " - Can be row1,col1:row2,col2 for range between row1,col1 till @@ -452,6 +450,15 @@ function! s:GetCellRange(range, ...) abort return values endfunction +" }}}2 + +" Borrowed from Tabular : {{{2 + +" function! s:StripTrailingSpaces(string) - Remove all trailing spaces {{{3 +" from a string. +function! s:StripTrailingSpaces(string) + return matchstr(a:string, '^.\{-}\ze\s*$') +endfunction " }}}3 function! s:Padding(string, length, where) "{{{3 @@ -468,7 +475,7 @@ function! s:Padding(string, length, where) "{{{3 endfunction " }}}3 -" Split a string into fields and delimiters {{{3 +" function! s:Split() - Split a string into fields and delimiters {{{3 " Like split(), but include the delimiters as elements " All odd numbered elements are delimiters " All even numbered elements are non-delimiters (including zero) @@ -508,8 +515,6 @@ function! s:SplitDelim(string, delim) let rv += [ strpart(a:string, beg) ] - call filter(rv, 'len(v:val) > 0') - return rv endfunction " }}}3 @@ -519,9 +524,15 @@ function! s:Align(lines) "{{{3 for line in lines if len(line) <= 1 | continue | endif - for i in range(len(line)) - let line[i] = s:Strip(line[i]) - endfor + + if line[0] !~ '^\s*$' + let line[0] = s:StripTrailingSpaces(line[0]) + endif + if len(line) >= 2 + for i in range(1, len(line)-1) + let line[i] = s:Strip(line[i]) + endfor + endif endfor let maxes = [] @@ -542,13 +553,15 @@ function! s:Align(lines) "{{{3 if len(line) <= 1 | continue | endif for i in range(len(line)) if line[i] !~# '[^0-9]' - let line[i] = s:Padding(line[i], maxes[i], 'r') + let field = s:Padding(line[i], maxes[i], 'r') else - let line[i] = s:Padding(line[i], maxes[i], 'l') + let field = s:Padding(line[i], maxes[i], 'l') endif + + let line[i] = field . (i == 0 || i == len(line) ? '' : ' ') endfor - let lines[idx] = join(line) + let lines[idx] = s:StripTrailingSpaces(join(line, '')) endfor return lines From dd38fcfeeb4de488b481c771b83d70f0f96579f1 Mon Sep 17 00:00:00 2001 From: Dhruva Sagar Date: Fri, 17 May 2013 07:45:49 +0530 Subject: [PATCH 7/7] Releasing v3.0 - Added feature to define & add formula expressions to table and calculate them. - Persist the fomulas as comments as line right after table. --- autoload/tablemode.vim | 224 ++++++++++++++++-------- {after/plugin => plugin}/table-mode.vim | 59 ++----- 2 files changed, 166 insertions(+), 117 deletions(-) rename {after/plugin => plugin}/table-mode.vim (77%) diff --git a/autoload/tablemode.vim b/autoload/tablemode.vim index 92c8f97..607d09f 100644 --- a/autoload/tablemode.vim +++ b/autoload/tablemode.vim @@ -1,9 +1,10 @@ " ============================== Header ==================================={{{ +" File: autoload/tablemode.vim " Description: Table mode for vim for creating neat tables. " Author: Dhruva Sagar " License: MIT (http://www.opensource.org/licenses/MIT) " Website: http://github.com/dhruvasagar/vim-table-mode -" Version: 2.4.0 +" Version: 3.0 " Note: This plugin was heavily inspired by the 'CucumberTables.vim' " (https://gist.github.com/tpope/287147) plugin by Tim Pope and " uses a small amount of code from it. @@ -75,7 +76,7 @@ endfunction function! s:Sum(list) "{{{3 let result = 0 for item in a:list - if type(item) == type(1) + if type(item) == type(1) || type(item) == type(1.0) let result = result + item elseif type(item) == type('') let result = result + str2nr(item) @@ -95,7 +96,7 @@ endfunction function! s:GetCommentStart() "{{{3 let cstring = &commentstring if s:Strlen(cstring) > 0 - return substitute(split(substitute(cstring, '%s', ' ', 'g'))[0], '.', '\\\0', 'g') + return substitute(split(cstring, '%s')[0], '.', '\\\0', 'g') else return '' endif @@ -131,11 +132,7 @@ endfunction " }}}3 function! s:RowGap() "{{{3 - if g:table_mode_border - return 2 - else - return 1 - endif + return g:table_mode_border ? 2 : 1 endfunction " }}}3 @@ -242,8 +239,7 @@ function! s:GetFirstRow(line) "{{{2 if tablemode#IsATableRow(a:line) let line = s:Line(a:line) - while line > 0 - if !tablemode#IsATableRow(line - s:RowGap()) | break | endif + while tablemode#IsATableRow(line - s:RowGap()) let line = line - s:RowGap() endwhile @@ -263,8 +259,7 @@ function! s:GetLastRow(line) "{{{2 if tablemode#IsATableRow(a:line) let line = s:Line(a:line) - while line <= line('$') - if !tablemode#IsATableRow(line + s:RowGap()) | break | endif + while tablemode#IsATableRow(line+ s:RowGap()) let line = line + s:RowGap() endwhile @@ -305,26 +300,26 @@ function! s:GetCells(line, ...) abort let [row, colm] = a:000 endif - if row > 0 - let line = line + (row - tablemode#RowNr(line)) * s:RowGap() - - if colm > 0 - return s:Strip(split(getline(line), g:table_mode_separator)[colm-1]) - else - return map(split(getline(line), g:table_mode_separator), 's:Strip(v:val)') - endif - elseif colm > 0 + if row == 0 let values = [] let line = s:GetFirstRow(line) - while line <= line('$') - if tablemode#IsATableRow(line) - call add(values, s:Strip(split(getline(line), g:table_mode_separator)[colm-1])) - else - break - endif + while tablemode#IsATableRow(line) + call add(values, s:Strip(split(getline(line), g:table_mode_separator)[colm>0?colm-1:colm])) let line = line + s:RowGap() endwhile return values + else + if row > 0 + let line = line + (row - tablemode#RowNr(line)) * s:RowGap() + else + let line = line + row * s:RowGap() + endif + + if colm == 0 + return map(split(getline(line), g:table_mode_separator), 's:Strip(v:val)') + else + return s:Strip(split(getline(line), g:table_mode_separator)[colm>0?colm-1:colm]) + endif endif endif endfunction @@ -362,26 +357,31 @@ endfunction " }}}2 function! s:GetRow(row, ...) abort "{{{2 - if a:0 < 1 - let line = '.' - elseif a:0 < 2 - let line = a:1 - endif - + let line = a:0 < 1 ? '.' : a:1 return s:GetCells(line, a:row) endfunction " }}}2 -function! s:GetColumn(col, ...) "{{{2 - if a:0 < 1 - let line = '.' - elseif a:0 < 2 - let line = a:1 - endif +function! s:GetRowColumn(col, ...) abort "{{{2 + let line = a:0 < 1 ? '.' : a:1 + let row = tablemode#RowNr('.') + return s:GetCells(line, row, a:col) +endfunction +" }}}2 + +function! s:GetColumn(col, ...) abort "{{{2 + let line = a:0 < 1 ? '.' : a:1 return s:GetCells(line, 0, a:col) endfunction " }}}2 +function! s:GetColumnRow(row, ...) abort "{{{2 + let line = a:0 < 1 ? '.' : a:1 + let col = tablemode#ColumnNr('.') + return s:GetCells(line, a:row, col) +endfunction +" }}}2 + function! s:ParseRange(range, ...) "{{{2 if a:0 < 1 let default_col = tablemode#ColumnNr('.') @@ -448,7 +448,7 @@ function! s:GetCellRange(range, ...) abort let tcol = col1 while tcol <= col2 call add(values, s:GetColumn(tcol, line)[(row1-1):(row2-1)]) - let tcol = tcol + 1 + let tcol += 1 endwhile endif endif @@ -580,6 +580,16 @@ endfunction " Public API {{{1 +function! tablemode#GetLastRow(line) "{{{2 + return s:GetLastRow(a:line) +endfunction +" }}}2 + +function! tablemode#GetFirstRow(line) "{{{2 + return s:GetFirstRow(a:line) +endfunction +" }}}2 + function! tablemode#TableizeInsertMode() "{{{2 if s:IsTableModeActive() && getline('.') =~# (s:StartExpr() . g:table_mode_separator) let column = s:Strlen(substitute(getline('.')[0:col('.')], '[^' . g:table_mode_separator . ']', '', 'g')) @@ -613,7 +623,7 @@ endfunction function! tablemode#TableizeRange(...) range "{{{2 let shift = 1 - if g:table_mode_border | let shift = shift + 1 | endif + if g:table_mode_border | let shift += 1 | endif call s:Tableizeline(a:firstline, a:1) undojoin " The first one causes 2 extra lines for top & bottom border while the @@ -644,24 +654,16 @@ function! tablemode#TableRealign(line) "{{{2 let [lnums, lines] = [[], []] let tline = line - while tline > 0 - if tablemode#IsATableRow(tline) - call insert(lnums, tline) - call insert(lines, getline(tline)) - else - break - endif + while tablemode#IsATableRow(tline) + call insert(lnums, tline) + call insert(lines, getline(tline)) let tline = tline - s:RowGap() endwhile let tline = line + s:RowGap() - while tline <= line('$') - if tablemode#IsATableRow(tline) - call add(lnums, tline) - call add(lines, getline(tline)) - else - break - endif + while tablemode#IsATableRow(tline) + call add(lnums, tline) + call add(lines, getline(tline)) let tline = tline + s:RowGap() endwhile @@ -685,22 +687,14 @@ function! tablemode#RowCount(line) "{{{2 let line = s:Line(a:line) let [tline, totalRowCount] = [line, 0] - while tline > 0 - if tablemode#IsATableRow(tline) - let totalRowCount = totalRowCount + 1 - else - break - endif + while tablemode#IsATableRow(tline) + let totalRowCount += 1 let tline = tline - s:RowGap() endwhile let tline = line + s:RowGap() - while tline <= line('$') - if tablemode#IsATableRow(tline) - let totalRowCount = totalRowCount + 1 - else - break - endif + while tablemode#IsATableRow(tline) + let totalRowCount += 1 let tline = tline + s:RowGap() endwhile @@ -712,12 +706,8 @@ function! tablemode#RowNr(line) "{{{2 let line = s:Line(a:line) let rowNr = 0 - while line > 0 - if tablemode#IsATableRow(line) - let rowNr = rowNr + 1 - else - break - endif + while tablemode#IsATableRow(line) + let rowNr += 1 let line = line - s:RowGap() endwhile @@ -868,6 +858,94 @@ function! tablemode#Average(range, ...) abort "{{{2 endfunction " }}}2 +function! tablemode#AddFormula() "{{{2 + let fr = input('f=') + let row = tablemode#RowNr('.') + let colm = tablemode#ColumnNr('.') + + if fr !=# '' + let fr = '$' . row . ',' . colm . '=' . fr + let fline = tablemode#GetLastRow('.') + s:RowGap() + let cursor_pos = [line('.'), col('.')] + if getline(fline) =~# 'tmf: ' + call setline(fline, getline(fline) . ';' . fr) + else + let cstring = &commentstring + if len(cstring) > 0 + let cstring = split(cstring, '%s')[0] + endif + let fr = cstring . 'tmf: ' . fr + call append(fline-1, fr) + call cursor(cursor_pos) + endif + call tablemode#EvaluateFormulaLine() + endif +endfunction +" }}}2 + +function! tablemode#EvaluateExpr(expr, line) abort "{{{2 + let line = s:Line(a:line) + let [target, expr] = split(a:expr, '=') + let cell = substitute(target, '\$', '', '') + if cell =~# ',' + let [row, colm] = split(cell, ',') + else + let [row, colm] = [0, cell] + endif + + if expr =~# 'Sum(.*)' + let expr = substitute(expr, 'Sum(\(.*\))', 'tablemode#Sum("\1",'.line.','.colm.')', 'g') + endif + + if expr =~# 'Average(.*)' + let expr = substitute(expr, 'Average(\(.*\))', 'tablemode#Average("\1",'.line.','.colm.')', 'g') + endif + + if expr =~# '[\$,]' + let expr = substitute(expr, '\$\(\d\+\),\(\d*\)', + \ '\=str2float(s:GetCells(line, submatch(1), submatch(2)))', 'g') + endif + + if cell =~# ',' + call s:SetCell(eval(expr), line, row, colm) + else + let [row, line] = [1, s:GetFirstRow(line)] + while tablemode#IsATableRow(line) + if expr =~# '\$' + let texpr = substitute(expr, '\$\(\d\+\)', + \ '\=str2float(s:GetCells(line, row, submatch(1)))', 'g') + else + let texpr = expr + endif + + call s:SetCell(eval(texpr), line, row, colm) + let row += 1 + let line += s:RowGap() + endwhile + endif +endfunction +" }}}2 + +function! tablemode#EvaluateFormulaLine() "{{{2 + let exprs = [] + if tablemode#IsATableRow('.') " We're inside the table + let line = s:GetLastRow('.') + if getline(line + s:RowGap()) =~# 'tmf: ' + let exprs = split(matchstr(getline(line + s:RowGap()), 'tmf: \zs.*'), ';') + endif + elseif getline('.') =~# 'tmf: ' " We're on the formula line + let line = line('.') - s:RowGap() + if tablemode#IsATableRow(line) + let exprs = split(matchstr(getline('.'), 'tmf: \zs.*'), ';') + endif + endif + + for expr in exprs + call tablemode#EvaluateExpr(expr, line) + endfor +endfunction +" }}}2 + " }}}1 " vim: sw=2 sts=2 fdl=0 fdm=marker diff --git a/after/plugin/table-mode.vim b/plugin/table-mode.vim similarity index 77% rename from after/plugin/table-mode.vim rename to plugin/table-mode.vim index e65379b..d44a71e 100644 --- a/after/plugin/table-mode.vim +++ b/plugin/table-mode.vim @@ -25,13 +25,13 @@ if exists('g:loaded_table_mode') endif let g:loaded_table_mode = 1 "}}}1 -" -" Finish if Tabularize plugin is not available {{{1 -if !exists(':Tabularize') - echoerr 'Table Mode depends on Tabularize, ensure that is installed first.' - finish -endif -" }}}1 + +" " Finish if Tabularize plugin is not available {{{1 +" if !exists(':Tabularize') +" echoerr 'Table Mode depends on Tabularize, ensure that is installed first.' +" finish +" endif +" " }}}1 " Avoiding side effects {{{1 let s:save_cpo = &cpo @@ -62,7 +62,7 @@ call s:SetGlobalOptDefault('table_mode_cell_text_object', 'tc') call s:SetGlobalOptDefault('table_mode_delete_row_map', 'tdd') call s:SetGlobalOptDefault('table_mode_delete_column_map', 'tdc') call s:SetGlobalOptDefault('table_mode_add_formula_map', 'tfa') -call s:SetGlobalOptDefault('table_mode_recalculate_map', 'tfr') +call s:SetGlobalOptDefault('table_mode_expr_calc_map', 'tfe') "}}}1 function! s:TableMotion() "{{{1 @@ -73,36 +73,6 @@ function! s:TableMotion() "{{{1 endfunction " }}}1 -let s:tables = {} - -function! s:AddTableFormula() abort "{{{1 - let fr = input('f=') - - if fr !=# '' - let [formula, range] = split(fr) - - let [line, colm] = [line('.'), tablemode#ColumnNr('.')] - let key = join([bufnr('%'), line, colm], ':') - let formula = 'tablemode#'.formula.'('.string(range).','.line.','.colm.')' - - let row = tablemode#RowNr(line) - call tablemode#SetCell(eval(formula), line, row, colm) - - let s:tables[key] = formula - endif -endfunction -" }}}1 - -function! s:RecalculateFormulas() "{{{1 - let formulas = filter(s:tables, 'split(v:key, ":")[0] == string(bufnr("%"))') - for [key, formula] in items(formulas) - let [bufnr, line, colm] = map(split(key, ':'), 'str2nr(v:val)') - let row = tablemode#RowNr(line) - call tablemode#SetCell(eval(formula), line, row, colm) - endfor -endfunction -" }}}1 - " Define Commands & Mappings {{{1 if !g:table_mode_always_active "{{{2 exec "nnoremap " . g:table_mode_toggle_map . @@ -123,6 +93,9 @@ endif command! -nargs=? -range Tableize ,call tablemode#TableizeRange() +command! TableAddFormula call tablemode#AddFormula() +command! TableEvalFormulaLine call tablemode#EvaluateFormulaLine() + execute "xnoremap " . g:table_mode_tableize_map . \ " :Tableize" execute "nnoremap " . g:table_mode_tableize_map . @@ -139,12 +112,10 @@ execute "nnoremap " . g:table_mode_delete_row_map . \ " :call tablemode#DeleteRow()" execute "nnoremap " . g:table_mode_delete_column_map . \ " :call tablemode#DeleteColumn()" - -command! TableFormula call s:AddTableFormula() -command! TableRecalc call s:RecalculateFormulas() - -execute "nnoremap " . g:table_mode_add_formula_map . " :TableFormula" -execute "nnoremap " . g:table_mode_recalculate_map . " :TableRecalc" +execute "nnoremap " . g:table_mode_add_formula_map . + \ " :TableAddFormula" +execute "nnoremap " . g:table_mode_expr_calc_map . + \ " :TableEvalFormulaLine" "}}}1 " Avoiding side effects {{{1