main.py 15 KB

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