logo

dotfiles

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

autosort.py (34830B)


  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2017 Maarten de Vries <maarten@de-vri.es>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. #
  19. # Autosort automatically keeps your buffers sorted and grouped by server.
  20. # You can define your own sorting rules. See /help autosort for more details.
  21. #
  22. # https://github.com/de-vri-es/weechat-autosort
  23. #
  24. #
  25. # Changelog:
  26. # 3.4:
  27. # * Fix rate-limit of sorting to prevent high CPU load and lock-ups.
  28. # * Fix bug in parsing empty arguments for info hooks.
  29. # * Add debug_log option to aid with debugging.
  30. # * Correct a few typos.
  31. # 3.3:
  32. # * Fix the /autosort debug command for unicode.
  33. # * Update the default rules to work better with Slack.
  34. # 3.2:
  35. # * Fix python3 compatiblity.
  36. # 3.1:
  37. # * Use colors to format the help text.
  38. # 3.0:
  39. # * Switch to evaluated expressions for sorting.
  40. # * Add `/autosort debug` command.
  41. # * Add ${info:autosort_replace,from,to,text} to replace substrings in sort rules.
  42. # * Add ${info:autosort_order,value,first,second,third} to ease writing sort rules.
  43. # * Make tab completion context aware.
  44. # 2.8:
  45. # * Fix compatibility with python 3 regarding unicode handling.
  46. # 2.7:
  47. # * Fix sorting of buffers with spaces in their name.
  48. # 2.6:
  49. # * Ignore case in rules when doing case insensitive sorting.
  50. # 2.5:
  51. # * Fix handling unicode buffer names.
  52. # * Add hint to set irc.look.server_buffer to independent and buffers.look.indenting to on.
  53. # 2.4:
  54. # * Make script python3 compatible.
  55. # 2.3:
  56. # * Fix sorting items without score last (regressed in 2.2).
  57. # 2.2:
  58. # * Add configuration option for signals that trigger a sort.
  59. # * Add command to manually trigger a sort (/autosort sort).
  60. # * Add replacement patterns to apply before sorting.
  61. # 2.1:
  62. # * Fix some minor style issues.
  63. # 2.0:
  64. # * Allow for custom sort rules.
  65. #
  66. import json
  67. import math
  68. import re
  69. import sys
  70. import time
  71. import weechat
  72. SCRIPT_NAME = 'autosort'
  73. SCRIPT_AUTHOR = 'Maarten de Vries <maarten@de-vri.es>'
  74. SCRIPT_VERSION = '3.4'
  75. SCRIPT_LICENSE = 'GPL3'
  76. SCRIPT_DESC = 'Flexible automatic (or manual) buffer sorting based on eval expressions.'
  77. config = None
  78. hooks = []
  79. signal_delay_timer = None
  80. sort_limit_timer = None
  81. sort_queued = False
  82. # Make sure that unicode, bytes and str are always available in python2 and 3.
  83. # For python 2, str == bytes
  84. # For python 3, str == unicode
  85. if sys.version_info[0] >= 3:
  86. unicode = str
  87. def ensure_str(input):
  88. '''
  89. Make sure the given type if the correct string type for the current python version.
  90. That means bytes for python2 and unicode for python3.
  91. '''
  92. if not isinstance(input, str):
  93. if isinstance(input, bytes):
  94. return input.encode('utf-8')
  95. if isinstance(input, unicode):
  96. return input.decode('utf-8')
  97. return input
  98. if hasattr(time, 'perf_counter'):
  99. perf_counter = time.perf_counter
  100. else:
  101. perf_counter = time.clock
  102. def casefold(string):
  103. if hasattr(string, 'casefold'): return string.casefold()
  104. # Fall back to lowercasing for python2.
  105. return string.lower()
  106. def list_swap(values, a, b):
  107. values[a], values[b] = values[b], values[a]
  108. def list_move(values, old_index, new_index):
  109. values.insert(new_index, values.pop(old_index))
  110. def list_find(collection, value):
  111. for i, elem in enumerate(collection):
  112. if elem == value: return i
  113. return None
  114. class HumanReadableError(Exception):
  115. pass
  116. def parse_int(arg, arg_name = 'argument'):
  117. ''' Parse an integer and provide a more human readable error. '''
  118. arg = arg.strip()
  119. try:
  120. return int(arg)
  121. except ValueError:
  122. raise HumanReadableError('Invalid {0}: expected integer, got "{1}".'.format(arg_name, arg))
  123. def decode_rules(blob):
  124. parsed = json.loads(blob)
  125. if not isinstance(parsed, list):
  126. log('Malformed rules, expected a JSON encoded list of strings, but got a {0}. No rules have been loaded. Please fix the setting manually.'.format(type(parsed)))
  127. return []
  128. for i, entry in enumerate(parsed):
  129. if not isinstance(entry, (str, unicode)):
  130. log('Rule #{0} is not a string but a {1}. No rules have been loaded. Please fix the setting manually.'.format(i, type(entry)))
  131. return []
  132. return parsed
  133. def decode_helpers(blob):
  134. parsed = json.loads(blob)
  135. if not isinstance(parsed, dict):
  136. log('Malformed helpers, expected a JSON encoded dictionary but got a {0}. No helpers have been loaded. Please fix the setting manually.'.format(type(parsed)))
  137. return {}
  138. for key, value in parsed.items():
  139. if not isinstance(value, (str, unicode)):
  140. log('Helper "{0}" is not a string but a {1}. No helpers have been loaded. Please fix setting manually.'.format(key, type(value)))
  141. return {}
  142. return parsed
  143. class Config:
  144. ''' The autosort configuration. '''
  145. default_rules = json.dumps([
  146. '${core_first}',
  147. '${irc_last}',
  148. '${buffer.plugin.name}',
  149. '${irc_raw_first}',
  150. '${if:${plugin}==irc?${server}}',
  151. '${if:${plugin}==irc?${info:autosort_order,${type},server,*,channel,private}}',
  152. '${if:${plugin}==irc?${hashless_name}}',
  153. '${buffer.full_name}',
  154. ])
  155. default_helpers = json.dumps({
  156. 'core_first': '${if:${buffer.full_name}!=core.weechat}',
  157. 'irc_first': '${if:${buffer.plugin.name}!=irc}',
  158. 'irc_last': '${if:${buffer.plugin.name}==irc}',
  159. 'irc_raw_first': '${if:${buffer.full_name}!=irc.irc_raw}',
  160. 'irc_raw_last': '${if:${buffer.full_name}==irc.irc_raw}',
  161. 'hashless_name': '${info:autosort_replace,#,,${buffer.name}}',
  162. })
  163. default_signal_delay = 5
  164. default_sort_limit = 100
  165. default_signals = 'buffer_opened buffer_merged buffer_unmerged buffer_renamed'
  166. def __init__(self, filename):
  167. ''' Initialize the configuration. '''
  168. self.filename = filename
  169. self.config_file = weechat.config_new(self.filename, '', '')
  170. self.sorting_section = None
  171. self.v3_section = None
  172. self.case_sensitive = False
  173. self.rules = []
  174. self.helpers = {}
  175. self.signals = []
  176. self.signal_delay = Config.default_signal_delay,
  177. self.sort_limit = Config.default_sort_limit,
  178. self.sort_on_config = True
  179. self.debug_log = False
  180. self.__case_sensitive = None
  181. self.__rules = None
  182. self.__helpers = None
  183. self.__signals = None
  184. self.__signal_delay = None
  185. self.__sort_limit = None
  186. self.__sort_on_config = None
  187. self.__debug_log = None
  188. if not self.config_file:
  189. log('Failed to initialize configuration file "{0}".'.format(self.filename))
  190. return
  191. self.sorting_section = weechat.config_new_section(self.config_file, 'sorting', False, False, '', '', '', '', '', '', '', '', '', '')
  192. self.v3_section = weechat.config_new_section(self.config_file, 'v3', False, False, '', '', '', '', '', '', '', '', '', '')
  193. if not self.sorting_section:
  194. log('Failed to initialize section "sorting" of configuration file.')
  195. weechat.config_free(self.config_file)
  196. return
  197. self.__case_sensitive = weechat.config_new_option(
  198. self.config_file, self.sorting_section,
  199. 'case_sensitive', 'boolean',
  200. 'If this option is on, sorting is case sensitive.',
  201. '', 0, 0, 'off', 'off', 0,
  202. '', '', '', '', '', ''
  203. )
  204. weechat.config_new_option(
  205. self.config_file, self.sorting_section,
  206. 'rules', 'string',
  207. 'Sort rules used by autosort v2.x and below. Not used by autosort anymore.',
  208. '', 0, 0, '', '', 0,
  209. '', '', '', '', '', ''
  210. )
  211. weechat.config_new_option(
  212. self.config_file, self.sorting_section,
  213. 'replacements', 'string',
  214. 'Replacement patterns used by autosort v2.x and below. Not used by autosort anymore.',
  215. '', 0, 0, '', '', 0,
  216. '', '', '', '', '', ''
  217. )
  218. self.__rules = weechat.config_new_option(
  219. self.config_file, self.v3_section,
  220. 'rules', 'string',
  221. 'An ordered list of sorting rules encoded as JSON. See /help autosort for commands to manipulate these rules.',
  222. '', 0, 0, Config.default_rules, Config.default_rules, 0,
  223. '', '', '', '', '', ''
  224. )
  225. self.__helpers = weechat.config_new_option(
  226. self.config_file, self.v3_section,
  227. 'helpers', 'string',
  228. 'A dictionary helper variables to use in the sorting rules, encoded as JSON. See /help autosort for commands to manipulate these helpers.',
  229. '', 0, 0, Config.default_helpers, Config.default_helpers, 0,
  230. '', '', '', '', '', ''
  231. )
  232. self.__signals = weechat.config_new_option(
  233. self.config_file, self.sorting_section,
  234. 'signals', 'string',
  235. 'A space separated list of signals that will cause autosort to resort your buffer list.',
  236. '', 0, 0, Config.default_signals, Config.default_signals, 0,
  237. '', '', '', '', '', ''
  238. )
  239. self.__signal_delay = weechat.config_new_option(
  240. self.config_file, self.sorting_section,
  241. 'signal_delay', 'integer',
  242. 'Delay in milliseconds to wait after a signal before sorting the buffer list. This prevents triggering many times if multiple signals arrive in a short time. It can also be needed to wait for buffer localvars to be available.',
  243. '', 0, 1000, str(Config.default_signal_delay), str(Config.default_signal_delay), 0,
  244. '', '', '', '', '', ''
  245. )
  246. self.__sort_limit = weechat.config_new_option(
  247. self.config_file, self.sorting_section,
  248. 'sort_limit', 'integer',
  249. 'Minimum delay in milliseconds to wait after sorting before signals can trigger a sort again. This is effectively a rate limit on sorting. Keeping signal_delay low while setting this higher can reduce excessive sorting without a long initial delay.',
  250. '', 0, 1000, str(Config.default_sort_limit), str(Config.default_sort_limit), 0,
  251. '', '', '', '', '', ''
  252. )
  253. self.__sort_on_config = weechat.config_new_option(
  254. self.config_file, self.sorting_section,
  255. 'sort_on_config_change', 'boolean',
  256. 'Decides if the buffer list should be sorted when autosort configuration changes.',
  257. '', 0, 0, 'on', 'on', 0,
  258. '', '', '', '', '', ''
  259. )
  260. self.__debug_log = weechat.config_new_option(
  261. self.config_file, self.sorting_section,
  262. 'debug_log', 'boolean',
  263. 'If enabled, print more debug messages. Not recommended for normal usage.',
  264. '', 0, 0, 'off', 'off', 0,
  265. '', '', '', '', '', ''
  266. )
  267. if weechat.config_read(self.config_file) != weechat.WEECHAT_RC_OK:
  268. log('Failed to load configuration file.')
  269. if weechat.config_write(self.config_file) != weechat.WEECHAT_RC_OK:
  270. log('Failed to write configuration file.')
  271. self.reload()
  272. def reload(self):
  273. ''' Load configuration variables. '''
  274. self.case_sensitive = weechat.config_boolean(self.__case_sensitive)
  275. rules_blob = weechat.config_string(self.__rules)
  276. helpers_blob = weechat.config_string(self.__helpers)
  277. signals_blob = weechat.config_string(self.__signals)
  278. self.rules = decode_rules(rules_blob)
  279. self.helpers = decode_helpers(helpers_blob)
  280. self.signals = signals_blob.split()
  281. self.signal_delay = weechat.config_integer(self.__signal_delay)
  282. self.sort_limit = weechat.config_integer(self.__sort_limit)
  283. self.sort_on_config = weechat.config_boolean(self.__sort_on_config)
  284. self.debug_log = weechat.config_boolean(self.__debug_log)
  285. def save_rules(self, run_callback = True):
  286. ''' Save the current rules to the configuration. '''
  287. weechat.config_option_set(self.__rules, json.dumps(self.rules), run_callback)
  288. def save_helpers(self, run_callback = True):
  289. ''' Save the current helpers to the configuration. '''
  290. weechat.config_option_set(self.__helpers, json.dumps(self.helpers), run_callback)
  291. def pad(sequence, length, padding = None):
  292. ''' Pad a list until is has a certain length. '''
  293. return sequence + [padding] * max(0, (length - len(sequence)))
  294. def log(message, buffer = 'NULL'):
  295. weechat.prnt(buffer, 'autosort: {0}'.format(message))
  296. def debug(message, buffer = 'NULL'):
  297. if config.debug_log:
  298. weechat.prnt(buffer, 'autosort: debug: {0}'.format(message))
  299. def get_buffers():
  300. ''' Get a list of all the buffers in weechat. '''
  301. hdata = weechat.hdata_get('buffer')
  302. buffer = weechat.hdata_get_list(hdata, "gui_buffers");
  303. result = []
  304. while buffer:
  305. number = weechat.hdata_integer(hdata, buffer, 'number')
  306. result.append((number, buffer))
  307. buffer = weechat.hdata_pointer(hdata, buffer, 'next_buffer')
  308. return hdata, result
  309. class MergedBuffers(list):
  310. """ A list of merged buffers, possibly of size 1. """
  311. def __init__(self, number):
  312. super(MergedBuffers, self).__init__()
  313. self.number = number
  314. def merge_buffer_list(buffers):
  315. '''
  316. Group merged buffers together.
  317. The output is a list of MergedBuffers.
  318. '''
  319. if not buffers: return []
  320. result = {}
  321. for number, buffer in buffers:
  322. if number not in result: result[number] = MergedBuffers(number)
  323. result[number].append(buffer)
  324. return result.values()
  325. def sort_buffers(hdata, buffers, rules, helpers, case_sensitive):
  326. for merged in buffers:
  327. for buffer in merged:
  328. name = weechat.hdata_string(hdata, buffer, 'name')
  329. return sorted(buffers, key=merged_sort_key(rules, helpers, case_sensitive))
  330. def buffer_sort_key(rules, helpers, case_sensitive):
  331. ''' Create a sort key function for a list of lists of merged buffers. '''
  332. def key(buffer):
  333. extra_vars = {}
  334. for helper_name, helper in sorted(helpers.items()):
  335. expanded = weechat.string_eval_expression(helper, {"buffer": buffer}, {}, {})
  336. extra_vars[helper_name] = expanded if case_sensitive else casefold(expanded)
  337. result = []
  338. for rule in rules:
  339. expanded = weechat.string_eval_expression(rule, {"buffer": buffer}, extra_vars, {})
  340. result.append(expanded if case_sensitive else casefold(expanded))
  341. return result
  342. return key
  343. def merged_sort_key(rules, helpers, case_sensitive):
  344. buffer_key = buffer_sort_key(rules, helpers, case_sensitive)
  345. def key(merged):
  346. best = None
  347. for buffer in merged:
  348. this = buffer_key(buffer)
  349. if best is None or this < best: best = this
  350. return best
  351. return key
  352. def apply_buffer_order(buffers):
  353. ''' Sort the buffers in weechat according to the given order. '''
  354. for i, buffer in enumerate(buffers):
  355. weechat.buffer_set(buffer[0], "number", str(i + 1))
  356. def split_args(args, expected, optional = 0):
  357. ''' Split an argument string in the desired number of arguments. '''
  358. split = args.split(' ', expected - 1)
  359. if (len(split) < expected):
  360. raise HumanReadableError('Expected at least {0} arguments, got {1}.'.format(expected, len(split)))
  361. return split[:-1] + pad(split[-1].split(' ', optional), optional + 1, '')
  362. def do_sort(verbose = False):
  363. start = perf_counter()
  364. hdata, buffers = get_buffers()
  365. buffers = merge_buffer_list(buffers)
  366. buffers = sort_buffers(hdata, buffers, config.rules, config.helpers, config.case_sensitive)
  367. apply_buffer_order(buffers)
  368. elapsed = perf_counter() - start
  369. if verbose:
  370. log("Finished sorting buffers in {0:.4f} seconds.".format(elapsed))
  371. else:
  372. debug("Finished sorting buffers in {0:.4f} seconds.".format(elapsed))
  373. def command_sort(buffer, command, args):
  374. ''' Sort the buffers and print a confirmation. '''
  375. do_sort(True)
  376. return weechat.WEECHAT_RC_OK
  377. def command_debug(buffer, command, args):
  378. hdata, buffers = get_buffers()
  379. buffers = merge_buffer_list(buffers)
  380. # Show evaluation results.
  381. log('Individual evaluation results:')
  382. start = perf_counter()
  383. key = buffer_sort_key(config.rules, config.helpers, config.case_sensitive)
  384. results = []
  385. for merged in buffers:
  386. for buffer in merged:
  387. fullname = weechat.hdata_string(hdata, buffer, 'full_name')
  388. results.append((fullname, key(buffer)))
  389. elapsed = perf_counter() - start
  390. for fullname, result in results:
  391. fullname = ensure_str(fullname)
  392. result = [ensure_str(x) for x in result]
  393. log('{0}: {1}'.format(fullname, result))
  394. log('Computing evaluation results took {0:.4f} seconds.'.format(elapsed))
  395. return weechat.WEECHAT_RC_OK
  396. def command_rule_list(buffer, command, args):
  397. ''' Show the list of sorting rules. '''
  398. output = 'Sorting rules:\n'
  399. for i, rule in enumerate(config.rules):
  400. output += ' {0}: {1}\n'.format(i, rule)
  401. if not len(config.rules):
  402. output += ' No sorting rules configured.\n'
  403. log(output )
  404. return weechat.WEECHAT_RC_OK
  405. def command_rule_add(buffer, command, args):
  406. ''' Add a rule to the rule list. '''
  407. config.rules.append(args)
  408. config.save_rules()
  409. command_rule_list(buffer, command, '')
  410. return weechat.WEECHAT_RC_OK
  411. def command_rule_insert(buffer, command, args):
  412. ''' Insert a rule at the desired position in the rule list. '''
  413. index, rule = split_args(args, 2)
  414. index = parse_int(index, 'index')
  415. config.rules.insert(index, rule)
  416. config.save_rules()
  417. command_rule_list(buffer, command, '')
  418. return weechat.WEECHAT_RC_OK
  419. def command_rule_update(buffer, command, args):
  420. ''' Update a rule in the rule list. '''
  421. index, rule = split_args(args, 2)
  422. index = parse_int(index, 'index')
  423. config.rules[index] = rule
  424. config.save_rules()
  425. command_rule_list(buffer, command, '')
  426. return weechat.WEECHAT_RC_OK
  427. def command_rule_delete(buffer, command, args):
  428. ''' Delete a rule from the rule list. '''
  429. index = args.strip()
  430. index = parse_int(index, 'index')
  431. config.rules.pop(index)
  432. config.save_rules()
  433. command_rule_list(buffer, command, '')
  434. return weechat.WEECHAT_RC_OK
  435. def command_rule_move(buffer, command, args):
  436. ''' Move a rule to a new position. '''
  437. index_a, index_b = split_args(args, 2)
  438. index_a = parse_int(index_a, 'index')
  439. index_b = parse_int(index_b, 'index')
  440. list_move(config.rules, index_a, index_b)
  441. config.save_rules()
  442. command_rule_list(buffer, command, '')
  443. return weechat.WEECHAT_RC_OK
  444. def command_rule_swap(buffer, command, args):
  445. ''' Swap two rules. '''
  446. index_a, index_b = split_args(args, 2)
  447. index_a = parse_int(index_a, 'index')
  448. index_b = parse_int(index_b, 'index')
  449. list_swap(config.rules, index_a, index_b)
  450. config.save_rules()
  451. command_rule_list(buffer, command, '')
  452. return weechat.WEECHAT_RC_OK
  453. def command_helper_list(buffer, command, args):
  454. ''' Show the list of helpers. '''
  455. output = 'Helper variables:\n'
  456. width = max(map(lambda x: len(x) if len(x) <= 30 else 0, config.helpers.keys()))
  457. for name, expression in sorted(config.helpers.items()):
  458. output += ' {0:>{width}}: {1}\n'.format(name, expression, width=width)
  459. if not len(config.helpers):
  460. output += ' No helper variables configured.'
  461. log(output)
  462. return weechat.WEECHAT_RC_OK
  463. def command_helper_set(buffer, command, args):
  464. ''' Add/update a helper to the helper list. '''
  465. name, expression = split_args(args, 2)
  466. config.helpers[name] = expression
  467. config.save_helpers()
  468. command_helper_list(buffer, command, '')
  469. return weechat.WEECHAT_RC_OK
  470. def command_helper_delete(buffer, command, args):
  471. ''' Delete a helper from the helper list. '''
  472. name = args.strip()
  473. del config.helpers[name]
  474. config.save_helpers()
  475. command_helper_list(buffer, command, '')
  476. return weechat.WEECHAT_RC_OK
  477. def command_helper_rename(buffer, command, args):
  478. ''' Rename a helper to a new position. '''
  479. old_name, new_name = split_args(args, 2)
  480. try:
  481. config.helpers[new_name] = config.helpers[old_name]
  482. del config.helpers[old_name]
  483. except KeyError:
  484. raise HumanReadableError('No such helper: {0}'.format(old_name))
  485. config.save_helpers()
  486. command_helper_list(buffer, command, '')
  487. return weechat.WEECHAT_RC_OK
  488. def command_helper_swap(buffer, command, args):
  489. ''' Swap two helpers. '''
  490. a, b = split_args(args, 2)
  491. try:
  492. config.helpers[b], config.helpers[a] = config.helpers[a], config.helpers[b]
  493. except KeyError as e:
  494. raise HumanReadableError('No such helper: {0}'.format(e.args[0]))
  495. config.helpers.swap(index_a, index_b)
  496. config.save_helpers()
  497. command_helper_list(buffer, command, '')
  498. return weechat.WEECHAT_RC_OK
  499. def call_command(buffer, command, args, subcommands):
  500. ''' Call a subcommand from a dictionary. '''
  501. subcommand, tail = pad(args.split(' ', 1), 2, '')
  502. subcommand = subcommand.strip()
  503. if (subcommand == ''):
  504. child = subcommands.get(' ')
  505. else:
  506. command = command + [subcommand]
  507. child = subcommands.get(subcommand)
  508. if isinstance(child, dict):
  509. return call_command(buffer, command, tail, child)
  510. elif callable(child):
  511. return child(buffer, command, tail)
  512. log('{0}: command not found'.format(' '.join(command)))
  513. return weechat.WEECHAT_RC_ERROR
  514. def on_signal(data, signal, signal_data):
  515. global signal_delay_timer
  516. global sort_queued
  517. # If the sort limit timeout is started, we're in the hold-off time after sorting, just queue a sort.
  518. if sort_limit_timer is not None:
  519. if sort_queued:
  520. debug('Signal {0} ignored, sort limit timeout is active and sort is already queued.'.format(signal))
  521. else:
  522. debug('Signal {0} received but sort limit timeout is active, sort is now queued.'.format(signal))
  523. sort_queued = True
  524. return weechat.WEECHAT_RC_OK
  525. # If the signal delay timeout is started, a signal was recently received, so ignore this signal.
  526. if signal_delay_timer is not None:
  527. debug('Signal {0} ignored, signal delay timeout active.'.format(signal))
  528. return weechat.WEECHAT_RC_OK
  529. # Otherwise, start the signal delay timeout.
  530. debug('Signal {0} received, starting signal delay timeout of {1} ms.'.format(signal, config.signal_delay))
  531. weechat.hook_timer(config.signal_delay, 0, 1, "on_signal_delay_timeout", "")
  532. return weechat.WEECHAT_RC_OK
  533. def on_signal_delay_timeout(pointer, remaining_calls):
  534. """ Called when the signal_delay_timer triggers. """
  535. global signal_delay_timer
  536. global sort_limit_timer
  537. global sort_queued
  538. signal_delay_timer = None
  539. # If the sort limit timeout was started, we're still in the no-sort period, so just queue a sort.
  540. if sort_limit_timer is not None:
  541. debug('Signal delay timeout expired, but sort limit timeout is active, sort is now queued.')
  542. sort_queued = True
  543. return weechat.WEECHAT_RC_OK
  544. # Time to sort!
  545. debug('Signal delay timeout expired, starting sort.')
  546. do_sort()
  547. # Start the sort limit timeout if not disabled.
  548. if config.sort_limit > 0:
  549. debug('Starting sort limit timeout of {0} ms.'.format(config.sort_limit))
  550. sort_limit_timer = weechat.hook_timer(config.sort_limit, 0, 1, "on_sort_limit_timeout", "")
  551. return weechat.WEECHAT_RC_OK
  552. def on_sort_limit_timeout(pointer, remainin_calls):
  553. """ Called when de sort_limit_timer triggers. """
  554. global sort_limit_timer
  555. global sort_queued
  556. # If no signal was received during the timeout, we're done.
  557. if not sort_queued:
  558. debug('Sort limit timeout expired without receiving a signal.')
  559. sort_limit_timer = None
  560. return weechat.WEECHAT_RC_OK
  561. # Otherwise it's time to sort.
  562. debug('Signal received during sort limit timeout, starting queued sort.')
  563. do_sort()
  564. sort_queued = False
  565. # Start the sort limit timeout again if not disabled.
  566. if config.sort_limit > 0:
  567. debug('Starting sort limit timeout of {0} ms.'.format(config.sort_limit))
  568. sort_limit_timer = weechat.hook_timer(config.sort_limit, 0, 1, "on_sort_limit_timeout", "")
  569. return weechat.WEECHAT_RC_OK
  570. def apply_config():
  571. # Unhook all signals and hook the new ones.
  572. for hook in hooks:
  573. weechat.unhook(hook)
  574. for signal in config.signals:
  575. hooks.append(weechat.hook_signal(signal, 'on_signal', ''))
  576. if config.sort_on_config:
  577. debug('Sorting because configuration changed.')
  578. do_sort()
  579. def on_config_changed(*args, **kwargs):
  580. ''' Called whenever the configuration changes. '''
  581. config.reload()
  582. apply_config()
  583. return weechat.WEECHAT_RC_OK
  584. def parse_arg(args):
  585. if not args: return '', None
  586. result = ''
  587. escaped = False
  588. for i, c in enumerate(args):
  589. if not escaped:
  590. if c == '\\':
  591. escaped = True
  592. continue
  593. elif c == ',':
  594. return result, args[i+1:]
  595. result += c
  596. escaped = False
  597. return result, None
  598. def parse_args(args, max = None):
  599. result = []
  600. i = 0
  601. while max is None or i < max:
  602. i += 1
  603. arg, args = parse_arg(args)
  604. if arg is None: break
  605. result.append(arg)
  606. if args is None: break
  607. return result, args
  608. def on_info_replace(pointer, name, arguments):
  609. arguments, rest = parse_args(arguments, 3)
  610. if rest or len(arguments) < 3:
  611. log('usage: ${{info:{0},old,new,text}}'.format(name))
  612. return ''
  613. old, new, text = arguments
  614. return text.replace(old, new)
  615. def on_info_order(pointer, name, arguments):
  616. arguments, rest = parse_args(arguments)
  617. if len(arguments) < 1:
  618. log('usage: ${{info:{0},value,first,second,third,...}}'.format(name))
  619. return ''
  620. value = arguments[0]
  621. keys = arguments[1:]
  622. if not keys: return '0'
  623. # Find the value in the keys (or '*' if we can't find it)
  624. result = list_find(keys, value)
  625. if result is None: result = list_find(keys, '*')
  626. if result is None: result = len(keys)
  627. # Pad result with leading zero to make sure string sorting works.
  628. width = int(math.log10(len(keys))) + 1
  629. return '{0:0{1}}'.format(result, width)
  630. def on_autosort_command(data, buffer, args):
  631. ''' Called when the autosort command is invoked. '''
  632. try:
  633. return call_command(buffer, ['/autosort'], args, {
  634. ' ': command_sort,
  635. 'sort': command_sort,
  636. 'debug': command_debug,
  637. 'rules': {
  638. ' ': command_rule_list,
  639. 'list': command_rule_list,
  640. 'add': command_rule_add,
  641. 'insert': command_rule_insert,
  642. 'update': command_rule_update,
  643. 'delete': command_rule_delete,
  644. 'move': command_rule_move,
  645. 'swap': command_rule_swap,
  646. },
  647. 'helpers': {
  648. ' ': command_helper_list,
  649. 'list': command_helper_list,
  650. 'set': command_helper_set,
  651. 'delete': command_helper_delete,
  652. 'rename': command_helper_rename,
  653. 'swap': command_helper_swap,
  654. },
  655. })
  656. except HumanReadableError as e:
  657. log(e)
  658. return weechat.WEECHAT_RC_ERROR
  659. def add_completions(completion, words):
  660. for word in words:
  661. weechat.hook_completion_list_add(completion, word, 0, weechat.WEECHAT_LIST_POS_END)
  662. def autosort_complete_rules(words, completion):
  663. if len(words) == 0:
  664. add_completions(completion, ['add', 'delete', 'insert', 'list', 'move', 'swap', 'update'])
  665. if len(words) == 1 and words[0] in ('delete', 'insert', 'move', 'swap', 'update'):
  666. add_completions(completion, map(str, range(len(config.rules))))
  667. if len(words) == 2 and words[0] in ('move', 'swap'):
  668. add_completions(completion, map(str, range(len(config.rules))))
  669. if len(words) == 2 and words[0] in ('update'):
  670. try:
  671. add_completions(completion, [config.rules[int(words[1])]])
  672. except KeyError: pass
  673. except ValueError: pass
  674. else:
  675. add_completions(completion, [''])
  676. return weechat.WEECHAT_RC_OK
  677. def autosort_complete_helpers(words, completion):
  678. if len(words) == 0:
  679. add_completions(completion, ['delete', 'list', 'rename', 'set', 'swap'])
  680. elif len(words) == 1 and words[0] in ('delete', 'rename', 'set', 'swap'):
  681. add_completions(completion, sorted(config.helpers.keys()))
  682. elif len(words) == 2 and words[0] == 'swap':
  683. add_completions(completion, sorted(config.helpers.keys()))
  684. elif len(words) == 2 and words[0] == 'rename':
  685. add_completions(completion, sorted(config.helpers.keys()))
  686. elif len(words) == 2 and words[0] == 'set':
  687. try:
  688. add_completions(completion, [config.helpers[words[1]]])
  689. except KeyError: pass
  690. return weechat.WEECHAT_RC_OK
  691. def on_autosort_complete(data, name, buffer, completion):
  692. cmdline = weechat.buffer_get_string(buffer, "input")
  693. cursor = weechat.buffer_get_integer(buffer, "input_pos")
  694. prefix = cmdline[:cursor]
  695. words = prefix.split()[1:]
  696. # If the current word isn't finished yet,
  697. # ignore it for coming up with completion suggestions.
  698. if prefix[-1] != ' ': words = words[:-1]
  699. if len(words) == 0:
  700. add_completions(completion, ['debug', 'helpers', 'rules', 'sort'])
  701. elif words[0] == 'rules':
  702. return autosort_complete_rules(words[1:], completion)
  703. elif words[0] == 'helpers':
  704. return autosort_complete_helpers(words[1:], completion)
  705. return weechat.WEECHAT_RC_OK
  706. command_description = r'''{*white}# General commands{reset}
  707. {*white}/autosort {brown}sort{reset}
  708. Manually trigger the buffer sorting.
  709. {*white}/autosort {brown}debug{reset}
  710. Show the evaluation results of the sort rules for each buffer.
  711. {*white}# Sorting rule commands{reset}
  712. {*white}/autosort{brown} rules list{reset}
  713. Print the list of sort rules.
  714. {*white}/autosort {brown}rules add {cyan}<expression>{reset}
  715. Add a new rule at the end of the list.
  716. {*white}/autosort {brown}rules insert {cyan}<index> <expression>{reset}
  717. Insert a new rule at the given index in the list.
  718. {*white}/autosort {brown}rules update {cyan}<index> <expression>{reset}
  719. Update a rule in the list with a new expression.
  720. {*white}/autosort {brown}rules delete {cyan}<index>
  721. Delete a rule from the list.
  722. {*white}/autosort {brown}rules move {cyan}<index_from> <index_to>{reset}
  723. Move a rule from one position in the list to another.
  724. {*white}/autosort {brown}rules swap {cyan}<index_a> <index_b>{reset}
  725. Swap two rules in the list
  726. {*white}# Helper variable commands{reset}
  727. {*white}/autosort {brown}helpers list
  728. Print the list of helper variables.
  729. {*white}/autosort {brown}helpers set {cyan}<name> <expression>
  730. Add or update a helper variable with the given name.
  731. {*white}/autosort {brown}helpers delete {cyan}<name>
  732. Delete a helper variable.
  733. {*white}/autosort {brown}helpers rename {cyan}<old_name> <new_name>
  734. Rename a helper variable.
  735. {*white}/autosort {brown}helpers swap {cyan}<name_a> <name_b>
  736. Swap the expressions of two helper variables in the list.
  737. {*white}# Description
  738. Autosort is a weechat script to automatically keep your buffers sorted. The sort
  739. order can be customized by defining your own sort rules, but the default should
  740. be sane enough for most people. It can also group IRC channel/private buffers
  741. under their server buffer if you like.
  742. {*white}# Sort rules{reset}
  743. Autosort evaluates a list of eval expressions (see {*default}/help eval{reset}) and sorts the
  744. buffers based on evaluated result. Earlier rules will be considered first. Only
  745. if earlier rules produced identical results is the result of the next rule
  746. considered for sorting purposes.
  747. You can debug your sort rules with the `{*default}/autosort debug{reset}` command, which will
  748. print the evaluation results of each rule for each buffer.
  749. {*brown}NOTE:{reset} The sort rules for version 3 are not compatible with version 2 or vice
  750. versa. You will have to manually port your old rules to version 3 if you have any.
  751. {*white}# Helper variables{reset}
  752. You may define helper variables for the main sort rules to keep your rules
  753. readable. They can be used in the main sort rules as variables. For example,
  754. a helper variable named `{cyan}foo{reset}` can be accessed in a main rule with the
  755. string `{cyan}${{foo}}{reset}`.
  756. {*white}# Replacing substrings{reset}
  757. There is no default method for replacing text inside eval expressions. However,
  758. autosort adds a `replace` info hook that can be used inside eval expressions:
  759. {cyan}${{info:autosort_replace,from,to,text}}{reset}
  760. For example, to strip all hashes from a buffer name, you could write:
  761. {cyan}${{info:autosort_replace,#,,${{buffer.name}}}}{reset}
  762. You can escape commas and backslashes inside the arguments by prefixing them with
  763. a backslash.
  764. {*white}# Automatic or manual sorting{reset}
  765. By default, autosort will automatically sort your buffer list whenever a buffer
  766. is opened, merged, unmerged or renamed. This should keep your buffers sorted in
  767. almost all situations. However, you may wish to change the list of signals that
  768. cause your buffer list to be sorted. Simply edit the `{cyan}autosort.sorting.signals{reset}`
  769. option to add or remove any signal you like.
  770. If you remove all signals you can still sort your buffers manually with the
  771. `{*default}/autosort sort{reset}` command. To prevent all automatic sorting, the option
  772. `{cyan}autosort.sorting.sort_on_config_change{reset}` should also be disabled.
  773. {*white}# Recommended settings
  774. For the best visual effect, consider setting the following options:
  775. {*white}/set {cyan}irc.look.server_buffer{reset} {brown}independent{reset}
  776. {*white}/set {cyan}buffers.look.indenting{reset} {brown}on{reset}
  777. The first setting allows server buffers to be sorted independently, which is
  778. needed to create a hierarchical tree view of the server and channel buffers.
  779. The second one indents channel and private buffers in the buffer list of the
  780. `{*default}buffers.pl{reset}` script.
  781. If you are using the {*default}buflist{reset} plugin you can (ab)use Unicode to draw a tree
  782. structure with the following setting (modify to suit your need):
  783. {*white}/set {cyan}buflist.format.indent {brown}"${{color:237}}${{if:${{buffer.next_buffer.local_variables.type}}=~^(channel|private)$?├─:└─}}"{reset}
  784. '''
  785. command_completion = '%(plugin_autosort) %(plugin_autosort) %(plugin_autosort) %(plugin_autosort) %(plugin_autosort)'
  786. info_replace_description = 'Replace all occurences of `from` with `to` in the string `text`.'
  787. info_replace_arguments = 'from,to,text'
  788. info_order_description = (
  789. 'Get a zero padded index of a value in a list of possible values.'
  790. 'If the value is not found, the index for `*` is returned.'
  791. 'If there is no `*` in the list, the highest index + 1 is returned.'
  792. )
  793. info_order_arguments = 'value,first,second,third,...'
  794. if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
  795. config = Config('autosort')
  796. colors = {
  797. 'default': weechat.color('default'),
  798. 'reset': weechat.color('reset'),
  799. 'black': weechat.color('black'),
  800. 'red': weechat.color('red'),
  801. 'green': weechat.color('green'),
  802. 'brown': weechat.color('brown'),
  803. 'yellow': weechat.color('yellow'),
  804. 'blue': weechat.color('blue'),
  805. 'magenta': weechat.color('magenta'),
  806. 'cyan': weechat.color('cyan'),
  807. 'white': weechat.color('white'),
  808. '*default': weechat.color('*default'),
  809. '*black': weechat.color('*black'),
  810. '*red': weechat.color('*red'),
  811. '*green': weechat.color('*green'),
  812. '*brown': weechat.color('*brown'),
  813. '*yellow': weechat.color('*yellow'),
  814. '*blue': weechat.color('*blue'),
  815. '*magenta': weechat.color('*magenta'),
  816. '*cyan': weechat.color('*cyan'),
  817. '*white': weechat.color('*white'),
  818. }
  819. weechat.hook_config('autosort.*', 'on_config_changed', '')
  820. weechat.hook_completion('plugin_autosort', '', 'on_autosort_complete', '')
  821. weechat.hook_command('autosort', command_description.format(**colors), '', '', command_completion, 'on_autosort_command', '')
  822. weechat.hook_info('autosort_replace', info_replace_description, info_replace_arguments, 'on_info_replace', '')
  823. weechat.hook_info('autosort_order', info_order_description, info_order_arguments, 'on_info_order', '')
  824. apply_config()