Another copy of my dotfiles. Because I don't completely trust GitHub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1075 lines
37 KiB

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