logo

dotfiles

My dotfiles, one branch per machine, rebased on base git clone https://hacktivis.me/git/dotfiles.git

go.py (20474B)


  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2014 Sébastien Helleu <flashcode@flashtux.org>
  4. # Copyright (C) 2010 m4v <lambdae2@gmail.com>
  5. # Copyright (C) 2011 stfn <stfnmd@googlemail.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. #
  21. # History:
  22. #
  23. # 2017-04-01, Sébastien Helleu <flashcode@flashtux.org>:
  24. # version 2.5: add option "buffer_number"
  25. # 2017-03-02, Sébastien Helleu <flashcode@flashtux.org>:
  26. # version 2.4: fix syntax and indentation error
  27. # 2017-02-25, Simmo Saan <simmo.saan@gmail.com>
  28. # version 2.3: fix fuzzy search breaking buffer number search display
  29. # 2016-01-28, ylambda <ylambda@koalabeast.com>
  30. # version 2.2: add option "fuzzy_search"
  31. # 2015-11-12, nils_2 <weechatter@arcor.de>
  32. # version 2.1: fix problem with buffer short_name "weechat", using option
  33. # "use_core_instead_weechat", see:
  34. # https://github.com/weechat/weechat/issues/574
  35. # 2014-05-12, Sébastien Helleu <flashcode@flashtux.org>:
  36. # version 2.0: add help on options, replace option "sort_by_activity" by
  37. # "sort" (add sort by name and first match at beginning of
  38. # name and by number), PEP8 compliance
  39. # 2012-11-26, Nei <anti.teamidiot.de>
  40. # version 1.9: add auto_jump option to automatically go to buffer when it
  41. # is uniquely selected
  42. # 2012-09-17, Sébastien Helleu <flashcode@flashtux.org>:
  43. # version 1.8: fix jump to non-active merged buffers (jump with buffer name
  44. # instead of number)
  45. # 2012-01-03 nils_2 <weechatter@arcor.de>
  46. # version 1.7: add option "use_core_instead_weechat"
  47. # 2012-01-03, Sébastien Helleu <flashcode@flashtux.org>:
  48. # version 1.6: make script compatible with Python 3.x
  49. # 2011-08-24, stfn <stfnmd@googlemail.com>:
  50. # version 1.5: /go with name argument jumps directly to buffer
  51. # Remember cursor position in buffer input
  52. # 2011-05-31, Elián Hanisch <lambdae2@gmail.com>:
  53. # version 1.4: Sort list of buffers by activity.
  54. # 2011-04-25, Sébastien Helleu <flashcode@flashtux.org>:
  55. # version 1.3: add info "go_running" (used by script input_lock.rb)
  56. # 2010-11-01, Sébastien Helleu <flashcode@flashtux.org>:
  57. # version 1.2: use high priority for hooks to prevent conflict with other
  58. # plugins/scripts (WeeChat >= 0.3.4 only)
  59. # 2010-03-25, Elián Hanisch <lambdae2@gmail.com>:
  60. # version 1.1: use a space to match the end of a string
  61. # 2009-11-16, Sébastien Helleu <flashcode@flashtux.org>:
  62. # version 1.0: add new option to display short names
  63. # 2009-06-15, Sébastien Helleu <flashcode@flashtux.org>:
  64. # version 0.9: fix typo in /help go with command /key
  65. # 2009-05-16, Sébastien Helleu <flashcode@flashtux.org>:
  66. # version 0.8: search buffer by number, fix bug when window is split
  67. # 2009-05-03, Sébastien Helleu <flashcode@flashtux.org>:
  68. # version 0.7: eat tab key (do not complete input, just move buffer
  69. # pointer)
  70. # 2009-05-02, Sébastien Helleu <flashcode@flashtux.org>:
  71. # version 0.6: sync with last API changes
  72. # 2009-03-22, Sébastien Helleu <flashcode@flashtux.org>:
  73. # version 0.5: update modifier signal name for input text display,
  74. # fix arguments for function string_remove_color
  75. # 2009-02-18, Sébastien Helleu <flashcode@flashtux.org>:
  76. # version 0.4: do not hook command and init options if register failed
  77. # 2009-02-08, Sébastien Helleu <flashcode@flashtux.org>:
  78. # version 0.3: case insensitive search for buffers names
  79. # 2009-02-08, Sébastien Helleu <flashcode@flashtux.org>:
  80. # version 0.2: add help about Tab key
  81. # 2009-02-08, Sébastien Helleu <flashcode@flashtux.org>:
  82. # version 0.1: initial release
  83. #
  84. """
  85. Quick jump to buffers.
  86. (this script requires WeeChat 0.3.0 or newer)
  87. """
  88. from __future__ import print_function
  89. SCRIPT_NAME = 'go'
  90. SCRIPT_AUTHOR = 'Sébastien Helleu <flashcode@flashtux.org>'
  91. SCRIPT_VERSION = '2.5'
  92. SCRIPT_LICENSE = 'GPL3'
  93. SCRIPT_DESC = 'Quick jump to buffers'
  94. SCRIPT_COMMAND = 'go'
  95. IMPORT_OK = True
  96. try:
  97. import weechat
  98. except ImportError:
  99. print('This script must be run under WeeChat.')
  100. print('Get WeeChat now at: http://www.weechat.org/')
  101. IMPORT_OK = False
  102. import re
  103. # script options
  104. SETTINGS = {
  105. 'color_number': (
  106. 'yellow,magenta',
  107. 'color for buffer number (not selected)'),
  108. 'color_number_selected': (
  109. 'yellow,red',
  110. 'color for selected buffer number'),
  111. 'color_name': (
  112. 'black,cyan',
  113. 'color for buffer name (not selected)'),
  114. 'color_name_selected': (
  115. 'black,brown',
  116. 'color for a selected buffer name'),
  117. 'color_name_highlight': (
  118. 'red,cyan',
  119. 'color for highlight in buffer name (not selected)'),
  120. 'color_name_highlight_selected': (
  121. 'red,brown',
  122. 'color for highlight in a selected buffer name'),
  123. 'message': (
  124. 'Go to: ',
  125. 'message to display before list of buffers'),
  126. 'short_name': (
  127. 'off',
  128. 'display and search in short names instead of buffer name'),
  129. 'sort': (
  130. 'number,beginning',
  131. 'comma-separated list of keys to sort buffers '
  132. '(the order is important, sorts are performed in the given order): '
  133. 'name = sort by name (or short name), ',
  134. 'hotlist = sort by hotlist order, '
  135. 'number = first match a buffer number before digits in name, '
  136. 'beginning = first match at beginning of names (or short names); '
  137. 'the default sort of buffers is by numbers'),
  138. 'use_core_instead_weechat': (
  139. 'off',
  140. 'use name "core" instead of "weechat" for core buffer'),
  141. 'auto_jump': (
  142. 'off',
  143. 'automatically jump to buffer when it is uniquely selected'),
  144. 'fuzzy_search': (
  145. 'off',
  146. 'search buffer matches using approximation'),
  147. 'buffer_number': (
  148. 'on',
  149. 'display buffer number'),
  150. }
  151. # hooks management
  152. HOOK_COMMAND_RUN = {
  153. 'input': ('/input *', 'go_command_run_input'),
  154. 'buffer': ('/buffer *', 'go_command_run_buffer'),
  155. 'window': ('/window *', 'go_command_run_window'),
  156. }
  157. hooks = {}
  158. # input before command /go (we'll restore it later)
  159. saved_input = ''
  160. saved_input_pos = 0
  161. # last user input (if changed, we'll update list of matching buffers)
  162. old_input = None
  163. # matching buffers
  164. buffers = []
  165. buffers_pos = 0
  166. def go_option_enabled(option):
  167. """Checks if a boolean script option is enabled or not."""
  168. return weechat.config_string_to_boolean(weechat.config_get_plugin(option))
  169. def go_info_running(data, info_name, arguments):
  170. """Returns "1" if go is running, otherwise "0"."""
  171. return '1' if 'modifier' in hooks else '0'
  172. def go_unhook_one(hook):
  173. """Unhook something hooked by this script."""
  174. global hooks
  175. if hook in hooks:
  176. weechat.unhook(hooks[hook])
  177. del hooks[hook]
  178. def go_unhook_all():
  179. """Unhook all."""
  180. go_unhook_one('modifier')
  181. for hook in HOOK_COMMAND_RUN:
  182. go_unhook_one(hook)
  183. def go_hook_all():
  184. """Hook command_run and modifier."""
  185. global hooks
  186. priority = ''
  187. version = weechat.info_get('version_number', '') or 0
  188. # use high priority for hook to prevent conflict with other plugins/scripts
  189. # (WeeChat >= 0.3.4 only)
  190. if int(version) >= 0x00030400:
  191. priority = '2000|'
  192. for hook, value in HOOK_COMMAND_RUN.items():
  193. if hook not in hooks:
  194. hooks[hook] = weechat.hook_command_run(
  195. '%s%s' % (priority, value[0]),
  196. value[1], '')
  197. if 'modifier' not in hooks:
  198. hooks['modifier'] = weechat.hook_modifier(
  199. 'input_text_display_with_cursor', 'go_input_modifier', '')
  200. def go_start(buf):
  201. """Start go on buffer."""
  202. global saved_input, saved_input_pos, old_input, buffers_pos
  203. go_hook_all()
  204. saved_input = weechat.buffer_get_string(buf, 'input')
  205. saved_input_pos = weechat.buffer_get_integer(buf, 'input_pos')
  206. weechat.buffer_set(buf, 'input', '')
  207. old_input = None
  208. buffers_pos = 0
  209. def go_end(buf):
  210. """End go on buffer."""
  211. global saved_input, saved_input_pos, old_input
  212. go_unhook_all()
  213. weechat.buffer_set(buf, 'input', saved_input)
  214. weechat.buffer_set(buf, 'input_pos', str(saved_input_pos))
  215. old_input = None
  216. def go_match_beginning(buf, string):
  217. """Check if a string matches the beginning of buffer name/short name."""
  218. if not string:
  219. return False
  220. esc_str = re.escape(string)
  221. if re.search(r'^#?' + esc_str, buf['name']) \
  222. or re.search(r'^#?' + esc_str, buf['short_name']):
  223. return True
  224. return False
  225. def go_match_fuzzy(name, string):
  226. """Check if string matches name using approximation."""
  227. if not string:
  228. return False
  229. name_len = len(name)
  230. string_len = len(string)
  231. if string_len > name_len:
  232. return False
  233. if name_len == string_len:
  234. return name == string
  235. # Attempt to match all chars somewhere in name
  236. prev_index = -1
  237. for i, char in enumerate(string):
  238. index = name.find(char, prev_index+1)
  239. if index == -1:
  240. return False
  241. prev_index = index
  242. return True
  243. def go_now(buf, args):
  244. """Go to buffer specified by args."""
  245. listbuf = go_matching_buffers(args)
  246. if not listbuf:
  247. return
  248. # prefer buffer that matches at beginning (if option is enabled)
  249. if 'beginning' in weechat.config_get_plugin('sort').split(','):
  250. for index in range(len(listbuf)):
  251. if go_match_beginning(listbuf[index], args):
  252. weechat.command(buf,
  253. '/buffer ' + str(listbuf[index]['full_name']))
  254. return
  255. # jump to first buffer in matching buffers by default
  256. weechat.command(buf, '/buffer ' + str(listbuf[0]['full_name']))
  257. def go_cmd(data, buf, args):
  258. """Command "/go": just hook what we need."""
  259. global hooks
  260. if args:
  261. go_now(buf, args)
  262. elif 'modifier' in hooks:
  263. go_end(buf)
  264. else:
  265. go_start(buf)
  266. return weechat.WEECHAT_RC_OK
  267. def go_matching_buffers(strinput):
  268. """Return a list with buffers matching user input."""
  269. global buffers_pos
  270. listbuf = []
  271. if len(strinput) == 0:
  272. buffers_pos = 0
  273. strinput = strinput.lower()
  274. infolist = weechat.infolist_get('buffer', '', '')
  275. while weechat.infolist_next(infolist):
  276. short_name = weechat.infolist_string(infolist, 'short_name')
  277. if go_option_enabled('short_name'):
  278. name = weechat.infolist_string(infolist, 'short_name')
  279. else:
  280. name = weechat.infolist_string(infolist, 'name')
  281. if name == 'weechat' \
  282. and go_option_enabled('use_core_instead_weechat') \
  283. and weechat.infolist_string(infolist, 'plugin_name') == 'core':
  284. name = 'core'
  285. number = weechat.infolist_integer(infolist, 'number')
  286. full_name = weechat.infolist_string(infolist, 'full_name')
  287. if not full_name:
  288. full_name = '%s.%s' % (
  289. weechat.infolist_string(infolist, 'plugin_name'),
  290. weechat.infolist_string(infolist, 'name'))
  291. pointer = weechat.infolist_pointer(infolist, 'pointer')
  292. matching = name.lower().find(strinput) >= 0
  293. if not matching and strinput[-1] == ' ':
  294. matching = name.lower().endswith(strinput.strip())
  295. if not matching and go_option_enabled('fuzzy_search'):
  296. matching = go_match_fuzzy(name.lower(), strinput)
  297. if not matching and strinput.isdigit():
  298. matching = str(number).startswith(strinput)
  299. if len(strinput) == 0 or matching:
  300. listbuf.append({
  301. 'number': number,
  302. 'short_name': short_name,
  303. 'name': name,
  304. 'full_name': full_name,
  305. 'pointer': pointer,
  306. })
  307. weechat.infolist_free(infolist)
  308. # sort buffers
  309. hotlist = []
  310. infolist = weechat.infolist_get('hotlist', '', '')
  311. while weechat.infolist_next(infolist):
  312. hotlist.append(
  313. weechat.infolist_pointer(infolist, 'buffer_pointer'))
  314. weechat.infolist_free(infolist)
  315. last_index_hotlist = len(hotlist)
  316. def _sort_name(buf):
  317. """Sort buffers by name (or short name)."""
  318. return buf['name']
  319. def _sort_hotlist(buf):
  320. """Sort buffers by hotlist order."""
  321. try:
  322. return hotlist.index(buf['pointer'])
  323. except ValueError:
  324. # not in hotlist, always last.
  325. return last_index_hotlist
  326. def _sort_match_number(buf):
  327. """Sort buffers by match on number."""
  328. return 0 if str(buf['number']) == strinput else 1
  329. def _sort_match_beginning(buf):
  330. """Sort buffers by match at beginning."""
  331. return 0 if go_match_beginning(buf, strinput) else 1
  332. funcs = {
  333. 'name': _sort_name,
  334. 'hotlist': _sort_hotlist,
  335. 'number': _sort_match_number,
  336. 'beginning': _sort_match_beginning,
  337. }
  338. for key in weechat.config_get_plugin('sort').split(','):
  339. if key in funcs:
  340. listbuf = sorted(listbuf, key=funcs[key])
  341. if not strinput:
  342. index = [i for i, buf in enumerate(listbuf)
  343. if buf['pointer'] == weechat.current_buffer()]
  344. if index:
  345. buffers_pos = index[0]
  346. return listbuf
  347. def go_buffers_to_string(listbuf, pos, strinput):
  348. """Return string built with list of buffers found (matching user input)."""
  349. string = ''
  350. strinput = strinput.lower()
  351. for i in range(len(listbuf)):
  352. selected = '_selected' if i == pos else ''
  353. buffer_name = listbuf[i]['name']
  354. index = buffer_name.lower().find(strinput)
  355. if index >= 0:
  356. index2 = index + len(strinput)
  357. name = '%s%s%s%s%s' % (
  358. buffer_name[:index],
  359. weechat.color(weechat.config_get_plugin(
  360. 'color_name_highlight' + selected)),
  361. buffer_name[index:index2],
  362. weechat.color(weechat.config_get_plugin(
  363. 'color_name' + selected)),
  364. buffer_name[index2:])
  365. elif go_option_enabled("fuzzy_search") and \
  366. go_match_fuzzy(buffer_name.lower(), strinput):
  367. name = ""
  368. prev_index = -1
  369. for char in strinput.lower():
  370. index = buffer_name.lower().find(char, prev_index+1)
  371. if prev_index < 0:
  372. name += buffer_name[:index]
  373. name += weechat.color(weechat.config_get_plugin(
  374. 'color_name_highlight' + selected))
  375. if prev_index >= 0 and index > prev_index+1:
  376. name += weechat.color(weechat.config_get_plugin(
  377. 'color_name' + selected))
  378. name += buffer_name[prev_index+1:index]
  379. name += weechat.color(weechat.config_get_plugin(
  380. 'color_name_highlight' + selected))
  381. name += buffer_name[index]
  382. prev_index = index
  383. name += weechat.color(weechat.config_get_plugin(
  384. 'color_name' + selected))
  385. name += buffer_name[prev_index+1:]
  386. else:
  387. name = buffer_name
  388. string += ' '
  389. if go_option_enabled('buffer_number'):
  390. string += '%s%s' % (
  391. weechat.color(weechat.config_get_plugin(
  392. 'color_number' + selected)),
  393. str(listbuf[i]['number']))
  394. string += '%s%s%s' % (
  395. weechat.color(weechat.config_get_plugin(
  396. 'color_name' + selected)),
  397. name,
  398. weechat.color('reset'))
  399. return ' ' + string if string else ''
  400. def go_input_modifier(data, modifier, modifier_data, string):
  401. """This modifier is called when input text item is built by WeeChat.
  402. This is commonly called after changes in input or cursor move: it builds
  403. a new input with prefix ("Go to:"), and suffix (list of buffers found).
  404. """
  405. global old_input, buffers, buffers_pos
  406. if modifier_data != weechat.current_buffer():
  407. return ''
  408. names = ''
  409. new_input = weechat.string_remove_color(string, '')
  410. new_input = new_input.lstrip()
  411. if old_input is None or new_input != old_input:
  412. old_buffers = buffers
  413. buffers = go_matching_buffers(new_input)
  414. if buffers != old_buffers and len(new_input) > 0:
  415. if len(buffers) == 1 and go_option_enabled('auto_jump'):
  416. weechat.command(modifier_data, '/wait 1ms /input return')
  417. buffers_pos = 0
  418. old_input = new_input
  419. names = go_buffers_to_string(buffers, buffers_pos, new_input.strip())
  420. return weechat.config_get_plugin('message') + string + names
  421. def go_command_run_input(data, buf, command):
  422. """Function called when a command "/input xxx" is run."""
  423. global buffers, buffers_pos
  424. if command == '/input search_text' or command.find('/input jump') == 0:
  425. # search text or jump to another buffer is forbidden now
  426. return weechat.WEECHAT_RC_OK_EAT
  427. elif command == '/input complete_next':
  428. # choose next buffer in list
  429. buffers_pos += 1
  430. if buffers_pos >= len(buffers):
  431. buffers_pos = 0
  432. weechat.hook_signal_send('input_text_changed',
  433. weechat.WEECHAT_HOOK_SIGNAL_STRING, '')
  434. return weechat.WEECHAT_RC_OK_EAT
  435. elif command == '/input complete_previous':
  436. # choose previous buffer in list
  437. buffers_pos -= 1
  438. if buffers_pos < 0:
  439. buffers_pos = len(buffers) - 1
  440. weechat.hook_signal_send('input_text_changed',
  441. weechat.WEECHAT_HOOK_SIGNAL_STRING, '')
  442. return weechat.WEECHAT_RC_OK_EAT
  443. elif command == '/input return':
  444. # switch to selected buffer (if any)
  445. go_end(buf)
  446. if len(buffers) > 0:
  447. weechat.command(
  448. buf, '/buffer ' + str(buffers[buffers_pos]['full_name']))
  449. return weechat.WEECHAT_RC_OK_EAT
  450. return weechat.WEECHAT_RC_OK
  451. def go_command_run_buffer(data, buf, command):
  452. """Function called when a command "/buffer xxx" is run."""
  453. return weechat.WEECHAT_RC_OK_EAT
  454. def go_command_run_window(data, buf, command):
  455. """Function called when a command "/window xxx" is run."""
  456. return weechat.WEECHAT_RC_OK_EAT
  457. def go_unload_script():
  458. """Function called when script is unloaded."""
  459. go_unhook_all()
  460. return weechat.WEECHAT_RC_OK
  461. def go_main():
  462. """Entry point."""
  463. if not weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
  464. SCRIPT_LICENSE, SCRIPT_DESC,
  465. 'go_unload_script', ''):
  466. return
  467. weechat.hook_command(
  468. SCRIPT_COMMAND,
  469. 'Quick jump to buffers', '[name]',
  470. 'name: directly jump to buffer by name (without argument, list is '
  471. 'displayed)\n\n'
  472. 'You can bind command to a key, for example:\n'
  473. ' /key bind meta-g /go\n\n'
  474. 'You can use completion key (commonly Tab and shift-Tab) to select '
  475. 'next/previous buffer in list.',
  476. '%(buffers_names)',
  477. 'go_cmd', '')
  478. # set default settings
  479. version = weechat.info_get('version_number', '') or 0
  480. for option, value in SETTINGS.items():
  481. if not weechat.config_is_set_plugin(option):
  482. weechat.config_set_plugin(option, value[0])
  483. if int(version) >= 0x00030500:
  484. weechat.config_set_desc_plugin(
  485. option, '%s (default: "%s")' % (value[1], value[0]))
  486. weechat.hook_info('go_running',
  487. 'Return "1" if go is running, otherwise "0"',
  488. '',
  489. 'go_info_running', '')
  490. if __name__ == "__main__" and IMPORT_OK:
  491. go_main()