My dotfiles for my Linux rice managed with stow and make
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.
 
 
 
 
 
 

2234 lines
81 KiB

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