Skip to content

Instantly share code, notes, and snippets.

@aktau
Last active July 20, 2017 20:50
Show Gist options
  • Save aktau/b1ed0ef699810aaec86cc4c3a437a2b5 to your computer and use it in GitHub Desktop.
Save aktau/b1ed0ef699810aaec86cc4c3a437a2b5 to your computer and use it in GitHub Desktop.
" Append lines to a buffer. Use the Neovim API instead of the traditional
"
" call append(line('$'), a:data)
"
" Reason: nvim_buf_set_lines allows adding lines to a buffer which is not
" the active one. This means we don't have to fiddle with the users' active
" buffers.
function s:appendlines(buf, list)
if !empty(a:list)
call nvim_buf_set_lines(a:buf, -1, -1, v:false, a:list)
endif
endfunction
function cb.on_stdout(job_id, data, event) dict
" If we have more than a single line, we can be sure there's some newline in
" there, so flush stdoutbuf.
if len(a:data) > 1
" Technically, this could make us add an empty line to the buffer: if
" self.stdoutbuf and a:data[0] are empty. I think this is intentional...
"
" But what happens if self.stdoutbuf was already '' (from a newline), and
" we get a newline now in a:data? Wouldn't we be collapsing that newline?
call s:appendlines(self.buf, [self.stdoutbuf . remove(a:data, 0)])
let self.stdoutbuf = ''
endif
" Print all lines save for the last, which may be incomplete.
call s:appendlines(self.buf, a:data[:-2])
if !empty(a:data[-1])
let self.stdoutbuf = a:data[-1]
endif
" I guess we just ignore empty last list items... (TODO)
endfunction
function cb.on_exit(job_id, data, event) dict
if !empty(self.stdoutbuf)
call s:appendlines(self.buf, [self.stdoutbuf])
endif
unlet self.stdoutbuf
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment