Guest User

Untitled

a guest
Nov 21st, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. " Execute currently selected visual range as Python. Lines are pre-processed
  2. " to remove extra indentation, leaders, or decorators that might be in place
  3. " due to the line range being part of a code block in a markup-language
  4. " document (such as ReStructured Text, Markdown, etc.)
  5. " Usage: Select a range of line in the buffer and then call ':EvalPy' to
  6. " execute those lines in the default system Python and show the results in the
  7. " command window. Using the 'bang' operator (':EvalPy!') will execute the
  8. " lines and insert the results in the current buffer.
  9. function! <SID>EvaluateCurrentRangeAsMarkedUpPython(insert_results) range
  10. "" get lines
  11. let [lnum1, col1] = getpos("'<")[1:2]
  12. let [lnum2, col2] = getpos("'>")[1:2]
  13. let lines = getline(lnum1, lnum2)
  14. " let lines[-1] = lines[-1][: col2 - 2]
  15. " let lines[0] = lines[0][col1 - 1:]
  16.  
  17. "" remove blank rows
  18. let rows = []
  19. for line in lines
  20. let row = substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '')
  21. if len(row) > 0
  22. call add(rows, line)
  23. endif
  24. endfor
  25. let lines = rows
  26.  
  27. if len(lines) == 0
  28. return
  29. endif
  30. let leader = matchstr(lines[0], '^\s*\(>>>\|\.\.\.\)\{0,1}\s*')
  31. let leader_len = len(leader)
  32. let code_lines = []
  33. for line in lines
  34. let code_line = strpart(line, leader_len)
  35. call add(code_lines, code_line)
  36. endfor
  37. let code = join(code_lines, "\n")
  38. if empty(a:insert_results)
  39. redir => result
  40. silent execute "!python -c " . shellescape(code)
  41. redir END
  42. let rows = split(result, '\n')[1:]
  43. let result = join(rows, "\n")
  44. echo result
  45. else
  46. let endpos = getpos("'>")
  47. call setpos('.', endpos)
  48. execute "r !python -c " . shellescape(code)
  49. endif
  50. endfunction
  51. command! -bang -range EvalPy :call s:EvaluateCurrentRangeAsMarkedUpPython("<bang>")
Add Comment
Please, Sign In to add comment