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.

1884 lines
68 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2014 Germain Z. <germanosz@gmail.com>
  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. # Add vi/vim-like modes to WeeChat.
  20. #
  21. import csv
  22. import json
  23. import os
  24. import re
  25. import subprocess
  26. try:
  27. from StringIO import StringIO
  28. except ImportError:
  29. from io import StringIO
  30. import time
  31. import weechat
  32. # Script info.
  33. # ============
  34. SCRIPT_NAME = "vimode"
  35. SCRIPT_AUTHOR = "GermainZ <germanosz@gmail.com>"
  36. SCRIPT_VERSION = "0.8.1"
  37. SCRIPT_LICENSE = "GPL3"
  38. SCRIPT_DESC = ("Add vi/vim-like modes and keybindings to WeeChat.")
  39. # Global variables.
  40. # =================
  41. # General.
  42. # --------
  43. # Halp! Halp! Halp!
  44. GITHUB_BASE = "https://github.com/GermainZ/weechat-vimode/blob/master/"
  45. README_URL = GITHUB_BASE + "README.md"
  46. FAQ_KEYBINDINGS = GITHUB_BASE + "FAQ.md#problematic-key-bindings"
  47. FAQ_ESC = GITHUB_BASE + "FAQ.md#esc-key-not-being-detected-instantly"
  48. # Holds the text of the tab-completions for the command-line mode.
  49. cmd_compl_text = ""
  50. # Holds the original text of the command-line mode, used for completion.
  51. cmd_text_orig = None
  52. # Index of current suggestion, used for completion.
  53. cmd_compl_pos = 0
  54. # Used for command-line mode history.
  55. cmd_history = []
  56. cmd_history_index = 0
  57. # Used to store the content of the input line when going into COMMAND mode.
  58. input_line_backup = {}
  59. # Mode we're in. One of INSERT, NORMAL, REPLACE, COMMAND or SEARCH.
  60. # SEARCH is only used if search_vim is enabled.
  61. mode = "INSERT"
  62. # Holds normal commands (e.g. "dd").
  63. vi_buffer = ""
  64. # See `cb_key_combo_default()`.
  65. esc_pressed = 0
  66. # See `cb_key_pressed()`.
  67. last_signal_time = 0
  68. # See `start_catching_keys()` for more info.
  69. catching_keys_data = {'amount': 0}
  70. # Used for ; and , to store the last f/F/t/T motion.
  71. last_search_motion = {'motion': None, 'data': None}
  72. # Used for undo history.
  73. undo_history = {}
  74. undo_history_index = {}
  75. # Holds mode colors (loaded from vimode_settings).
  76. mode_colors = {}
  77. # Script options.
  78. vimode_settings = {
  79. 'no_warn': ("off", ("don't warn about problematic keybindings and "
  80. "tmux/screen")),
  81. 'copy_clipboard_cmd': ("xclip -selection c",
  82. ("command used to copy to clipboard; must read "
  83. "input from stdin")),
  84. 'paste_clipboard_cmd': ("xclip -selection c -o",
  85. ("command used to paste clipboard; must output "
  86. "content to stdout")),
  87. 'imap_esc': ("", ("use alternate mapping to enter Normal mode while in "
  88. "Insert mode; having it set to 'jk' is similar to "
  89. "`:imap jk <Esc>` in vim")),
  90. 'imap_esc_timeout': ("1000", ("time in ms to wait for the imap_esc "
  91. "sequence to complete")),
  92. 'search_vim': ("off", ("allow n/N usage after searching (requires an extra"
  93. " <Enter> to return to normal mode)")),
  94. 'user_mappings': ("", ("see the `:nmap` command in the README for more "
  95. "info; please do not modify this field manually "
  96. "unless you know what you're doing")),
  97. 'mode_indicator_prefix': ("", "prefix for the bar item mode_indicator"),
  98. 'mode_indicator_suffix': ("", "suffix for the bar item mode_indicator"),
  99. 'mode_indicator_normal_color': ("white",
  100. "color for mode indicator in Normal mode"),
  101. 'mode_indicator_normal_color_bg': ("gray",
  102. ("background color for mode indicator "
  103. "in Normal mode")),
  104. 'mode_indicator_insert_color': ("white",
  105. "color for mode indicator in Insert mode"),
  106. 'mode_indicator_insert_color_bg': ("blue",
  107. ("background color for mode indicator "
  108. "in Insert mode")),
  109. 'mode_indicator_replace_color': ("white",
  110. "color for mode indicator in Replace mode"),
  111. 'mode_indicator_replace_color_bg': ("red",
  112. ("background color for mode indicator "
  113. "in Replace mode")),
  114. 'mode_indicator_cmd_color': ("white",
  115. "color for mode indicator in Command mode"),
  116. 'mode_indicator_cmd_color_bg': ("cyan",
  117. ("background color for mode indicator in "
  118. "Command mode")),
  119. 'mode_indicator_search_color': ("white",
  120. "color for mode indicator in Search mode"),
  121. 'mode_indicator_search_color_bg': ("magenta",
  122. ("background color for mode indicator "
  123. "in Search mode")),
  124. 'line_number_prefix': ("", "prefix for line numbers"),
  125. 'line_number_suffix': (" ", "suffix for line numbers")
  126. }
  127. # Regex patterns.
  128. # ---------------
  129. WHITESPACE = re.compile(r"\s")
  130. IS_KEYWORD = re.compile(r"[a-zA-Z0-9_@À-ÿ]")
  131. REGEX_MOTION_LOWERCASE_W = re.compile(r"\b\S|(?<=\s)\S")
  132. REGEX_MOTION_UPPERCASE_W = re.compile(r"(?<=\s)\S")
  133. REGEX_MOTION_UPPERCASE_E = re.compile(r"\S(?!\S)")
  134. REGEX_MOTION_UPPERCASE_B = REGEX_MOTION_UPPERCASE_E
  135. REGEX_MOTION_G_UPPERCASE_E = REGEX_MOTION_UPPERCASE_W
  136. REGEX_MOTION_CARRET = re.compile(r"\S")
  137. REGEX_INT = r"[0-9]"
  138. REGEX_MAP_KEYS_1 = {
  139. re.compile("<([^>]*-)Left>", re.IGNORECASE): '<\\1\x01[[D>',
  140. re.compile("<([^>]*-)Right>", re.IGNORECASE): '<\\1\x01[[C>',
  141. re.compile("<([^>]*-)Up>", re.IGNORECASE): '<\\1\x01[[A>',
  142. re.compile("<([^>]*-)Down>", re.IGNORECASE): '<\\1\x01[[B>',
  143. re.compile("<Left>", re.IGNORECASE): '\x01[[D',
  144. re.compile("<Right>", re.IGNORECASE): '\x01[[C',
  145. re.compile("<Up>", re.IGNORECASE): '\x01[[A',
  146. re.compile("<Down>", re.IGNORECASE): '\x01[[B'
  147. }
  148. REGEX_MAP_KEYS_2 = {
  149. re.compile(r"<C-([^>]*)>", re.IGNORECASE): '\x01\\1',
  150. re.compile(r"<M-([^>]*)>", re.IGNORECASE): '\x01[\\1'
  151. }
  152. # Regex used to detect problematic keybindings.
  153. # For example: meta-wmeta-s is bound by default to ``/window swap``.
  154. # If the user pressed Esc-w, WeeChat will detect it as meta-w and will not
  155. # send any signal to `cb_key_combo_default()` just yet, since it's the
  156. # beginning of a known key combo.
  157. # Instead, `cb_key_combo_default()` will receive the Esc-ws signal, which
  158. # becomes "ws" after removing the Esc part, and won't know how to handle it.
  159. REGEX_PROBLEMATIC_KEYBINDINGS = re.compile(r"meta-\w(meta|ctrl)")
  160. # Vi commands.
  161. # ------------
  162. def cmd_nmap(args):
  163. """Add a user-defined key mapping.
  164. Some (but not all) vim-like key codes are supported to simplify things for
  165. the user: <Up>, <Down>, <Left>, <Right>, <C-...> and <M-...>.
  166. See Also:
  167. `cmd_unmap()`.
  168. """
  169. args = args.strip()
  170. if not args:
  171. mappings = vimode_settings['user_mappings']
  172. if mappings:
  173. weechat.prnt("", "User-defined key mappings:")
  174. for key, mapping in mappings.items():
  175. weechat.prnt("", "{} -> {}".format(key, mapping))
  176. else:
  177. weechat.prnt("", "nmap: no mapping found.")
  178. elif not " " in args:
  179. weechat.prnt("", "nmap syntax -> :nmap {lhs} {rhs}")
  180. else:
  181. key, mapping = args.split(" ", 1)
  182. # First pass of replacements. We perform two passes as a simple way to
  183. # avoid incorrect replacements due to dictionaries not being
  184. # insertion-ordered prior to Python 3.7.
  185. for regex, repl in REGEX_MAP_KEYS_1.items():
  186. key = regex.sub(repl, key)
  187. mapping = regex.sub(repl, mapping)
  188. # Second pass of replacements.
  189. for regex, repl in REGEX_MAP_KEYS_2.items():
  190. key = regex.sub(repl, key)
  191. mapping = regex.sub(repl, mapping)
  192. mappings = vimode_settings['user_mappings']
  193. mappings[key] = mapping
  194. weechat.config_set_plugin('user_mappings', json.dumps(mappings))
  195. vimode_settings['user_mappings'] = mappings
  196. def cmd_nunmap(args):
  197. """Remove a user-defined key mapping.
  198. See Also:
  199. `cmd_map()`.
  200. """
  201. args = args.strip()
  202. if not args:
  203. weechat.prnt("", "nunmap syntax -> :unmap {lhs}")
  204. else:
  205. key = args
  206. for regex, repl in REGEX_MAP_KEYS_1.items():
  207. key = regex.sub(repl, key)
  208. for regex, repl in REGEX_MAP_KEYS_2.items():
  209. key = regex.sub(repl, key)
  210. mappings = vimode_settings['user_mappings']
  211. if key in mappings:
  212. del mappings[key]
  213. weechat.config_set_plugin('user_mappings', json.dumps(mappings))
  214. vimode_settings['user_mappings'] = mappings
  215. else:
  216. weechat.prnt("", "nunmap: No such mapping")
  217. # See Also: `cb_exec_cmd()`.
  218. VI_COMMAND_GROUPS = {('h', 'help'): "/help",
  219. ('qa', 'qall', 'quita', 'quitall'): "/exit",
  220. ('q', 'quit'): "/close",
  221. ('w', 'write'): "/save",
  222. ('bN', 'bNext', 'bp', 'bprevious'): "/buffer -1",
  223. ('bn', 'bnext'): "/buffer +1",
  224. ('bd', 'bdel', 'bdelete'): "/close",
  225. ('b#',): "/input jump_last_buffer_displayed",
  226. ('b', 'bu', 'buf', 'buffer'): "/buffer",
  227. ('sp', 'split'): "/window splith",
  228. ('vs', 'vsplit'): "/window splitv",
  229. ('nm', 'nmap'): cmd_nmap,
  230. ('nun', 'nunmap'): cmd_nunmap}
  231. VI_COMMANDS = dict()
  232. for T, v in VI_COMMAND_GROUPS.items():
  233. VI_COMMANDS.update(dict.fromkeys(T, v))
  234. # Vi operators.
  235. # -------------
  236. # Each operator must have a corresponding function, called "operator_X" where
  237. # X is the operator. For example: `operator_c()`.
  238. VI_OPERATORS = ["c", "d", "y"]
  239. # Vi motions.
  240. # -----------
  241. # Vi motions. Each motion must have a corresponding function, called
  242. # "motion_X" where X is the motion (e.g. `motion_w()`).
  243. # See Also: `SPECIAL_CHARS`.
  244. VI_MOTIONS = ["w", "e", "b", "^", "$", "h", "l", "W", "E", "B", "f", "F", "t",
  245. "T", "ge", "gE", "0"]
  246. # Special characters for motions. The corresponding function's name is
  247. # converted before calling. For example, "^" will call `motion_carret` instead
  248. # of `motion_^` (which isn't allowed because of illegal characters).
  249. SPECIAL_CHARS = {'^': "carret",
  250. '$': "dollar"}
  251. # Methods for vi operators, motions and key bindings.
  252. # ===================================================
  253. # Documented base examples:
  254. # -------------------------
  255. def operator_base(buf, input_line, pos1, pos2, overwrite):
  256. """Operator method example.
  257. Args:
  258. buf (str): pointer to the current WeeChat buffer.
  259. input_line (str): the content of the input line.
  260. pos1 (int): the starting position of the motion.
  261. pos2 (int): the ending position of the motion.
  262. overwrite (bool, optional): whether the character at the cursor's new
  263. position should be overwritten or not (for inclusive motions).
  264. Defaults to False.
  265. Notes:
  266. Should be called "operator_X", where X is the operator, and defined in
  267. `VI_OPERATORS`.
  268. Must perform actions (e.g. modifying the input line) on its own,
  269. using the WeeChat API.
  270. See Also:
  271. For additional examples, see `operator_d()` and
  272. `operator_y()`.
  273. """
  274. # Get start and end positions.
  275. start = min(pos1, pos2)
  276. end = max(pos1, pos2)
  277. # Print the text the operator should go over.
  278. weechat.prnt("", "Selection: %s" % input_line[start:end])
  279. def motion_base(input_line, cur, count):
  280. """Motion method example.
  281. Args:
  282. input_line (str): the content of the input line.
  283. cur (int): the position of the cursor.
  284. count (int): the amount of times to multiply or iterate the action.
  285. Returns:
  286. A tuple containing three values:
  287. int: the new position of the cursor.
  288. bool: True if the motion is inclusive, False otherwise.
  289. bool: True if the motion is catching, False otherwise.
  290. See `start_catching_keys()` for more info on catching motions.
  291. Notes:
  292. Should be called "motion_X", where X is the motion, and defined in
  293. `VI_MOTIONS`.
  294. Must not modify the input line directly.
  295. See Also:
  296. For additional examples, see `motion_w()` (normal motion) and
  297. `motion_f()` (catching motion).
  298. """
  299. # Find (relative to cur) position of next number.
  300. pos = get_pos(input_line, REGEX_INT, cur, True, count)
  301. # Return the new (absolute) cursor position.
  302. # This motion is exclusive, so overwrite is False.
  303. return cur + pos, False
  304. def key_base(buf, input_line, cur, count):
  305. """Key method example.
  306. Args:
  307. buf (str): pointer to the current WeeChat buffer.
  308. input_line (str): the content of the input line.
  309. cur (int): the position of the cursor.
  310. count (int): the amount of times to multiply or iterate the action.
  311. Notes:
  312. Should be called `key_X`, where X represents the key(s), and defined
  313. in `VI_KEYS`.
  314. Must perform actions on its own (using the WeeChat API).
  315. See Also:
  316. For additional examples, see `key_a()` (normal key) and
  317. `key_r()` (catching key).
  318. """
  319. # Key was pressed. Go to Insert mode (similar to "i").
  320. set_mode("INSERT")
  321. # Operators:
  322. # ----------
  323. def operator_d(buf, input_line, pos1, pos2, overwrite=False):
  324. """Delete text from `pos1` to `pos2` from the input line.
  325. If `overwrite` is set to True, the character at the cursor's new position
  326. is removed as well (the motion is inclusive).
  327. See Also:
  328. `operator_base()`.
  329. """
  330. start = min(pos1, pos2)
  331. end = max(pos1, pos2)
  332. if overwrite:
  333. end += 1
  334. input_line = list(input_line)
  335. del input_line[start:end]
  336. input_line = "".join(input_line)
  337. weechat.buffer_set(buf, "input", input_line)
  338. set_cur(buf, input_line, pos1)
  339. def operator_c(buf, input_line, pos1, pos2, overwrite=False):
  340. """Delete text from `pos1` to `pos2` from the input and enter Insert mode.
  341. If `overwrite` is set to True, the character at the cursor's new position
  342. is removed as well (the motion is inclusive.)
  343. See Also:
  344. `operator_base()`.
  345. """
  346. operator_d(buf, input_line, pos1, pos2, overwrite)
  347. set_mode("INSERT")
  348. def operator_y(buf, input_line, pos1, pos2, _):
  349. """Yank text from `pos1` to `pos2` from the input line.
  350. See Also:
  351. `operator_base()`.
  352. """
  353. start = min(pos1, pos2)
  354. end = max(pos1, pos2)
  355. cmd = vimode_settings['copy_clipboard_cmd']
  356. proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
  357. proc.communicate(input=input_line[start:end].encode())
  358. # Motions:
  359. # --------
  360. def motion_0(input_line, cur, count):
  361. """Go to the first character of the line.
  362. See Also;
  363. `motion_base()`.
  364. """
  365. return 0, False, False
  366. def motion_w(input_line, cur, count):
  367. """Go `count` words forward and return position.
  368. See Also:
  369. `motion_base()`.
  370. """
  371. pos = get_pos(input_line, REGEX_MOTION_LOWERCASE_W, cur, True, count)
  372. if pos == -1:
  373. return len(input_line), False, False
  374. return cur + pos, False, False
  375. def motion_W(input_line, cur, count):
  376. """Go `count` WORDS forward and return position.
  377. See Also:
  378. `motion_base()`.
  379. """
  380. pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_W, cur, True, count)
  381. if pos == -1:
  382. return len(input_line), False, False
  383. return cur + pos, False, False
  384. def motion_e(input_line, cur, count):
  385. """Go to the end of `count` words and return position.
  386. See Also:
  387. `motion_base()`.
  388. """
  389. for _ in range(max(1, count)):
  390. found = False
  391. pos = cur
  392. for pos in range(cur + 1, len(input_line) - 1):
  393. # Whitespace, keep going.
  394. if WHITESPACE.match(input_line[pos]):
  395. pass
  396. # End of sequence made from 'iskeyword' characters only,
  397. # or end of sequence made from non 'iskeyword' characters only.
  398. elif ((IS_KEYWORD.match(input_line[pos]) and
  399. (not IS_KEYWORD.match(input_line[pos + 1]) or
  400. WHITESPACE.match(input_line[pos + 1]))) or
  401. (not IS_KEYWORD.match(input_line[pos]) and
  402. (IS_KEYWORD.match(input_line[pos + 1]) or
  403. WHITESPACE.match(input_line[pos + 1])))):
  404. found = True
  405. cur = pos
  406. break
  407. # We're at the character before the last and we still found nothing.
  408. # Go to the last character.
  409. if not found:
  410. cur = pos + 1
  411. return cur, True, False
  412. def motion_E(input_line, cur, count):
  413. """Go to the end of `count` WORDS and return cusor position.
  414. See Also:
  415. `motion_base()`.
  416. """
  417. pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_E, cur, True, count)
  418. if pos == -1:
  419. return len(input_line), False, False
  420. return cur + pos, True, False
  421. def motion_b(input_line, cur, count):
  422. """Go `count` words backwards and return position.
  423. See Also:
  424. `motion_base()`.
  425. """
  426. # "b" is just "e" on inverted data (e.g. "olleH" instead of "Hello").
  427. pos_inv = motion_e(input_line[::-1], len(input_line) - cur - 1, count)[0]
  428. pos = len(input_line) - pos_inv - 1
  429. return pos, True, False
  430. def motion_B(input_line, cur, count):
  431. """Go `count` WORDS backwards and return position.
  432. See Also:
  433. `motion_base()`.
  434. """
  435. new_cur = len(input_line) - cur
  436. pos = get_pos(input_line[::-1], REGEX_MOTION_UPPERCASE_B, new_cur,
  437. count=count)
  438. if pos == -1:
  439. return 0, False, False
  440. pos = len(input_line) - (pos + new_cur + 1)
  441. return pos, True, False
  442. def motion_ge(input_line, cur, count):
  443. """Go to end of `count` words backwards and return position.
  444. See Also:
  445. `motion_base()`.
  446. """
  447. # "ge is just "w" on inverted data (e.g. "olleH" instead of "Hello").
  448. pos_inv = motion_w(input_line[::-1], len(input_line) - cur - 1, count)[0]
  449. pos = len(input_line) - pos_inv - 1
  450. return pos, True, False
  451. def motion_gE(input_line, cur, count):
  452. """Go to end of `count` WORDS backwards and return position.
  453. See Also:
  454. `motion_base()`.
  455. """
  456. new_cur = len(input_line) - cur - 1
  457. pos = get_pos(input_line[::-1], REGEX_MOTION_G_UPPERCASE_E, new_cur,
  458. True, count)
  459. if pos == -1:
  460. return 0, False, False
  461. pos = len(input_line) - (pos + new_cur + 1)
  462. return pos, True, False
  463. def motion_h(input_line, cur, count):
  464. """Go `count` characters to the left and return position.
  465. See Also:
  466. `motion_base()`.
  467. """
  468. return max(0, cur - max(count, 1)), False, False
  469. def motion_l(input_line, cur, count):
  470. """Go `count` characters to the right and return position.
  471. See Also:
  472. `motion_base()`.
  473. """
  474. return cur + max(count, 1), False, False
  475. def motion_carret(input_line, cur, count):
  476. """Go to first non-blank character of line and return position.
  477. See Also:
  478. `motion_base()`.
  479. """
  480. pos = get_pos(input_line, REGEX_MOTION_CARRET, 0)
  481. return pos, False, False
  482. def motion_dollar(input_line, cur, count):
  483. """Go to end of line and return position.
  484. See Also:
  485. `motion_base()`.
  486. """
  487. pos = len(input_line)
  488. return pos, False, False
  489. def motion_f(input_line, cur, count):
  490. """Go to `count`'th occurence of character and return position.
  491. See Also:
  492. `motion_base()`.
  493. """
  494. return start_catching_keys(1, "cb_motion_f", input_line, cur, count)
  495. def cb_motion_f(update_last=True):
  496. """Callback for `motion_f()`.
  497. Args:
  498. update_last (bool, optional): should `last_search_motion` be updated?
  499. Set to False when calling from `key_semicolon()` or `key_comma()`
  500. so that the last search motion isn't overwritten.
  501. Defaults to True.
  502. See Also:
  503. `start_catching_keys()`.
  504. """
  505. global last_search_motion
  506. pattern = catching_keys_data['keys']
  507. pos = get_pos(catching_keys_data['input_line'], re.escape(pattern),
  508. catching_keys_data['cur'], True,
  509. catching_keys_data['count'])
  510. catching_keys_data['new_cur'] = max(0, pos) + catching_keys_data['cur']
  511. if update_last:
  512. last_search_motion = {'motion': "f", 'data': pattern}
  513. cb_key_combo_default(None, None, "")
  514. def motion_F(input_line, cur, count):
  515. """Go to `count`'th occurence of char to the right and return position.
  516. See Also:
  517. `motion_base()`.
  518. """
  519. return start_catching_keys(1, "cb_motion_F", input_line, cur, count)
  520. def cb_motion_F(update_last=True):
  521. """Callback for `motion_F()`.
  522. Args:
  523. update_last (bool, optional): should `last_search_motion` be updated?
  524. Set to False when calling from `key_semicolon()` or `key_comma()`
  525. so that the last search motion isn't overwritten.
  526. Defaults to True.
  527. See Also:
  528. `start_catching_keys()`.
  529. """
  530. global last_search_motion
  531. pattern = catching_keys_data['keys']
  532. cur = len(catching_keys_data['input_line']) - catching_keys_data['cur']
  533. pos = get_pos(catching_keys_data['input_line'][::-1],
  534. re.escape(pattern),
  535. cur,
  536. False,
  537. catching_keys_data['count'])
  538. catching_keys_data['new_cur'] = catching_keys_data['cur'] - max(0, pos + 1)
  539. if update_last:
  540. last_search_motion = {'motion': "F", 'data': pattern}
  541. cb_key_combo_default(None, None, "")
  542. def motion_t(input_line, cur, count):
  543. """Go to `count`'th occurence of char and return position.
  544. The position returned is the position of the character to the left of char.
  545. See Also:
  546. `motion_base()`.
  547. """
  548. return start_catching_keys(1, "cb_motion_t", input_line, cur, count)
  549. def cb_motion_t(update_last=True):
  550. """Callback for `motion_t()`.
  551. Args:
  552. update_last (bool, optional): should `last_search_motion` be updated?
  553. Set to False when calling from `key_semicolon()` or `key_comma()`
  554. so that the last search motion isn't overwritten.
  555. Defaults to True.
  556. See Also:
  557. `start_catching_keys()`.
  558. """
  559. global last_search_motion
  560. pattern = catching_keys_data['keys']
  561. pos = get_pos(catching_keys_data['input_line'], re.escape(pattern),
  562. catching_keys_data['cur'] + 1,
  563. True, catching_keys_data['count'])
  564. pos += 1
  565. if pos > 0:
  566. catching_keys_data['new_cur'] = pos + catching_keys_data['cur'] - 1
  567. else:
  568. catching_keys_data['new_cur'] = catching_keys_data['cur']
  569. if update_last:
  570. last_search_motion = {'motion': "t", 'data': pattern}
  571. cb_key_combo_default(None, None, "")
  572. def motion_T(input_line, cur, count):
  573. """Go to `count`'th occurence of char to the left and return position.
  574. The position returned is the position of the character to the right of
  575. char.
  576. See Also:
  577. `motion_base()`.
  578. """
  579. return start_catching_keys(1, "cb_motion_T", input_line, cur, count)
  580. def cb_motion_T(update_last=True):
  581. """Callback for `motion_T()`.
  582. Args:
  583. update_last (bool, optional): should `last_search_motion` be updated?
  584. Set to False when calling from `key_semicolon()` or `key_comma()`
  585. so that the last search motion isn't overwritten.
  586. Defaults to True.
  587. See Also:
  588. `start_catching_keys()`.
  589. """
  590. global last_search_motion
  591. pattern = catching_keys_data['keys']
  592. pos = get_pos(catching_keys_data['input_line'][::-1], re.escape(pattern),
  593. (len(catching_keys_data['input_line']) -
  594. (catching_keys_data['cur'] + 1)) + 1,
  595. True, catching_keys_data['count'])
  596. pos += 1
  597. if pos > 0:
  598. catching_keys_data['new_cur'] = catching_keys_data['cur'] - pos + 1
  599. else:
  600. catching_keys_data['new_cur'] = catching_keys_data['cur']
  601. if update_last:
  602. last_search_motion = {'motion': "T", 'data': pattern}
  603. cb_key_combo_default(None, None, "")
  604. # Keys:
  605. # -----
  606. def key_cc(buf, input_line, cur, count):
  607. """Delete line and start Insert mode.
  608. See Also:
  609. `key_base()`.
  610. """
  611. weechat.command("", "/input delete_line")
  612. set_mode("INSERT")
  613. def key_C(buf, input_line, cur, count):
  614. """Delete from cursor to end of line and start Insert mode.
  615. See Also:
  616. `key_base()`.
  617. """
  618. weechat.command("", "/input delete_end_of_line")
  619. set_mode("INSERT")
  620. def key_yy(buf, input_line, cur, count):
  621. """Yank line.
  622. See Also:
  623. `key_base()`.
  624. """
  625. cmd = vimode_settings['copy_clipboard_cmd']
  626. proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
  627. proc.communicate(input=input_line.encode())
  628. def key_p(buf, input_line, cur, count):
  629. """Paste text.
  630. See Also:
  631. `key_base()`.
  632. """
  633. cmd = vimode_settings['paste_clipboard_cmd']
  634. weechat.hook_process(cmd, 10 * 1000, "cb_key_p", weechat.current_buffer())
  635. def cb_key_p(data, command, return_code, output, err):
  636. """Callback for fetching clipboard text and pasting it."""
  637. buf = ""
  638. this_buffer = data
  639. if output != "":
  640. buf += output.strip()
  641. if return_code == 0:
  642. my_input = weechat.buffer_get_string(this_buffer, "input")
  643. pos = weechat.buffer_get_integer(this_buffer, "input_pos")
  644. my_input = my_input[:pos] + buf + my_input[pos:]
  645. pos += len(buf)
  646. weechat.buffer_set(this_buffer, "input", my_input)
  647. weechat.buffer_set(this_buffer, "input_pos", str(pos))
  648. return weechat.WEECHAT_RC_OK
  649. def key_i(buf, input_line, cur, count):
  650. """Start Insert mode.
  651. See Also:
  652. `key_base()`.
  653. """
  654. set_mode("INSERT")
  655. def key_a(buf, input_line, cur, count):
  656. """Move cursor one character to the right and start Insert mode.
  657. See Also:
  658. `key_base()`.
  659. """
  660. set_cur(buf, input_line, cur + 1, False)
  661. set_mode("INSERT")
  662. def key_A(buf, input_line, cur, count):
  663. """Move cursor to end of line and start Insert mode.
  664. See Also:
  665. `key_base()`.
  666. """
  667. set_cur(buf, input_line, len(input_line), False)
  668. set_mode("INSERT")
  669. def key_I(buf, input_line, cur, count):
  670. """Move cursor to first non-blank character and start Insert mode.
  671. See Also:
  672. `key_base()`.
  673. """
  674. pos, _, _ = motion_carret(input_line, cur, 0)
  675. set_cur(buf, input_line, pos)
  676. set_mode("INSERT")
  677. def key_G(buf, input_line, cur, count):
  678. """Scroll to specified line or bottom of buffer.
  679. See Also:
  680. `key_base()`.
  681. """
  682. if count > 0:
  683. # This is necessary to prevent weird scroll jumps.
  684. weechat.command("", "/window scroll_top")
  685. weechat.command("", "/window scroll %s" % (count - 1))
  686. else:
  687. weechat.command("", "/window scroll_bottom")
  688. def key_r(buf, input_line, cur, count):
  689. """Replace `count` characters under the cursor.
  690. See Also:
  691. `key_base()`.
  692. """
  693. start_catching_keys(1, "cb_key_r", input_line, cur, count, buf)
  694. def cb_key_r():
  695. """Callback for `key_r()`.
  696. See Also:
  697. `start_catching_keys()`.
  698. """
  699. global catching_keys_data
  700. input_line = list(catching_keys_data['input_line'])
  701. count = max(catching_keys_data['count'], 1)
  702. cur = catching_keys_data['cur']
  703. if cur + count <= len(input_line):
  704. for _ in range(count):
  705. input_line[cur] = catching_keys_data['keys']
  706. cur += 1
  707. input_line = "".join(input_line)
  708. weechat.buffer_set(catching_keys_data['buf'], "input", input_line)
  709. set_cur(catching_keys_data['buf'], input_line, cur - 1)
  710. catching_keys_data = {'amount': 0}
  711. def key_R(buf, input_line, cur, count):
  712. """Start Replace mode.
  713. See Also:
  714. `key_base()`.
  715. """
  716. set_mode("REPLACE")
  717. def key_tilda(buf, input_line, cur, count):
  718. """Switch the case of `count` characters under the cursor.
  719. See Also:
  720. `key_base()`.
  721. """
  722. input_line = list(input_line)
  723. count = max(1, count)
  724. while count and cur < len(input_line):
  725. input_line[cur] = input_line[cur].swapcase()
  726. count -= 1
  727. cur += 1
  728. input_line = "".join(input_line)
  729. weechat.buffer_set(buf, "input", input_line)
  730. set_cur(buf, input_line, cur)
  731. def key_alt_j(buf, input_line, cur, count):
  732. """Go to WeeChat buffer.
  733. Called to preserve WeeChat's alt-j buffer switching.
  734. This is only called when alt-j<num> is pressed after pressing Esc, because
  735. \x01\x01j is received in key_combo_default which becomes \x01j after
  736. removing the detected Esc key.
  737. If Esc isn't the last pressed key, \x01j<num> is directly received in
  738. key_combo_default.
  739. """
  740. start_catching_keys(2, "cb_key_alt_j", input_line, cur, count)
  741. def cb_key_alt_j():
  742. """Callback for `key_alt_j()`.
  743. See Also:
  744. `start_catching_keys()`.
  745. """
  746. global catching_keys_data
  747. weechat.command("", "/buffer " + catching_keys_data['keys'])
  748. catching_keys_data = {'amount': 0}
  749. def key_semicolon(buf, input_line, cur, count, swap=False):
  750. """Repeat last f, t, F, T `count` times.
  751. Args:
  752. swap (bool, optional): if True, the last motion will be repeated in the
  753. opposite direction (e.g. "f" instead of "F"). Defaults to False.
  754. See Also:
  755. `key_base()`.
  756. """
  757. global catching_keys_data, vi_buffer
  758. catching_keys_data = ({'amount': 0,
  759. 'input_line': input_line,
  760. 'cur': cur,
  761. 'keys': last_search_motion['data'],
  762. 'count': count,
  763. 'new_cur': 0,
  764. 'buf': buf})
  765. # Swap the motion's case if called from key_comma.
  766. if swap:
  767. motion = last_search_motion['motion'].swapcase()
  768. else:
  769. motion = last_search_motion['motion']
  770. func = "cb_motion_%s" % motion
  771. vi_buffer = motion
  772. globals()[func](False)
  773. def key_comma(buf, input_line, cur, count):
  774. """Repeat last f, t, F, T in opposite direction `count` times.
  775. See Also:
  776. `key_base()`.
  777. """
  778. key_semicolon(buf, input_line, cur, count, True)
  779. def key_u(buf, input_line, cur, count):
  780. """Undo change `count` times.
  781. See Also:
  782. `key_base()`.
  783. """
  784. buf = weechat.current_buffer()
  785. if buf not in undo_history:
  786. return
  787. for _ in range(max(count, 1)):
  788. if undo_history_index[buf] > -len(undo_history[buf]):
  789. undo_history_index[buf] -= 1
  790. input_line = undo_history[buf][undo_history_index[buf]]
  791. weechat.buffer_set(buf, "input", input_line)
  792. else:
  793. break
  794. def key_ctrl_r(buf, input_line, cur, count):
  795. """Redo change `count` times.
  796. See Also:
  797. `key_base()`.
  798. """
  799. if buf not in undo_history:
  800. return
  801. for _ in range(max(count, 1)):
  802. if undo_history_index[buf] < -1:
  803. undo_history_index[buf] += 1
  804. input_line = undo_history[buf][undo_history_index[buf]]
  805. weechat.buffer_set(buf, "input", input_line)
  806. else:
  807. break
  808. # Vi key bindings.
  809. # ================
  810. # String values will be executed as normal WeeChat commands.
  811. # For functions, see `key_base()` for reference.
  812. VI_KEYS = {'j': "/window scroll_down",
  813. 'k': "/window scroll_up",
  814. 'G': key_G,
  815. 'gg': "/window scroll_top",
  816. 'x': "/input delete_next_char",
  817. 'X': "/input delete_previous_char",
  818. 'dd': "/input delete_line",
  819. 'D': "/input delete_end_of_line",
  820. 'cc': key_cc,
  821. 'C': key_C,
  822. 'i': key_i,
  823. 'a': key_a,
  824. 'A': key_A,
  825. 'I': key_I,
  826. 'yy': key_yy,
  827. 'p': key_p,
  828. 'gt': "/buffer -1",
  829. 'K': "/buffer -1",
  830. 'gT': "/buffer +1",
  831. 'J': "/buffer +1",
  832. 'r': key_r,
  833. 'R': key_R,
  834. '~': key_tilda,
  835. 'nt': "/bar scroll nicklist * -100%",
  836. 'nT': "/bar scroll nicklist * +100%",
  837. '\x01[[A': "/input history_previous",
  838. '\x01[[B': "/input history_next",
  839. '\x01[[C': "/input move_next_char",
  840. '\x01[[D': "/input move_previous_char",
  841. '\x01[[H': "/input move_beginning_of_line",
  842. '\x01[[F': "/input move_end_of_line",
  843. '\x01[[5~': "/window page_up",
  844. '\x01[[6~': "/window page_down",
  845. '\x01[[3~': "/input delete_next_char",
  846. '\x01[[2~': key_i,
  847. '\x01M': "/input return",
  848. '\x01?': "/input move_previous_char",
  849. ' ': "/input move_next_char",
  850. '\x01[j': key_alt_j,
  851. '\x01[1': "/buffer *1",
  852. '\x01[2': "/buffer *2",
  853. '\x01[3': "/buffer *3",
  854. '\x01[4': "/buffer *4",
  855. '\x01[5': "/buffer *5",
  856. '\x01[6': "/buffer *6",
  857. '\x01[7': "/buffer *7",
  858. '\x01[8': "/buffer *8",
  859. '\x01[9': "/buffer *9",
  860. '\x01[0': "/buffer *10",
  861. '\x01^': "/input jump_last_buffer_displayed",
  862. '\x01D': "/window page_down",
  863. '\x01U': "/window page_up",
  864. '\x01Wh': "/window left",
  865. '\x01Wj': "/window down",
  866. '\x01Wk': "/window up",
  867. '\x01Wl': "/window right",
  868. '\x01W=': "/window balance",
  869. '\x01Wx': "/window swap",
  870. '\x01Ws': "/window splith",
  871. '\x01Wv': "/window splitv",
  872. '\x01Wq': "/window merge",
  873. ';': key_semicolon,
  874. ',': key_comma,
  875. 'u': key_u,
  876. '\x01R': key_ctrl_r}
  877. # Add alt-j<number> bindings.
  878. for i in range(10, 99):
  879. VI_KEYS['\x01[j%s' % i] = "/buffer %s" % i
  880. # Key handling.
  881. # =============
  882. def cb_key_pressed(data, signal, signal_data):
  883. """Detect potential Esc presses.
  884. Alt and Esc are detected as the same key in most terminals. The difference
  885. is that Alt signal is sent just before the other pressed key's signal.
  886. We therefore use a timeout (50ms) to detect whether Alt or Esc was pressed.
  887. """
  888. global last_signal_time
  889. last_signal_time = time.time()
  890. if signal_data == "\x01[":
  891. # In 50ms, check if any other keys were pressed. If not, it's Esc!
  892. weechat.hook_timer(50, 0, 1, "cb_check_esc",
  893. "{:f}".format(last_signal_time))
  894. return weechat.WEECHAT_RC_OK
  895. def cb_check_esc(data, remaining_calls):
  896. """Check if the Esc key was pressed and change the mode accordingly."""
  897. global esc_pressed, vi_buffer, catching_keys_data
  898. # Not perfect, would be better to use direct comparison (==) but that only
  899. # works for py2 and not for py3.
  900. if abs(last_signal_time - float(data)) <= 0.000001:
  901. esc_pressed += 1
  902. if mode == "SEARCH":
  903. weechat.command("", "/input search_stop_here")
  904. set_mode("NORMAL")
  905. # Cancel any current partial commands.
  906. vi_buffer = ""
  907. catching_keys_data = {'amount': 0}
  908. weechat.bar_item_update("vi_buffer")
  909. return weechat.WEECHAT_RC_OK
  910. def cb_key_combo_default(data, signal, signal_data):
  911. """Eat and handle key events when in Normal mode, if needed.
  912. The key_combo_default signal is sent when a key combo is pressed. For
  913. example, alt-k will send the "\x01[k" signal.
  914. Esc is handled a bit differently to avoid delays, see `cb_key_pressed()`.
  915. """
  916. global esc_pressed, vi_buffer, cmd_compl_text, cmd_text_orig, \
  917. cmd_compl_pos, cmd_history_index
  918. # If Esc was pressed, strip the Esc part from the pressed keys.
  919. # Example: user presses Esc followed by i. This is detected as "\x01[i",
  920. # but we only want to handle "i".
  921. keys = signal_data
  922. if esc_pressed or esc_pressed == -2:
  923. if keys.startswith("\x01[" * esc_pressed):
  924. # Multiples of 3 seem to "cancel" themselves,
  925. # e.g. Esc-Esc-Esc-Alt-j-11 is detected as "\x01[\x01[\x01"
  926. # followed by "\x01[j11" (two different signals).
  927. if signal_data == "\x01[" * 3:
  928. esc_pressed = -1 # `cb_check_esc()` will increment it to 0.
  929. else:
  930. esc_pressed = 0
  931. # This can happen if a valid combination is started but interrupted
  932. # with Esc, such as Ctrl-W→Esc→w which would send two signals:
  933. # "\x01W\x01[" then "\x01W\x01[w".
  934. # In that case, we still need to handle the next signal ("\x01W\x01[w")
  935. # so we use the special value "-2".
  936. else:
  937. esc_pressed = -2
  938. keys = keys.split("\x01[")[-1] # Remove the "Esc" part(s).
  939. # Ctrl-Space.
  940. elif keys == "\x01@":
  941. set_mode("NORMAL")
  942. return weechat.WEECHAT_RC_OK_EAT
  943. # Clear the undo history for this buffer on <Return>.
  944. if keys == "\x01M":
  945. buf = weechat.current_buffer()
  946. clear_undo_history(buf)
  947. # Detect imap_esc presses if any.
  948. if mode == "INSERT":
  949. imap_esc = vimode_settings['imap_esc']
  950. if not imap_esc:
  951. return weechat.WEECHAT_RC_OK
  952. if (imap_esc.startswith(vi_buffer) and
  953. imap_esc[len(vi_buffer):len(vi_buffer)+1] == keys):
  954. vi_buffer += keys
  955. weechat.bar_item_update("vi_buffer")
  956. weechat.hook_timer(int(vimode_settings['imap_esc_timeout']), 0, 1,
  957. "cb_check_imap_esc", vi_buffer)
  958. elif (vi_buffer and imap_esc.startswith(vi_buffer) and
  959. imap_esc[len(vi_buffer):len(vi_buffer)+1] != keys):
  960. vi_buffer = ""
  961. weechat.bar_item_update("vi_buffer")
  962. # imap_esc sequence detected -- remove the sequence keys from the
  963. # Weechat input bar and enter Normal mode.
  964. if imap_esc == vi_buffer:
  965. buf = weechat.current_buffer()
  966. input_line = weechat.buffer_get_string(buf, "input")
  967. cur = weechat.buffer_get_integer(buf, "input_pos")
  968. input_line = (input_line[:cur-len(imap_esc)+1] +
  969. input_line[cur:])
  970. weechat.buffer_set(buf, "input", input_line)
  971. set_cur(buf, input_line, cur-len(imap_esc)+1, False)
  972. set_mode("NORMAL")
  973. vi_buffer = ""
  974. weechat.bar_item_update("vi_buffer")
  975. return weechat.WEECHAT_RC_OK_EAT
  976. return weechat.WEECHAT_RC_OK
  977. # We're in Replace mode — allow "normal" key presses (e.g. "a") and
  978. # overwrite the next character with them, but let the other key presses
  979. # pass normally (e.g. backspace, arrow keys, etc).
  980. if mode == "REPLACE":
  981. if len(keys) == 1:
  982. weechat.command("", "/input delete_next_char")
  983. elif keys == "\x01?":
  984. weechat.command("", "/input move_previous_char")
  985. return weechat.WEECHAT_RC_OK_EAT
  986. return weechat.WEECHAT_RC_OK
  987. # We're catching keys! Only "normal" key presses interest us (e.g. "a"),
  988. # not complex ones (e.g. backspace).
  989. if len(keys) == 1 and catching_keys_data['amount']:
  990. catching_keys_data['keys'] += keys
  991. catching_keys_data['amount'] -= 1
  992. # Done catching keys, execute the callback.
  993. if catching_keys_data['amount'] == 0:
  994. globals()[catching_keys_data['callback']]()
  995. vi_buffer = ""
  996. weechat.bar_item_update("vi_buffer")
  997. return weechat.WEECHAT_RC_OK_EAT
  998. # We're in command-line mode.
  999. if mode == "COMMAND":
  1000. buf = weechat.current_buffer()
  1001. cmd_text = weechat.buffer_get_string(buf, "input")
  1002. weechat.hook_timer(1, 0, 1, "cb_check_cmd_mode", "")
  1003. # Return key.
  1004. if keys == "\x01M":
  1005. weechat.hook_timer(1, 0, 1, "cb_exec_cmd", cmd_text)
  1006. if len(cmd_text) > 1 and (not cmd_history or
  1007. cmd_history[-1] != cmd_text):
  1008. cmd_history.append(cmd_text)
  1009. cmd_history_index = 0
  1010. set_mode("NORMAL")
  1011. buf = weechat.current_buffer()
  1012. input_line = input_line_backup[buf]['input_line']
  1013. weechat.buffer_set(buf, "input", input_line)
  1014. set_cur(buf, input_line, input_line_backup[buf]['cur'], False)
  1015. # Up arrow.
  1016. elif keys == "\x01[[A":
  1017. if cmd_history_index > -len(cmd_history):
  1018. cmd_history_index -= 1
  1019. cmd_text = cmd_history[cmd_history_index]
  1020. weechat.buffer_set(buf, "input", cmd_text)
  1021. set_cur(buf, cmd_text, len(cmd_text), False)
  1022. # Down arrow.
  1023. elif keys == "\x01[[B":
  1024. if cmd_history_index < -1:
  1025. cmd_history_index += 1
  1026. cmd_text = cmd_history[cmd_history_index]
  1027. else:
  1028. cmd_history_index = 0
  1029. cmd_text = ":"
  1030. weechat.buffer_set(buf, "input", cmd_text)
  1031. set_cur(buf, cmd_text, len(cmd_text), False)
  1032. # Tab key. No completion when searching ("/").
  1033. elif keys == "\x01I" and cmd_text[0] == ":":
  1034. if cmd_text_orig is None:
  1035. input_ = list(cmd_text)
  1036. del input_[0]
  1037. cmd_text_orig = "".join(input_)
  1038. cmd_compl_list = []
  1039. for cmd in VI_COMMANDS.keys():
  1040. if cmd.startswith(cmd_text_orig):
  1041. cmd_compl_list.append(cmd)
  1042. if cmd_compl_list:
  1043. curr_suggestion = cmd_compl_list[cmd_compl_pos]
  1044. cmd_text = ":%s" % curr_suggestion
  1045. cmd_compl_list[cmd_compl_pos] = weechat.string_eval_expression(
  1046. "${color:bold}%s${color:-bold}" % curr_suggestion,
  1047. {}, {}, {})
  1048. cmd_compl_text = ", ".join(cmd_compl_list)
  1049. cmd_compl_pos = (cmd_compl_pos + 1) % len(cmd_compl_list)
  1050. weechat.buffer_set(buf, "input", cmd_text)
  1051. set_cur(buf, cmd_text, len(cmd_text), False)
  1052. # Input.
  1053. else:
  1054. cmd_compl_text = ""
  1055. cmd_text_orig = None
  1056. cmd_compl_pos = 0
  1057. weechat.bar_item_update("cmd_completion")
  1058. if keys in ["\x01M", "\x01[[A", "\x01[[B"]:
  1059. cmd_compl_text = ""
  1060. return weechat.WEECHAT_RC_OK_EAT
  1061. else:
  1062. return weechat.WEECHAT_RC_OK
  1063. # Enter command mode.
  1064. elif keys in [":", "/"]:
  1065. if keys == "/":
  1066. weechat.command("", "/input search_text_here")
  1067. if not weechat.config_string_to_boolean(
  1068. vimode_settings['search_vim']):
  1069. return weechat.WEECHAT_RC_OK
  1070. else:
  1071. buf = weechat.current_buffer()
  1072. cur = weechat.buffer_get_integer(buf, "input_pos")
  1073. input_line = weechat.buffer_get_string(buf, "input")
  1074. input_line_backup[buf] = {'input_line': input_line, 'cur': cur}
  1075. input_line = ":"
  1076. weechat.buffer_set(buf, "input", input_line)
  1077. set_cur(buf, input_line, 1, False)
  1078. set_mode("COMMAND")
  1079. cmd_compl_text = ""
  1080. cmd_text_orig = None
  1081. cmd_compl_pos = 0
  1082. return weechat.WEECHAT_RC_OK_EAT
  1083. # Add key to the buffer.
  1084. vi_buffer += keys
  1085. weechat.bar_item_update("vi_buffer")
  1086. if not vi_buffer:
  1087. return weechat.WEECHAT_RC_OK
  1088. # Check if the keys have a (partial or full) match. If so, also get the
  1089. # keys without the count. (These are the actual keys we should handle.)
  1090. # After that, `vi_buffer` is only used for display purposes — only
  1091. # `vi_keys` is checked for all the handling.
  1092. # If no matches are found, the keys buffer is cleared.
  1093. matched, vi_keys, count = get_keys_and_count(vi_buffer)
  1094. if not matched:
  1095. vi_buffer = ""
  1096. return weechat.WEECHAT_RC_OK_EAT
  1097. # Check if it's a command (user defined key mapped to a :cmd).
  1098. if vi_keys.startswith(":"):
  1099. weechat.hook_timer(1, 0, 1, "cb_exec_cmd", "{} {}".format(vi_keys,
  1100. count))
  1101. vi_buffer = ""
  1102. return weechat.WEECHAT_RC_OK_EAT
  1103. # It's a WeeChat command (user defined key mapped to a /cmd).
  1104. if vi_keys.startswith("/"):
  1105. weechat.command("", vi_keys)
  1106. vi_buffer = ""
  1107. return weechat.WEECHAT_RC_OK_EAT
  1108. buf = weechat.current_buffer()
  1109. input_line = weechat.buffer_get_string(buf, "input")
  1110. cur = weechat.buffer_get_integer(buf, "input_pos")
  1111. # It's a default mapping. If the corresponding value is a string, we assume
  1112. # it's a WeeChat command. Otherwise, it's a method we'll call.
  1113. if vi_keys in VI_KEYS:
  1114. if vi_keys not in ['u', '\x01R']:
  1115. add_undo_history(buf, input_line)
  1116. if isinstance(VI_KEYS[vi_keys], str):
  1117. for _ in range(max(count, 1)):
  1118. # This is to avoid crashing WeeChat on script reloads/unloads,
  1119. # because no hooks must still be running when a script is
  1120. # reloaded or unloaded.
  1121. if (VI_KEYS[vi_keys] == "/input return" and
  1122. input_line.startswith("/script ")):
  1123. return weechat.WEECHAT_RC_OK
  1124. weechat.command("", VI_KEYS[vi_keys])
  1125. current_cur = weechat.buffer_get_integer(buf, "input_pos")
  1126. set_cur(buf, input_line, current_cur)
  1127. else:
  1128. VI_KEYS[vi_keys](buf, input_line, cur, count)
  1129. # It's a motion (e.g. "w") — call `motion_X()` where X is the motion, then
  1130. # set the cursor's position to what that function returned.
  1131. elif vi_keys in VI_MOTIONS:
  1132. if vi_keys in SPECIAL_CHARS:
  1133. func = "motion_%s" % SPECIAL_CHARS[vi_keys]
  1134. else:
  1135. func = "motion_%s" % vi_keys
  1136. end, _, _ = globals()[func](input_line, cur, count)
  1137. set_cur(buf, input_line, end)
  1138. # It's an operator + motion (e.g. "dw") — call `motion_X()` (where X is
  1139. # the motion), then we call `operator_Y()` (where Y is the operator)
  1140. # with the position `motion_X()` returned. `operator_Y()` should then
  1141. # handle changing the input line.
  1142. elif (len(vi_keys) > 1 and
  1143. vi_keys[0] in VI_OPERATORS and
  1144. vi_keys[1:] in VI_MOTIONS):
  1145. add_undo_history(buf, input_line)
  1146. if vi_keys[1:] in SPECIAL_CHARS:
  1147. func = "motion_%s" % SPECIAL_CHARS[vi_keys[1:]]
  1148. else:
  1149. func = "motion_%s" % vi_keys[1:]
  1150. pos, overwrite, catching = globals()[func](input_line, cur, count)
  1151. # If it's a catching motion, we don't want to call the operator just
  1152. # yet -- this code will run again when the motion is complete, at which
  1153. # point we will.
  1154. if not catching:
  1155. oper = "operator_%s" % vi_keys[0]
  1156. globals()[oper](buf, input_line, cur, pos, overwrite)
  1157. # The combo isn't completed yet (e.g. just "d").
  1158. else:
  1159. return weechat.WEECHAT_RC_OK_EAT
  1160. # We've already handled the key combo, so clear the keys buffer.
  1161. if not catching_keys_data['amount']:
  1162. vi_buffer = ""
  1163. weechat.bar_item_update("vi_buffer")
  1164. return weechat.WEECHAT_RC_OK_EAT
  1165. def cb_check_imap_esc(data, remaining_calls):
  1166. """Clear the imap_esc sequence after some time if nothing was pressed."""
  1167. global vi_buffer
  1168. if vi_buffer == data:
  1169. vi_buffer = ""
  1170. weechat.bar_item_update("vi_buffer")
  1171. return weechat.WEECHAT_RC_OK
  1172. def cb_key_combo_search(data, signal, signal_data):
  1173. """Handle keys while search mode is active (if search_vim is enabled)."""
  1174. if not weechat.config_string_to_boolean(vimode_settings['search_vim']):
  1175. return weechat.WEECHAT_RC_OK
  1176. if mode == "COMMAND":
  1177. if signal_data == "\x01M":
  1178. set_mode("SEARCH")
  1179. return weechat.WEECHAT_RC_OK_EAT
  1180. elif mode == "SEARCH":
  1181. if signal_data == "\x01M":
  1182. set_mode("NORMAL")
  1183. else:
  1184. if signal_data == "n":
  1185. weechat.command("", "/input search_next")
  1186. elif signal_data == "N":
  1187. weechat.command("", "/input search_previous")
  1188. # Start a new search.
  1189. elif signal_data == "/":
  1190. weechat.command("", "/input search_stop_here")
  1191. set_mode("NORMAL")
  1192. weechat.command("", "/input search_text_here")
  1193. return weechat.WEECHAT_RC_OK_EAT
  1194. return weechat.WEECHAT_RC_OK
  1195. # Callbacks.
  1196. # ==========
  1197. # Bar items.
  1198. # ----------
  1199. def cb_vi_buffer(data, item, window):
  1200. """Return the content of the vi buffer (pressed keys on hold)."""
  1201. return vi_buffer
  1202. def cb_cmd_completion(data, item, window):
  1203. """Return the text of the command line."""
  1204. return cmd_compl_text
  1205. def cb_mode_indicator(data, item, window):
  1206. """Return the current mode (INSERT/NORMAL/REPLACE/...)."""
  1207. return "{}{}{}{}{}".format(
  1208. weechat.color(mode_colors[mode]),
  1209. vimode_settings['mode_indicator_prefix'], mode,
  1210. vimode_settings['mode_indicator_suffix'], weechat.color("reset"))
  1211. def cb_line_numbers(data, item, window):
  1212. """Fill the line numbers bar item."""
  1213. bar_height = weechat.window_get_integer(window, "win_chat_height")
  1214. content = ""
  1215. for i in range(1, bar_height + 1):
  1216. content += "{}{}{}\n".format(vimode_settings['line_number_prefix'], i,
  1217. vimode_settings['line_number_suffix'])
  1218. return content
  1219. # Callbacks for the line numbers bar.
  1220. # ...................................
  1221. def cb_update_line_numbers(data, signal, signal_data):
  1222. """Call `cb_timer_update_line_numbers()` when switching buffers.
  1223. A timer is required because the bar item is refreshed before the new buffer
  1224. is actually displayed, so ``win_chat_height`` would refer to the old
  1225. buffer. Using a timer refreshes the item after the new buffer is displayed.
  1226. """
  1227. weechat.hook_timer(10, 0, 1, "cb_timer_update_line_numbers", "")
  1228. return weechat.WEECHAT_RC_OK
  1229. def cb_timer_update_line_numbers(data, remaining_calls):
  1230. """Update the line numbers bar item."""
  1231. weechat.bar_item_update("line_numbers")
  1232. return weechat.WEECHAT_RC_OK
  1233. # Config.
  1234. # -------
  1235. def cb_config(data, option, value):
  1236. """Script option changed, update our copy."""
  1237. option_name = option.split(".")[-1]
  1238. if option_name in vimode_settings:
  1239. vimode_settings[option_name] = value
  1240. if option_name == 'user_mappings':
  1241. load_user_mappings()
  1242. if "_color" in option_name:
  1243. load_mode_colors()
  1244. return weechat.WEECHAT_RC_OK
  1245. def load_mode_colors():
  1246. mode_colors.update({
  1247. 'NORMAL': "{},{}".format(
  1248. vimode_settings['mode_indicator_normal_color'],
  1249. vimode_settings['mode_indicator_normal_color_bg']),
  1250. 'INSERT': "{},{}".format(
  1251. vimode_settings['mode_indicator_insert_color'],
  1252. vimode_settings['mode_indicator_insert_color_bg']),
  1253. 'REPLACE': "{},{}".format(
  1254. vimode_settings['mode_indicator_replace_color'],
  1255. vimode_settings['mode_indicator_replace_color_bg']),
  1256. 'COMMAND': "{},{}".format(
  1257. vimode_settings['mode_indicator_cmd_color'],
  1258. vimode_settings['mode_indicator_cmd_color_bg']),
  1259. 'SEARCH': "{},{}".format(
  1260. vimode_settings['mode_indicator_search_color'],
  1261. vimode_settings['mode_indicator_search_color_bg'])
  1262. })
  1263. def load_user_mappings():
  1264. """Load user-defined mappings."""
  1265. mappings = {}
  1266. if vimode_settings['user_mappings']:
  1267. mappings.update(json.loads(vimode_settings['user_mappings']))
  1268. vimode_settings['user_mappings'] = mappings
  1269. # Command-line execution.
  1270. # -----------------------
  1271. def cb_exec_cmd(data, remaining_calls):
  1272. """Translate and execute our custom commands to WeeChat command."""
  1273. # Process the entered command.
  1274. data = list(data)
  1275. del data[0]
  1276. data = "".join(data)
  1277. # s/foo/bar command.
  1278. if data.startswith("s/"):
  1279. cmd = data
  1280. parsed_cmd = next(csv.reader(StringIO(cmd), delimiter="/",
  1281. escapechar="\\"))
  1282. pattern = re.escape(parsed_cmd[1])
  1283. repl = parsed_cmd[2]
  1284. repl = re.sub(r"([^\\])&", r"\1" + pattern, repl)
  1285. flag = None
  1286. if len(parsed_cmd) == 4:
  1287. flag = parsed_cmd[3]
  1288. count = 1
  1289. if flag == "g":
  1290. count = 0
  1291. buf = weechat.current_buffer()
  1292. input_line = weechat.buffer_get_string(buf, "input")
  1293. input_line = re.sub(pattern, repl, input_line, count)
  1294. weechat.buffer_set(buf, "input", input_line)
  1295. # Shell command.
  1296. elif data.startswith("!"):
  1297. weechat.command("", "/exec -buffer shell %s" % data[1:])
  1298. # Commands like `:22`. This should start cursor mode (``/cursor``) and take
  1299. # us to the relevant line.
  1300. elif data.isdigit():
  1301. line_number = int(data)
  1302. hdata_window = weechat.hdata_get("window")
  1303. window = weechat.current_window()
  1304. x = weechat.hdata_integer(hdata_window, window, "win_chat_x")
  1305. y = (weechat.hdata_integer(hdata_window, window, "win_chat_y") +
  1306. (line_number - 1))
  1307. weechat.command("", "/cursor go {},{}".format(x, y))
  1308. # Check againt defined commands.
  1309. elif data:
  1310. raw_data = data
  1311. data = data.split(" ", 1)
  1312. cmd = data[0]
  1313. args = ""
  1314. if len(data) == 2:
  1315. args = data[1]
  1316. if cmd in VI_COMMANDS:
  1317. if isinstance(VI_COMMANDS[cmd], str):
  1318. weechat.command("", "%s %s" % (VI_COMMANDS[cmd], args))
  1319. else:
  1320. VI_COMMANDS[cmd](args)
  1321. else:
  1322. # Check for commands not sepearated by space (e.g. "b2")
  1323. for i in range(1, len(raw_data)):
  1324. tmp_cmd = raw_data[:i]
  1325. tmp_args = raw_data[i:]
  1326. if tmp_cmd in VI_COMMANDS and tmp_args.isdigit():
  1327. weechat.command("", "%s %s" % (VI_COMMANDS[tmp_cmd],
  1328. tmp_args))
  1329. return weechat.WEECHAT_RC_OK
  1330. # No vi commands found, run the command as WeeChat command
  1331. weechat.command("", "/{} {}".format(cmd, args))
  1332. return weechat.WEECHAT_RC_OK
  1333. def cb_vimode_go_to_normal(data, buf, args):
  1334. set_mode("NORMAL")
  1335. return weechat.WEECHAT_RC_OK
  1336. # Script commands.
  1337. # ----------------
  1338. def cb_vimode_cmd(data, buf, args):
  1339. """Handle script commands (``/vimode <command>``)."""
  1340. # ``/vimode`` or ``/vimode help``
  1341. if not args or args == "help":
  1342. weechat.prnt("", "[vimode.py] %s" % README_URL)
  1343. # ``/vimode bind_keys`` or ``/vimode bind_keys --list``
  1344. elif args.startswith("bind_keys"):
  1345. infolist = weechat.infolist_get("key", "", "default")
  1346. weechat.infolist_reset_item_cursor(infolist)
  1347. commands = ["/key unbind ctrl-W",
  1348. "/key bind ctrl-W /input delete_previous_word",
  1349. "/key bind ctrl-^ /input jump_last_buffer_displayed",
  1350. "/key bind ctrl-Wh /window left",
  1351. "/key bind ctrl-Wj /window down",
  1352. "/key bind ctrl-Wk /window up",
  1353. "/key bind ctrl-Wl /window right",
  1354. "/key bind ctrl-W= /window balance",
  1355. "/key bind ctrl-Wx /window swap",
  1356. "/key bind ctrl-Ws /window splith",
  1357. "/key bind ctrl-Wv /window splitv",
  1358. "/key bind ctrl-Wq /window merge"]
  1359. while weechat.infolist_next(infolist):
  1360. key = weechat.infolist_string(infolist, "key")
  1361. if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key):
  1362. commands.append("/key unbind %s" % key)
  1363. weechat.infolist_free(infolist)
  1364. if args == "bind_keys":
  1365. weechat.prnt("", "Running commands:")
  1366. for command in commands:
  1367. weechat.command("", command)
  1368. weechat.prnt("", "Done.")
  1369. elif args == "bind_keys --list":
  1370. weechat.prnt("", "Listing commands we'll run:")
  1371. for command in commands:
  1372. weechat.prnt("", " %s" % command)
  1373. weechat.prnt("", "Done.")
  1374. return weechat.WEECHAT_RC_OK
  1375. # Helpers.
  1376. # ========
  1377. # Motions/keys helpers.
  1378. # ---------------------
  1379. def get_pos(data, regex, cur, ignore_cur=False, count=0):
  1380. """Return the position of `regex` match in `data`, starting at `cur`.
  1381. Args:
  1382. data (str): the data to search in.
  1383. regex (pattern): regex pattern to search for.
  1384. cur (int): where to start the search.
  1385. ignore_cur (bool, optional): should the first match be ignored if it's
  1386. also the character at `cur`?
  1387. Defaults to False.
  1388. count (int, optional): the index of the match to return. Defaults to 0.
  1389. Returns:
  1390. int: position of the match. -1 if no matches are found.
  1391. """
  1392. # List of the *positions* of the found patterns.
  1393. matches = [m.start() for m in re.finditer(regex, data[cur:])]
  1394. pos = -1
  1395. if count:
  1396. if len(matches) > count - 1:
  1397. if ignore_cur and matches[0] == 0:
  1398. if len(matches) > count:
  1399. pos = matches[count]
  1400. else:
  1401. pos = matches[count - 1]
  1402. elif matches:
  1403. if ignore_cur and matches[0] == 0:
  1404. if len(matches) > 1:
  1405. pos = matches[1]
  1406. else:
  1407. pos = matches[0]
  1408. return pos
  1409. def set_cur(buf, input_line, pos, cap=True):
  1410. """Set the cursor's position.
  1411. Args:
  1412. buf (str): pointer to the current WeeChat buffer.
  1413. input_line (str): the content of the input line.
  1414. pos (int): the position to set the cursor to.
  1415. cap (bool, optional): if True, the `pos` will shortened to the length
  1416. of `input_line` if it's too long. Defaults to True.
  1417. """
  1418. if cap:
  1419. pos = min(pos, len(input_line) - 1)
  1420. weechat.buffer_set(buf, "input_pos", str(pos))
  1421. def start_catching_keys(amount, callback, input_line, cur, count, buf=None):
  1422. """Start catching keys. Used for special commands (e.g. "f", "r").
  1423. amount (int): amount of keys to catch.
  1424. callback (str): name of method to call once all keys are caught.
  1425. input_line (str): input line's content.
  1426. cur (int): cursor's position.
  1427. count (int): count, e.g. "2" for "2fs".
  1428. buf (str, optional): pointer to the current WeeChat buffer.
  1429. Defaults to None.
  1430. `catching_keys_data` is a dict with the above arguments, as well as:
  1431. keys (str): pressed keys will be added under this key.
  1432. new_cur (int): the new cursor's position, set in the callback.
  1433. When catching keys is active, normal pressed keys (e.g. "a" but not arrows)
  1434. will get added to `catching_keys_data` under the key "keys", and will not
  1435. be handled any further.
  1436. Once all keys are caught, the method defined in the "callback" key is
  1437. called, and can use the data in `catching_keys_data` to perform its action.
  1438. """
  1439. global catching_keys_data
  1440. if "new_cur" in catching_keys_data:
  1441. new_cur = catching_keys_data['new_cur']
  1442. catching_keys_data = {'amount': 0}
  1443. return new_cur, True, False
  1444. catching_keys_data = ({'amount': amount,
  1445. 'callback': callback,
  1446. 'input_line': input_line,
  1447. 'cur': cur,
  1448. 'keys': "",
  1449. 'count': count,
  1450. 'new_cur': 0,
  1451. 'buf': buf})
  1452. return cur, False, True
  1453. def get_keys_and_count(combo):
  1454. """Check if `combo` is a valid combo and extract keys/counts if so.
  1455. Args:
  1456. combo (str): pressed keys combo.
  1457. Returns:
  1458. matched (bool): True if the combo has a (partial or full) match, False
  1459. otherwise.
  1460. combo (str): `combo` with the count removed. These are the actual keys
  1461. we should handle. User mappings are also expanded.
  1462. count (int): count for `combo`.
  1463. """
  1464. # Look for a potential match (e.g. "d" might become "dw" or "dd" so we
  1465. # accept it, but "d9" is invalid).
  1466. matched = False
  1467. # Digits are allowed at the beginning (counts or "0").
  1468. count = 0
  1469. if combo.isdigit():
  1470. matched = True
  1471. elif combo and combo[0].isdigit():
  1472. count = ""
  1473. for char in combo:
  1474. if char.isdigit():
  1475. count += char
  1476. else:
  1477. break
  1478. combo = combo.replace(count, "", 1)
  1479. count = int(count)
  1480. # It's a user defined key. Expand it.
  1481. if combo in vimode_settings['user_mappings']:
  1482. combo = vimode_settings['user_mappings'][combo]
  1483. # It's a WeeChat command.
  1484. if not matched and combo.startswith("/"):
  1485. matched = True
  1486. # Check against defined keys.
  1487. if not matched:
  1488. for key in VI_KEYS:
  1489. if key.startswith(combo):
  1490. matched = True
  1491. break
  1492. # Check against defined motions.
  1493. if not matched:
  1494. for motion in VI_MOTIONS:
  1495. if motion.startswith(combo):
  1496. matched = True
  1497. break
  1498. # Check against defined operators + motions.
  1499. if not matched:
  1500. for operator in VI_OPERATORS:
  1501. if combo.startswith(operator):
  1502. # Check for counts before the motion (but after the operator).
  1503. vi_keys_no_op = combo[len(operator):]
  1504. # There's no motion yet.
  1505. if vi_keys_no_op.isdigit():
  1506. matched = True
  1507. break
  1508. # Get the motion count, then multiply the operator count by
  1509. # it, similar to vim's behavior.
  1510. elif vi_keys_no_op and vi_keys_no_op[0].isdigit():
  1511. motion_count = ""
  1512. for char in vi_keys_no_op:
  1513. if char.isdigit():
  1514. motion_count += char
  1515. else:
  1516. break
  1517. # Remove counts from `vi_keys_no_op`.
  1518. combo = combo.replace(motion_count, "", 1)
  1519. motion_count = int(motion_count)
  1520. count = max(count, 1) * motion_count
  1521. # Check against defined motions.
  1522. for motion in VI_MOTIONS:
  1523. if motion.startswith(combo[1:]):
  1524. matched = True
  1525. break
  1526. return matched, combo, count
  1527. # Other helpers.
  1528. # --------------
  1529. def set_mode(arg):
  1530. """Set the current mode and update the bar mode indicator."""
  1531. global mode
  1532. buf = weechat.current_buffer()
  1533. input_line = weechat.buffer_get_string(buf, "input")
  1534. if mode == "INSERT" and arg == "NORMAL":
  1535. add_undo_history(buf, input_line)
  1536. mode = arg
  1537. # If we're going to Normal mode, the cursor must move one character to the
  1538. # left.
  1539. if mode == "NORMAL":
  1540. cur = weechat.buffer_get_integer(buf, "input_pos")
  1541. set_cur(buf, input_line, cur - 1, False)
  1542. weechat.bar_item_update("mode_indicator")
  1543. def cb_check_cmd_mode(data, remaining_calls):
  1544. """Exit command mode if user erases the leading ':' character."""
  1545. buf = weechat.current_buffer()
  1546. cmd_text = weechat.buffer_get_string(buf, "input")
  1547. if not cmd_text:
  1548. set_mode("NORMAL")
  1549. return weechat.WEECHAT_RC_OK
  1550. def add_undo_history(buf, input_line):
  1551. """Add an item to the per-buffer undo history."""
  1552. if buf in undo_history:
  1553. if not undo_history[buf] or undo_history[buf][-1] != input_line:
  1554. undo_history[buf].append(input_line)
  1555. undo_history_index[buf] = -1
  1556. else:
  1557. undo_history[buf] = ['', input_line]
  1558. undo_history_index[buf] = -1
  1559. def clear_undo_history(buf):
  1560. """Clear the undo history for a given buffer."""
  1561. undo_history[buf] = ['']
  1562. undo_history_index[buf] = -1
  1563. def print_warning(text):
  1564. """Print warning, in red, to the current buffer."""
  1565. weechat.prnt("", ("%s[vimode.py] %s" % (weechat.color("red"), text)))
  1566. def check_warnings():
  1567. """Warn the user about problematic key bindings and tmux/screen."""
  1568. user_warned = False
  1569. # Warn the user about problematic key bindings that may conflict with
  1570. # vimode.
  1571. # The solution is to remove these key bindings, but that's up to the user.
  1572. infolist = weechat.infolist_get("key", "", "default")
  1573. problematic_keybindings = []
  1574. while weechat.infolist_next(infolist):
  1575. key = weechat.infolist_string(infolist, "key")
  1576. command = weechat.infolist_string(infolist, "command")
  1577. if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key):
  1578. problematic_keybindings.append("%s -> %s" % (key, command))
  1579. weechat.infolist_free(infolist)
  1580. if problematic_keybindings:
  1581. user_warned = True
  1582. print_warning("Problematic keybindings detected:")
  1583. for keybinding in problematic_keybindings:
  1584. print_warning(" %s" % keybinding)
  1585. print_warning("These keybindings may conflict with vimode.")
  1586. print_warning("You can remove problematic key bindings and add"
  1587. " recommended ones by using /vimode bind_keys, or only"
  1588. " list them with /vimode bind_keys --list")
  1589. print_warning("For help, see: %s" % FAQ_KEYBINDINGS)
  1590. del problematic_keybindings
  1591. # Warn tmux/screen users about possible Esc detection delays.
  1592. if "STY" in os.environ or "TMUX" in os.environ:
  1593. if user_warned:
  1594. weechat.prnt("", "")
  1595. user_warned = True
  1596. print_warning("tmux/screen users, see: %s" % FAQ_ESC)
  1597. if (user_warned and not
  1598. weechat.config_string_to_boolean(vimode_settings['no_warn'])):
  1599. if user_warned:
  1600. weechat.prnt("", "")
  1601. print_warning("To force disable warnings, you can set"
  1602. " plugins.var.python.vimode.no_warn to 'on'")
  1603. # Main script.
  1604. # ============
  1605. if __name__ == "__main__":
  1606. weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
  1607. SCRIPT_LICENSE, SCRIPT_DESC, "", "")
  1608. # Warn the user if he's using an unsupported WeeChat version.
  1609. VERSION = weechat.info_get("version_number", "")
  1610. if int(VERSION) < 0x01000000:
  1611. print_warning("Please upgrade to WeeChat ≥ 1.0.0. Previous versions"
  1612. " are not supported.")
  1613. # Set up script options.
  1614. for option, value in list(vimode_settings.items()):
  1615. if weechat.config_is_set_plugin(option):
  1616. vimode_settings[option] = weechat.config_get_plugin(option)
  1617. else:
  1618. weechat.config_set_plugin(option, value[0])
  1619. vimode_settings[option] = value[0]
  1620. weechat.config_set_desc_plugin(option,
  1621. "%s (default: \"%s\")" % (value[1],
  1622. value[0]))
  1623. load_user_mappings()
  1624. load_mode_colors()
  1625. # Warn the user about possible problems if necessary.
  1626. if not weechat.config_string_to_boolean(vimode_settings['no_warn']):
  1627. check_warnings()
  1628. # Create bar items and setup hooks.
  1629. weechat.bar_item_new("mode_indicator", "cb_mode_indicator", "")
  1630. weechat.bar_item_new("cmd_completion", "cb_cmd_completion", "")
  1631. weechat.bar_item_new("vi_buffer", "cb_vi_buffer", "")
  1632. weechat.bar_item_new("line_numbers", "cb_line_numbers", "")
  1633. if int(VERSION) >= 0x02090000:
  1634. weechat.bar_new("vi_line_numbers", "on", "0", "window", "", "left",
  1635. "vertical", "vertical", "0", "0", "default", "default",
  1636. "default", "default", "0", "line_numbers")
  1637. else:
  1638. weechat.bar_new("vi_line_numbers", "on", "0", "window", "", "left",
  1639. "vertical", "vertical", "0", "0", "default", "default",
  1640. "default", "0", "line_numbers")
  1641. weechat.hook_config("plugins.var.python.%s.*" % SCRIPT_NAME, "cb_config",
  1642. "")
  1643. weechat.hook_signal("key_pressed", "cb_key_pressed", "")
  1644. weechat.hook_signal("key_combo_default", "cb_key_combo_default", "")
  1645. weechat.hook_signal("key_combo_search", "cb_key_combo_search", "")
  1646. weechat.hook_signal("buffer_switch", "cb_update_line_numbers", "")
  1647. weechat.hook_command("vimode", SCRIPT_DESC, "[help | bind_keys [--list]]",
  1648. " help: show help\n"
  1649. "bind_keys: unbind problematic keys, and bind"
  1650. " recommended keys to use in WeeChat\n"
  1651. " --list: only list changes",
  1652. "help || bind_keys |--list",
  1653. "cb_vimode_cmd", "")
  1654. weechat.hook_command("vimode_go_to_normal",
  1655. ("This command can be used for key bindings to go to "
  1656. "normal mode."),
  1657. "", "", "", "cb_vimode_go_to_normal", "")
  1658. # Remove obsolete bar.
  1659. vi_cmd_bar = weechat.bar_search("vi_cmd")
  1660. weechat.bar_remove(vi_cmd_bar)