Guest User

Untitled

a guest
Jun 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.56 KB | None | 0 0
  1. # -*- coding: utf8 -*-
  2. import vim
  3. import sys
  4. import re
  5. import os
  6.  
  7. def normal(str):
  8. vim.command("normal! "+str)
  9.  
  10. def select_all_buffer():
  11. """Select all buffer """
  12. normal("ggVG")
  13.  
  14. # def current_line():
  15.  
  16. def vim_eval(arg):
  17. return vim.eval(arg)
  18.  
  19. def buffer_length():
  20. """Return buffer length """
  21. return len(cb())
  22.  
  23. def num_of_buffers():
  24. return len(vim.buffers)
  25.  
  26. def all_buffer_name():
  27. for b in vim.buffers:
  28. print b.name
  29.  
  30. def num_of_windows():
  31. return len(vim.windows)
  32.  
  33. def all_window_name():
  34. for w in vim.windows:
  35. print w
  36.  
  37. def vim_current_demo():
  38. print vim.current.line
  39. print vim.current.buffer
  40. print vim.current.window
  41. print vim.current.range
  42.  
  43. def cb():
  44. return vim.current.buffer
  45.  
  46. def vim_append(lines):
  47. vim.current.buffer.append(lines)
  48.  
  49. def delete_selected():
  50. del vim.current.range[:]
  51.  
  52. def selected_text():
  53. vim.current.range
  54.  
  55. def prompt(ask = 'input', mode = 'cui'):
  56. if mode == 'cui':
  57. input = vim_eval("input('%s')" % ask)
  58. else:
  59. input = vim_eval("inputdialog('%s')" % ask)
  60. return input
  61.  
  62. def surround_text(header=None, footer=None):
  63. """Surround selected text with header and footer """
  64. # header, footer):
  65. if not header: header = prompt("header? :")
  66. if not footer: footer = prompt("footer? :")
  67. cr = vim_get_range()
  68. new_text = [header] + cr[:] + [footer]
  69. cr[:] = None
  70. insert_text(cr.start,new_text)
  71.  
  72. def translate_selection(f):
  73. cr = vim_get_range()
  74. new_text = [ f(line) for line in cr[:]]
  75. cr[:] = None
  76. insert_text(cr.start,new_text)
  77.  
  78. def html_escape_selection():
  79. """HTML escape for selection"""
  80. translate_selection(html_escape)
  81.  
  82. def html_unescape_selection():
  83. """HTML unescape for selection"""
  84. translate_selection(html_unescape)
  85.  
  86. def upper_selection():
  87. """選択範囲を大文字にする。"""
  88. translate_selection(lambda x: x.upper() )
  89.  
  90. def lower_selection():
  91. """選択範囲を小文字にする。"""
  92. translate_selection(lambda x: x.lower() )
  93.  
  94. def commentify_selection():
  95. """選択範囲をコメントにする。"""
  96. surround_text('"""','"""')
  97.  
  98. def methodize_selection():
  99. """選択範囲を method にする。"""
  100. surround_text(None,'')
  101.  
  102. def insert_text(num,line):
  103. cb().range(num,num).append(line)
  104.  
  105. def edit_tmp(file="/tmp/hogebuffer", how="split"):
  106. """open temporary file """
  107. edit(file, how)
  108. vim_cmd("setlocal bufhidden=delete")
  109. vim_cmd("setlocal buftype=nofile")
  110. vim_cmd("setlocal noswapfile")
  111. vim_cmd("setlocal nobuflisted")
  112. vim_cmd("setlocal modifiable")
  113.  
  114. vim_range = -1
  115.  
  116. def vim_set_range():
  117. global vim_range
  118. vim_range = vim.current.range
  119.  
  120. def vim_get_range():
  121. global vim_range
  122. return vim_range
  123.  
  124. def vim_reset_range():
  125. global vim_range
  126. vim_range = -1
  127.  
  128. def vim_prompt():
  129. vim_cmd('echo')
  130. vim_cmd('redraw')
  131.  
  132. def vim_cmd(vim_ex_command):
  133. vim.command(vim_ex_command)
  134.  
  135. def edit(file, how="split"):
  136. cmd = how + " " + file
  137. vim_cmd(cmd)
  138.  
  139. def analyze_code(how="vsplit"):
  140. tmp_xml = "/tmp/output.xml"
  141. tmp_py = "/tmp/output.py"
  142. src = cb().name
  143. tchecker_cmd = "tchecker.py -o " + tmp_xml + " " + src
  144. annot_cmd = "annot.py " + tmp_xml + " " + src
  145. os.system(tchecker_cmd)
  146. ret = os.popen(annot_cmd).read().split("\n")
  147. edit(tmp_py, how)
  148. clear_buffer()
  149. insert_text(0, ret)
  150.  
  151. def clear_buffer():
  152. """Erase buffers contents"""
  153. del cb()[:]
  154.  
  155. def run_ipython():
  156. """Load current buffer to ipython"""
  157. cmd = "ruby $iterm.write('ipython %s')" % cb().name
  158. vim_cmd(cmd)
  159.  
  160.  
  161. def build_command_help(cmd_list):
  162. list = [ " %-30s %-10s" % (cmd.__name__, cmd.__doc__) for cmd in cmd_list]
  163. list[0] = '>' + list[0][1:]
  164. return list
  165.  
  166.  
  167. def vimpy_setup_key():
  168. lower_alpha = "abcdefghijklmnopqrstuvwxyz"
  169. upper_alpha = "abcdefghijklmnopqrstuvwxyz".upper()
  170. numbers = "0123456789"
  171. punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space
  172. chars = lower_alpha + upper_alpha + numbers + punctuation
  173. vim_cmd("setlocal timeout")
  174. vim_cmd("setlocal timeoutlen=0")
  175. vim_cmd("setlocal nonumber")
  176. fmt = "nnoremap <silent> <buffer> <Char-%s> :python pressed(%s)<CR>"
  177. list = [ fmt % (ord(char), ord(char)) for char in chars ]
  178. # for cmd in list: print cmd
  179. for cmd in list: vim_cmd(cmd)
  180.  
  181. fmt = "nnoremap <silent> <buffer> %s :python pressed_special('%s')<CR>"
  182. special_keys = {
  183. 'Backspace' : '<BS>',
  184. 'Backspace' : '<C-h>',
  185. 'AcceptSelection' : '<CR>',
  186. 'Cancel' : '<C-c>',
  187. 'Cancel' : '<C-g>',
  188. 'NextLine' : '<C-n>',
  189. 'PreviousLine' : '<C-p>',
  190. 'ClearLine' : '<C-u>',
  191. 'DeleteBackwordWord' : '<C-w>',
  192. }
  193. list = [ fmt % (key, func) for func, key in special_keys.items()]
  194. for cmd in list: vim_cmd(cmd)
  195.  
  196.  
  197. current_input = ""
  198.  
  199. # Prompt handling mini function
  200. def delete_char():
  201. global current_input
  202. current_input = current_input[:-1]
  203. update_candidate()
  204. update_inputline()
  205.  
  206. def cancel_vimpy():
  207. clear_line()
  208. vim_cmd("bdelete!")
  209. vim_cmd("wincmd p")
  210. vim_cmd("set timeoutlen=1000")
  211.  
  212. def next_line(): normal('j')
  213. def previous_line(): normal('k')
  214.  
  215. def clear_line():
  216. global current_input
  217. current_input = ""
  218. update()
  219.  
  220. def delete_backward_word():
  221. global current_input
  222. current_input = ' '.join(current_input.split()[:-1])
  223. update()
  224.  
  225. def do_action():
  226. """Docstring for select_command"""
  227. selected_cmd = vim_eval('expand("<cword>")')
  228. clear_line()
  229. vim_cmd("bdelete!")
  230. vim_cmd("wincmd p")
  231. vim_cmd("redraw!")
  232. if not selected_cmd == 'NO': let = eval(selected_cmd + "()")
  233. # vim_cmd("echo ")
  234. print_result(let)
  235. # vim_cmd("redraw!")
  236. vim_cmd("set timeoutlen=1000")
  237.  
  238. special_keys_func = {}
  239. special_keys_func['Backspace'] = delete_char
  240. special_keys_func['Cancel'] = cancel_vimpy
  241. special_keys_func['NextLine'] = next_line
  242. special_keys_func['PreviousLine'] = previous_line
  243. special_keys_func['AcceptSelection'] = do_action
  244. special_keys_func['ClearLine'] = clear_line
  245. special_keys_func['DeleteBackwordWord'] = delete_backward_word
  246.  
  247. def vim_py():
  248. global cmd_list
  249. vim_set_range()
  250. split_location = 'botright'
  251. split_command = "silent! %s 10split" % split_location
  252. edit_tmp("/tmp/cmdbuffer", split_command)
  253. vim_cmd("syn match CommandDesc ' .*$'")
  254. vim_cmd("syn match SelctedLine '> .*$'")
  255. vim_cmd("syn match NotFound 'NO MATCH'")
  256. vim_cmd('hi def link CommandDesc Function')
  257. vim_cmd('hi def link NotFound WarningMsg')
  258. vim_cmd('hi SelctedLine guibg=#293739')
  259. vim_cmd('setlocal nocursorline')
  260. vimpy_setup_key()
  261. insert_text(0, build_command_help(cmd_list))
  262. vim_set_winheight(len(cmd_list))
  263. update_inputline()
  264.  
  265. def update():
  266. update_candidate()
  267. update_inputline()
  268.  
  269. def pressed(key):
  270. global current_input
  271. input_key = chr(key)
  272. current_input += input_key
  273. update()
  274.  
  275. def pressed_special(key):
  276. global special_keys_func
  277. special_keys_func[key]()
  278.  
  279. def update_inputline():
  280. global current_input
  281. vim_cmd('redraw')
  282. ary = [ ('Comment', ">> "), ('Type', current_input), ('Function', '|') ]
  283. for highight, text in ary:
  284. vim_cmd("echohl " + highight)
  285. vim_cmd("echon '%s'" % text)
  286. vim_cmd('echohl None')
  287.  
  288. def print_result(arg):
  289. vim_cmd('redraw')
  290. ary = [ ('Comment', "[result] "), ('Directory', arg) ]
  291. for highight, text in ary:
  292. vim_cmd("echohl " + highight)
  293. vim_cmd("echon '%s'" % text)
  294. vim_cmd('echohl None')
  295.  
  296. def vim_set_winheight(num):
  297. vim.current.window.height = num
  298.  
  299. def build_candidate(source, ptns):
  300. if not len(ptns):
  301. return source
  302.  
  303. result = []
  304. first_match = 8; middle_match = 5
  305. score = {}
  306. for cmd in source: score[cmd] = 0
  307.  
  308. limit = 0
  309. for ptn in ptns.split():
  310. limit += middle_match
  311. search_first = "%s.*" % ptn
  312. search_middle = ".*%s.*" % ptn
  313. for cmd in source:
  314. if re.match(search_first, cmd.__name__):
  315. score[cmd] += first_match
  316. if re.match(search_middle, cmd.__name__):
  317. score[cmd] += middle_match
  318.  
  319. l = [ (key, val) for (key,val) in score.items() ]
  320. result = [ (cmd ,score) for cmd, score in sorted(l, lambda x,y: cmp(-x[1], -y[1])) ]
  321. return [ cmd for cmd, score in filter(lambda x: x[1] >= limit, result) ]
  322.  
  323. def update_candidate():
  324. global current_input
  325. global cmd_list
  326. clear_buffer()
  327. search_pattern = '.*' + current_input + '.*'
  328. candidate = build_candidate(cmd_list, current_input)
  329.  
  330. if len(candidate) == 0:
  331. candidate = ['NO MATCH']
  332. else:
  333. candidate = build_command_help(candidate)
  334. insert_text(0, candidate)
  335. vim_set_winheight(len(candidate))
  336.  
  337. html_escape_table = {
  338. "&": "&",
  339. ">": ">",
  340. "<": "<",
  341. }
  342.  
  343. def html_escape(text):
  344. return "".join(html_escape_table.get(c,c) for c in text)
  345.  
  346. def html_unescape(s):
  347. s = s.replace("<", "<")
  348. s = s.replace(">", ">")
  349. # this has to be last:
  350. s = s.replace("&", "&")
  351. return s
  352.  
  353. def nerd_tree():
  354. """NERDTree"""
  355. cmd = "NERDTree %s" % buffer_dir()
  356. vim_cmd(cmd)
  357.  
  358. def buffer_dir():
  359. return os.path.dirname(cb().name)
  360.  
  361. def win_maximize_height():
  362. """Maximize window height"""
  363. vim_cmd('wincmd _')
  364.  
  365. def win_maximize_width():
  366. """Maximize window width"""
  367. vim_cmd('wincmd |')
  368.  
  369. def win_equalize():
  370. """Equqlize window width"""
  371. vim_cmd('wincmd =')
  372.  
  373. def translate_english_to_japanese():
  374. """選択範囲を日本語に翻訳"""
  375. #[TODO] implement via google translate-api
  376. def e2j(s):
  377. s = s.replace("apple", "リンゴ")
  378. s = s.replace("orange", "オレンジ")
  379. return s
  380. translate_selection(html_escape)
  381.  
  382. def pwd():
  383. """Print working directory"""
  384. return vim_eval('getcwd()')
  385.  
  386. cmd_list = [
  387. select_all_buffer, buffer_length, clear_buffer,
  388. edit_tmp, surround_text, run_ipython, commentify_selection,
  389. upper_selection, lower_selection, html_escape_selection,
  390. html_unescape_selection, nerd_tree, pwd,
  391. win_maximize_height,
  392. win_maximize_width,
  393. win_equalize,
  394. methodize_selection,
  395. translate_english_to_japanese,
  396. ]
Add Comment
Please, Sign In to add comment