main.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #!/usr/bin/env python
  2. # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
  3. import sys
  4. from collections.abc import Sequence
  5. from functools import lru_cache
  6. from typing import Any
  7. from kitty.cli_stub import HintsCLIOptions
  8. from kitty.clipboard import set_clipboard_string, set_primary_selection
  9. from kitty.constants import website_url
  10. from kitty.fast_data_types import get_options
  11. from kitty.typing import BossType, WindowType
  12. from kitty.utils import get_editor, resolve_custom_file
  13. from ..tui.handler import result_handler
  14. DEFAULT_REGEX = r'(?m)^\s*(.+)\s*$'
  15. def load_custom_processor(customize_processing: str) -> Any:
  16. if customize_processing.startswith('::import::'):
  17. import importlib
  18. m = importlib.import_module(customize_processing[len('::import::'):])
  19. return {k: getattr(m, k) for k in dir(m)}
  20. if customize_processing == '::linenum::':
  21. return {'handle_result': linenum_handle_result}
  22. custom_path = resolve_custom_file(customize_processing)
  23. import runpy
  24. return runpy.run_path(custom_path, run_name='__main__')
  25. class Mark:
  26. __slots__ = ('index', 'start', 'end', 'text', 'is_hyperlink', 'group_id', 'groupdict')
  27. def __init__(
  28. self,
  29. index: int, start: int, end: int,
  30. text: str,
  31. groupdict: Any,
  32. is_hyperlink: bool = False,
  33. group_id: str | None = None
  34. ):
  35. self.index, self.start, self.end = index, start, end
  36. self.text = text
  37. self.groupdict = groupdict
  38. self.is_hyperlink = is_hyperlink
  39. self.group_id = group_id
  40. def as_dict(self) -> dict[str, Any]:
  41. return {
  42. 'index': self.index, 'start': self.start, 'end': self.end,
  43. 'text': self.text, 'groupdict': {str(k):v for k, v in (self.groupdict or {}).items()},
  44. 'group_id': self.group_id or '', 'is_hyperlink': self.is_hyperlink
  45. }
  46. def parse_hints_args(args: list[str]) -> tuple[HintsCLIOptions, list[str]]:
  47. from kitty.cli import parse_args
  48. return parse_args(args, OPTIONS, usage, help_text, 'kitty +kitten hints', result_class=HintsCLIOptions)
  49. def custom_marking() -> None:
  50. import json
  51. text = sys.stdin.read()
  52. sys.stdin.close()
  53. opts, extra_cli_args = parse_hints_args(sys.argv[1:])
  54. m = load_custom_processor(opts.customize_processing or '::impossible::')
  55. if 'mark' not in m:
  56. raise SystemExit(2)
  57. all_marks = tuple(x.as_dict() for x in m['mark'](text, opts, Mark, extra_cli_args))
  58. sys.stdout.write(json.dumps(all_marks))
  59. raise SystemExit(0)
  60. OPTIONS = r'''
  61. --program
  62. type=list
  63. What program to use to open matched text. Defaults to the default open program
  64. for the operating system. Various special values are supported:
  65. :code:`-`
  66. paste the match into the terminal window.
  67. :code:`@`
  68. copy the match to the clipboard
  69. :code:`*`
  70. copy the match to the primary selection (on systems that support primary selections)
  71. :code:`@NAME`
  72. copy the match to the specified buffer, e.g. :code:`@a`
  73. :code:`default`
  74. run the default open program. Note that when using the hyperlink :code:`--type`
  75. the default is to use the kitty :doc:`hyperlink handling </open_actions>` facilities.
  76. :code:`launch`
  77. run :doc:`/launch` to open the program in a new kitty tab, window, overlay, etc.
  78. For example::
  79. --program "launch --type=tab vim"
  80. Can be specified multiple times to run multiple programs.
  81. --type
  82. default=url
  83. choices=url,regex,path,line,hash,word,linenum,hyperlink,ip
  84. The type of text to search for. A value of :code:`linenum` is special, it looks
  85. for error messages using the pattern specified with :option:`--regex`, which
  86. must have the named groups: :code:`path` and :code:`line`. If not specified,
  87. will look for :code:`path:line`. The :option:`--linenum-action` option
  88. controls where to display the selected error message, other options are ignored.
  89. --regex
  90. default={default_regex}
  91. The regular expression to use when option :option:`--type` is set to
  92. :code:`regex`, in Perl 5 syntax. If you specify a numbered group in the regular
  93. expression, only the group will be matched. This allow you to match text
  94. ignoring a prefix/suffix, as needed. The default expression matches lines. To
  95. match text over multiple lines, things get a little tricky, as line endings
  96. are a sequence of zero or more null bytes followed by either a carriage return
  97. or a newline character. To have a pattern match over line endings you will need to
  98. match the character set ``[\0\r\n]``. The newlines and null bytes are automatically
  99. stripped from the returned text. If you specify named groups and a
  100. :option:`--program`, then the program will be passed arguments corresponding
  101. to each named group of the form :code:`key=value`.
  102. --linenum-action
  103. default=self
  104. type=choice
  105. choices=self,window,tab,os_window,background
  106. Where to perform the action on matched errors. :code:`self` means the current
  107. window, :code:`window` a new kitty window, :code:`tab` a new tab,
  108. :code:`os_window` a new OS window and :code:`background` run in the background.
  109. The actual action is whatever arguments are provided to the kitten, for
  110. example:
  111. :code:`kitten hints --type=linenum --linenum-action=tab vim +{line} {path}`
  112. will open the matched path at the matched line number in vim in
  113. a new kitty tab. Note that in order to use :option:`--program` to copy or paste
  114. the provided arguments, you need to use the special value :code:`self`.
  115. --url-prefixes
  116. default=default
  117. Comma separated list of recognized URL prefixes. Defaults to the list of
  118. prefixes defined by the :opt:`url_prefixes` option in :file:`kitty.conf`.
  119. --url-excluded-characters
  120. default=default
  121. Characters to exclude when matching URLs. Defaults to the list of characters
  122. defined by the :opt:`url_excluded_characters` option in :file:`kitty.conf`.
  123. The syntax for this option is the same as for :opt:`url_excluded_characters`.
  124. --word-characters
  125. Characters to consider as part of a word. In addition, all characters marked as
  126. alphanumeric in the Unicode database will be considered as word characters.
  127. Defaults to the :opt:`select_by_word_characters` option from :file:`kitty.conf`.
  128. --minimum-match-length
  129. default=3
  130. type=int
  131. The minimum number of characters to consider a match.
  132. --multiple
  133. type=bool-set
  134. Select multiple matches and perform the action on all of them together at the
  135. end. In this mode, press :kbd:`Esc` to finish selecting.
  136. --multiple-joiner
  137. default=auto
  138. String for joining multiple selections when copying to the clipboard or
  139. inserting into the terminal. The special values are: :code:`space` - a space
  140. character, :code:`newline` - a newline, :code:`empty` - an empty joiner,
  141. :code:`json` - a JSON serialized list, :code:`auto` - an automatic choice, based
  142. on the type of text being selected. In addition, integers are interpreted as
  143. zero-based indices into the list of selections. You can use :code:`0` for the
  144. first selection and :code:`-1` for the last.
  145. --add-trailing-space
  146. default=auto
  147. choices=auto,always,never
  148. Add trailing space after matched text. Defaults to :code:`auto`, which adds the
  149. space when used together with :option:`--multiple`.
  150. --hints-offset
  151. default=1
  152. type=int
  153. The offset (from zero) at which to start hint numbering. Note that only numbers
  154. greater than or equal to zero are respected.
  155. --alphabet
  156. The list of characters to use for hints. The default is to use numbers and
  157. lowercase English alphabets. Specify your preference as a string of characters.
  158. Note that you need to specify the :option:`--hints-offset` as zero to use the
  159. first character to highlight the first match, otherwise it will start with the
  160. second character by default.
  161. --ascending
  162. type=bool-set
  163. Make the hints increase from top to bottom, instead of decreasing from top to
  164. bottom.
  165. --hints-foreground-color
  166. default=black
  167. type=str
  168. The foreground color for hints. You can use color names or hex values. For the eight basic
  169. named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
  170. color.
  171. --hints-background-color
  172. default=green
  173. type=str
  174. The background color for hints. You can use color names or hex values. For the eight basic
  175. named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
  176. color.
  177. --hints-text-color
  178. default=auto
  179. type=str
  180. The foreground color for text pointed to by the hints. You can use color names or hex values. For the eight basic
  181. named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
  182. color. The default is to pick a suitable color automatically.
  183. --customize-processing
  184. Name of a python file in the kitty config directory which will be imported to
  185. provide custom implementations for pattern finding and performing actions
  186. on selected matches. You can also specify absolute paths to load the script from
  187. elsewhere. See {hints_url} for details.
  188. --window-title
  189. The title for the hints window, default title is based on the type of text being
  190. hinted.
  191. '''.format(
  192. default_regex=DEFAULT_REGEX,
  193. line='{{line}}', path='{{path}}',
  194. hints_url=website_url('kittens/hints'),
  195. ).format
  196. help_text = 'Select text from the screen using the keyboard. Defaults to searching for URLs.'
  197. usage = ''
  198. def main(args: list[str]) -> dict[str, Any] | None:
  199. raise SystemExit('Should be run as kitten hints')
  200. def linenum_process_result(data: dict[str, Any]) -> tuple[str, int]:
  201. for match, g in zip(data['match'], data['groupdicts']):
  202. path, line = g['path'], g['line']
  203. if path and line:
  204. return path, int(line)
  205. return '', -1
  206. def linenum_handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType, extra_cli_args: Sequence[str], *a: Any) -> None:
  207. path, line = linenum_process_result(data)
  208. if not path:
  209. return
  210. if extra_cli_args:
  211. cmd = [x.format(path=path, line=line) for x in extra_cli_args]
  212. else:
  213. cmd = get_editor(path_to_edit=path, line_number=line)
  214. w = boss.window_id_map.get(target_window_id)
  215. action = data['linenum_action']
  216. if action == 'self':
  217. if w is not None:
  218. def is_copy_action(s: str) -> bool:
  219. return s in ('-', '@', '*') or s.startswith('@')
  220. programs = list(filter(is_copy_action, data['programs'] or ()))
  221. # keep for backward compatibility, previously option `--program` does not need to be specified to perform copy actions
  222. if is_copy_action(cmd[0]):
  223. programs.append(cmd.pop(0))
  224. if programs:
  225. text = ' '.join(cmd)
  226. for program in programs:
  227. if program == '-':
  228. w.paste_bytes(text)
  229. elif program == '@':
  230. set_clipboard_string(text)
  231. elif program == '*':
  232. set_primary_selection(text)
  233. elif program.startswith('@'):
  234. boss.set_clipboard_buffer(program[1:], text)
  235. else:
  236. import shlex
  237. text = shlex.join(cmd)
  238. w.paste_bytes(f'{text}\r')
  239. elif action == 'background':
  240. import subprocess
  241. subprocess.Popen(cmd, cwd=data['cwd'])
  242. else:
  243. getattr(boss, {
  244. 'window': 'new_window_with_cwd', 'tab': 'new_tab_with_cwd', 'os_window': 'new_os_window_with_cwd'
  245. }[action])(*cmd)
  246. def on_mark_clicked(boss: BossType, window: WindowType, url: str, hyperlink_id: int, cwd: str) -> bool:
  247. if url.startswith('mark:'):
  248. window.send_cmd_response({'Type': 'mark_activated', 'Mark': int(url[5:])})
  249. return True
  250. return False
  251. @result_handler(type_of_input='screen-ansi', has_ready_notification=True, open_url_handler=on_mark_clicked)
  252. def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
  253. cp = data['customize_processing']
  254. if data['type'] == 'linenum':
  255. cp = '::linenum::'
  256. if cp:
  257. m = load_custom_processor(cp)
  258. if 'handle_result' in m:
  259. m['handle_result'](args, data, target_window_id, boss, data['extra_cli_args'])
  260. return None
  261. programs = data['programs'] or ('default',)
  262. matches: list[str] = []
  263. groupdicts = []
  264. for m, g in zip(data['match'], data['groupdicts']):
  265. if m:
  266. matches.append(m)
  267. groupdicts.append(g)
  268. joiner = data['multiple_joiner']
  269. try:
  270. is_int: int | None = int(joiner)
  271. except Exception:
  272. is_int = None
  273. text_type = data['type']
  274. @lru_cache
  275. def joined_text() -> str:
  276. if is_int is not None:
  277. try:
  278. return matches[is_int]
  279. except IndexError:
  280. return matches[-1]
  281. if joiner == 'json':
  282. import json
  283. return json.dumps(matches, ensure_ascii=False, indent='\t')
  284. if joiner == 'auto':
  285. q = '\n\r' if text_type in ('line', 'url') else ' '
  286. else:
  287. q = {'newline': '\n\r', 'space': ' '}.get(joiner, '')
  288. return q.join(matches)
  289. for program in programs:
  290. if program == '-':
  291. w = boss.window_id_map.get(target_window_id)
  292. if w is not None:
  293. w.paste_text(joined_text())
  294. elif program == '*':
  295. set_primary_selection(joined_text())
  296. elif program.startswith('@'):
  297. if program == '@':
  298. set_clipboard_string(joined_text())
  299. else:
  300. boss.set_clipboard_buffer(program[1:], joined_text())
  301. else:
  302. from kitty.conf.utils import to_cmdline
  303. cwd = data['cwd']
  304. is_default_program = program == 'default'
  305. program = get_options().open_url_with if is_default_program else program
  306. if text_type == 'hyperlink' and is_default_program:
  307. w = boss.window_id_map.get(target_window_id)
  308. for m in matches:
  309. if w is not None:
  310. w.open_url(m, hyperlink_id=1, cwd=cwd)
  311. else:
  312. launch_args = []
  313. if isinstance(program, str) and program.startswith('launch '):
  314. launch_args = to_cmdline(program)
  315. launch_args.insert(1, '--cwd=' + cwd)
  316. for m, groupdict in zip(matches, groupdicts):
  317. if groupdict:
  318. m = []
  319. for k, v in groupdict.items():
  320. m.append('{}={}'.format(k, v or ''))
  321. if launch_args:
  322. w = boss.window_id_map.get(target_window_id)
  323. boss.call_remote_control(self_window=w, args=tuple(launch_args + ([m] if isinstance(m, str) else m)))
  324. else:
  325. boss.open_url(m, program, cwd=cwd)
  326. if __name__ == '__main__':
  327. # Run with kitty +kitten hints
  328. ans = main(sys.argv)
  329. if ans:
  330. print(ans)
  331. elif __name__ == '__doc__':
  332. cd = sys.cli_docs # type: ignore
  333. cd['usage'] = usage
  334. cd['short_desc'] = 'Select text from screen with keyboard'
  335. cd['options'] = OPTIONS
  336. cd['help_text'] = help_text
  337. # }}}