fillstruct.vim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function! go#fillstruct#FillStruct() abort
  2. let l:cmd = ['fillstruct',
  3. \ '-file', bufname(''),
  4. \ '-offset', go#util#OffsetCursor(),
  5. \ '-line', line('.')]
  6. " Read from stdin if modified.
  7. if &modified
  8. call add(l:cmd, '-modified')
  9. let [l:out, l:err] = go#util#Exec(l:cmd, go#util#archive())
  10. else
  11. let [l:out, l:err] = go#util#Exec(l:cmd)
  12. endif
  13. if l:err
  14. call go#util#EchoError(l:out)
  15. return
  16. endif
  17. try
  18. let l:json = json_decode(l:out)
  19. catch
  20. call go#util#EchoError(l:out)
  21. return
  22. endtry
  23. " Output is array:
  24. "[
  25. " {"start": 92, "end": 106, "code": "mail.Address{\n\tName: \"\",\n\tAddress: \"\",\n}"},
  26. " {...second struct...}
  27. " ]
  28. let l:pos = getpos('.')
  29. try
  30. for l:struct in l:json
  31. let l:code = split(l:struct['code'], "\n")
  32. " Add any code before/after the struct.
  33. exe l:struct['start'] . 'go'
  34. let l:code[0] = getline('.')[:col('.')-1] . l:code[0]
  35. exe l:struct['end'] . 'go'
  36. let l:code[len(l:code)-1] .= getline('.')[col('.'):]
  37. " Indent every line except the first one; makes it look nice.
  38. let l:indent = repeat("\t", indent('.') / &tabstop)
  39. for l:i in range(1, len(l:code)-1)
  40. let l:code[l:i] = l:indent . l:code[l:i]
  41. endfor
  42. " Out with the old ...
  43. exe 'normal! ' . l:struct['start'] . 'gov' . l:struct['end'] . 'gox'
  44. " ... in with the new.
  45. call setline('.', l:code[0])
  46. call append('.', l:code[1:])
  47. endfor
  48. finally
  49. call setpos('.', l:pos)
  50. endtry
  51. endfunction
  52. " vim: sw=2 ts=2 et