|
| 1 | +" =========================================================================== |
| 2 | +" Description: Vim plugin that executes shell command with a buffer contents |
| 3 | +" or selection and redirects output to a new buffer |
| 4 | +" Author: Alexander Skachko <alexander.skachko@gmail.com> |
| 5 | +" Homepage: https://github.com/lucerion/vim-executor |
| 6 | +" Version: 0.1 |
| 7 | +" Licence: MIT |
| 8 | +" =========================================================================== |
| 9 | + |
| 10 | +func! executor#exec(start_line, end_line, count, ...) |
| 11 | + if !exists('g:loaded_buffr') |
| 12 | + call s:show_error('Please, install vim-buffr plugin first') | return |
| 13 | + endif |
| 14 | + |
| 15 | + call s:execute(a:start_line, a:end_line, a:count, a:000) |
| 16 | +endfunc |
| 17 | + |
| 18 | +func! s:execute(start_line, end_line, count, command) |
| 19 | + let l:selection = s:selection(a:start_line, a:end_line) |
| 20 | + let l:command = s:command(a:command) |
| 21 | + let l:result = s:result(l:command, l:selection, a:count) |
| 22 | + let l:buffer_name = s:buffer_name(l:command) |
| 23 | + |
| 24 | + call s:open_result(l:result, l:buffer_name) |
| 25 | +endfunc |
| 26 | + |
| 27 | +func! s:selection(start_line, end_line) |
| 28 | + let l:lines = getline(a:start_line, a:end_line) |
| 29 | + return join(l:lines, "\n") . "\n" |
| 30 | +endfunc |
| 31 | + |
| 32 | +func! s:command(command) |
| 33 | + let l:command = join(a:command) |
| 34 | + if len(substitute(l:command, ' ', '', 'g')) |
| 35 | + return l:command |
| 36 | + end |
| 37 | + |
| 38 | + return g:executor_default_command |
| 39 | +endfunc |
| 40 | + |
| 41 | +func! s:result(command, selection, count) |
| 42 | + if a:count |
| 43 | + return system(a:command, a:selection) |
| 44 | + endif |
| 45 | + |
| 46 | + return system(a:command) |
| 47 | +endfunc |
| 48 | + |
| 49 | +func! s:open_result(result, buffer_name) |
| 50 | + call buffr#create_buffer({ |
| 51 | + \ 'position': g:executor_position, |
| 52 | + \ 'name': a:buffer_name |
| 53 | + \ }) |
| 54 | + call s:set_buffer_defaults() |
| 55 | + call append(0, split(a:result, "\n")) |
| 56 | +endfunc |
| 57 | + |
| 58 | +func! s:buffer_name(command) |
| 59 | + let l:buffer_name = g:executor_buffer_name |
| 60 | + let l:buffer_name = substitute(l:buffer_name, '{command}', a:command, 'g') |
| 61 | + let l:buffer_name = substitute(l:buffer_name, '{filename}', expand('%:t'), 'g') |
| 62 | + |
| 63 | + return l:buffer_name |
| 64 | +endfunc |
| 65 | + |
| 66 | +func! s:set_buffer_defaults() |
| 67 | + setlocal buftype=nofile |
| 68 | + setlocal bufhidden=wipe |
| 69 | + setlocal nobuflisted |
| 70 | + setlocal noswapfile |
| 71 | +endfunc |
| 72 | + |
| 73 | +func! s:show_error(message) |
| 74 | + echohl ErrorMsg | echomsg a:message | echohl None |
| 75 | +endfunc |
0 commit comments