processors.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. """
  2. Processors are little transformation blocks that transform the token list from
  3. a buffer before the BufferControl will render it to the screen.
  4. They can insert tokens before or after, or highlight fragments by replacing the
  5. token types.
  6. """
  7. from __future__ import unicode_literals
  8. from abc import ABCMeta, abstractmethod
  9. from six import with_metaclass
  10. from six.moves import range
  11. from prompt_toolkit.cache import SimpleCache
  12. from prompt_toolkit.document import Document
  13. from prompt_toolkit.enums import SEARCH_BUFFER
  14. from prompt_toolkit.filters import to_cli_filter, ViInsertMultipleMode
  15. from prompt_toolkit.layout.utils import token_list_to_text
  16. from prompt_toolkit.reactive import Integer
  17. from prompt_toolkit.token import Token
  18. from .utils import token_list_len, explode_tokens
  19. import re
  20. __all__ = (
  21. 'Processor',
  22. 'Transformation',
  23. 'HighlightSearchProcessor',
  24. 'HighlightSelectionProcessor',
  25. 'PasswordProcessor',
  26. 'HighlightMatchingBracketProcessor',
  27. 'DisplayMultipleCursors',
  28. 'BeforeInput',
  29. 'AfterInput',
  30. 'AppendAutoSuggestion',
  31. 'ConditionalProcessor',
  32. 'ShowLeadingWhiteSpaceProcessor',
  33. 'ShowTrailingWhiteSpaceProcessor',
  34. 'TabsProcessor',
  35. )
  36. class Processor(with_metaclass(ABCMeta, object)):
  37. """
  38. Manipulate the tokens for a given line in a
  39. :class:`~prompt_toolkit.layout.controls.BufferControl`.
  40. """
  41. @abstractmethod
  42. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  43. """
  44. Apply transformation. Returns a :class:`.Transformation` instance.
  45. :param cli: :class:`.CommandLineInterface` instance.
  46. :param lineno: The number of the line to which we apply the processor.
  47. :param source_to_display: A function that returns the position in the
  48. `tokens` for any position in the source string. (This takes
  49. previous processors into account.)
  50. :param tokens: List of tokens that we can transform. (Received from the
  51. previous processor.)
  52. """
  53. return Transformation(tokens)
  54. def has_focus(self, cli):
  55. """
  56. Processors can override the focus.
  57. (Used for the reverse-i-search prefix in DefaultPrompt.)
  58. """
  59. return False
  60. class Transformation(object):
  61. """
  62. Transformation result, as returned by :meth:`.Processor.apply_transformation`.
  63. Important: Always make sure that the length of `document.text` is equal to
  64. the length of all the text in `tokens`!
  65. :param tokens: The transformed tokens. To be displayed, or to pass to the
  66. next processor.
  67. :param source_to_display: Cursor position transformation from original string to
  68. transformed string.
  69. :param display_to_source: Cursor position transformed from source string to
  70. original string.
  71. """
  72. def __init__(self, tokens, source_to_display=None, display_to_source=None):
  73. self.tokens = tokens
  74. self.source_to_display = source_to_display or (lambda i: i)
  75. self.display_to_source = display_to_source or (lambda i: i)
  76. class HighlightSearchProcessor(Processor):
  77. """
  78. Processor that highlights search matches in the document.
  79. Note that this doesn't support multiline search matches yet.
  80. :param preview_search: A Filter; when active it indicates that we take
  81. the search text in real time while the user is typing, instead of the
  82. last active search state.
  83. """
  84. def __init__(self, preview_search=False, search_buffer_name=SEARCH_BUFFER,
  85. get_search_state=None):
  86. self.preview_search = to_cli_filter(preview_search)
  87. self.search_buffer_name = search_buffer_name
  88. self.get_search_state = get_search_state or (lambda cli: cli.search_state)
  89. def _get_search_text(self, cli):
  90. """
  91. The text we are searching for.
  92. """
  93. # When the search buffer has focus, take that text.
  94. if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text:
  95. return cli.buffers[self.search_buffer_name].text
  96. # Otherwise, take the text of the last active search.
  97. else:
  98. return self.get_search_state(cli).text
  99. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  100. search_text = self._get_search_text(cli)
  101. searchmatch_current_token = (':', ) + Token.SearchMatch.Current
  102. searchmatch_token = (':', ) + Token.SearchMatch
  103. if search_text and not cli.is_returning:
  104. # For each search match, replace the Token.
  105. line_text = token_list_to_text(tokens)
  106. tokens = explode_tokens(tokens)
  107. flags = re.IGNORECASE if cli.is_ignoring_case else 0
  108. # Get cursor column.
  109. if document.cursor_position_row == lineno:
  110. cursor_column = source_to_display(document.cursor_position_col)
  111. else:
  112. cursor_column = None
  113. for match in re.finditer(re.escape(search_text), line_text, flags=flags):
  114. if cursor_column is not None:
  115. on_cursor = match.start() <= cursor_column < match.end()
  116. else:
  117. on_cursor = False
  118. for i in range(match.start(), match.end()):
  119. old_token, text = tokens[i]
  120. if on_cursor:
  121. tokens[i] = (old_token + searchmatch_current_token, tokens[i][1])
  122. else:
  123. tokens[i] = (old_token + searchmatch_token, tokens[i][1])
  124. return Transformation(tokens)
  125. class HighlightSelectionProcessor(Processor):
  126. """
  127. Processor that highlights the selection in the document.
  128. """
  129. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  130. selected_token = (':', ) + Token.SelectedText
  131. # In case of selection, highlight all matches.
  132. selection_at_line = document.selection_range_at_line(lineno)
  133. if selection_at_line:
  134. from_, to = selection_at_line
  135. from_ = source_to_display(from_)
  136. to = source_to_display(to)
  137. tokens = explode_tokens(tokens)
  138. if from_ == 0 and to == 0 and len(tokens) == 0:
  139. # When this is an empty line, insert a space in order to
  140. # visualiase the selection.
  141. return Transformation([(Token.SelectedText, ' ')])
  142. else:
  143. for i in range(from_, to + 1):
  144. if i < len(tokens):
  145. old_token, old_text = tokens[i]
  146. tokens[i] = (old_token + selected_token, old_text)
  147. return Transformation(tokens)
  148. class PasswordProcessor(Processor):
  149. """
  150. Processor that turns masks the input. (For passwords.)
  151. :param char: (string) Character to be used. "*" by default.
  152. """
  153. def __init__(self, char='*'):
  154. self.char = char
  155. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  156. tokens = [(token, self.char * len(text)) for token, text in tokens]
  157. return Transformation(tokens)
  158. class HighlightMatchingBracketProcessor(Processor):
  159. """
  160. When the cursor is on or right after a bracket, it highlights the matching
  161. bracket.
  162. :param max_cursor_distance: Only highlight matching brackets when the
  163. cursor is within this distance. (From inside a `Processor`, we can't
  164. know which lines will be visible on the screen. But we also don't want
  165. to scan the whole document for matching brackets on each key press, so
  166. we limit to this value.)
  167. """
  168. _closing_braces = '])}>'
  169. def __init__(self, chars='[](){}<>', max_cursor_distance=1000):
  170. self.chars = chars
  171. self.max_cursor_distance = max_cursor_distance
  172. self._positions_cache = SimpleCache(maxsize=8)
  173. def _get_positions_to_highlight(self, document):
  174. """
  175. Return a list of (row, col) tuples that need to be highlighted.
  176. """
  177. # Try for the character under the cursor.
  178. if document.current_char and document.current_char in self.chars:
  179. pos = document.find_matching_bracket_position(
  180. start_pos=document.cursor_position - self.max_cursor_distance,
  181. end_pos=document.cursor_position + self.max_cursor_distance)
  182. # Try for the character before the cursor.
  183. elif (document.char_before_cursor and document.char_before_cursor in
  184. self._closing_braces and document.char_before_cursor in self.chars):
  185. document = Document(document.text, document.cursor_position - 1)
  186. pos = document.find_matching_bracket_position(
  187. start_pos=document.cursor_position - self.max_cursor_distance,
  188. end_pos=document.cursor_position + self.max_cursor_distance)
  189. else:
  190. pos = None
  191. # Return a list of (row, col) tuples that need to be highlighted.
  192. if pos:
  193. pos += document.cursor_position # pos is relative.
  194. row, col = document.translate_index_to_position(pos)
  195. return [(row, col), (document.cursor_position_row, document.cursor_position_col)]
  196. else:
  197. return []
  198. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  199. # Get the highlight positions.
  200. key = (cli.render_counter, document.text, document.cursor_position)
  201. positions = self._positions_cache.get(
  202. key, lambda: self._get_positions_to_highlight(document))
  203. # Apply if positions were found at this line.
  204. if positions:
  205. for row, col in positions:
  206. if row == lineno:
  207. col = source_to_display(col)
  208. tokens = explode_tokens(tokens)
  209. token, text = tokens[col]
  210. if col == document.cursor_position_col:
  211. token += (':', ) + Token.MatchingBracket.Cursor
  212. else:
  213. token += (':', ) + Token.MatchingBracket.Other
  214. tokens[col] = (token, text)
  215. return Transformation(tokens)
  216. class DisplayMultipleCursors(Processor):
  217. """
  218. When we're in Vi block insert mode, display all the cursors.
  219. """
  220. _insert_multiple = ViInsertMultipleMode()
  221. def __init__(self, buffer_name):
  222. self.buffer_name = buffer_name
  223. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  224. buff = cli.buffers[self.buffer_name]
  225. if self._insert_multiple(cli):
  226. positions = buff.multiple_cursor_positions
  227. tokens = explode_tokens(tokens)
  228. # If any cursor appears on the current line, highlight that.
  229. start_pos = document.translate_row_col_to_index(lineno, 0)
  230. end_pos = start_pos + len(document.lines[lineno])
  231. token_suffix = (':', ) + Token.MultipleCursors.Cursor
  232. for p in positions:
  233. if start_pos <= p < end_pos:
  234. column = source_to_display(p - start_pos)
  235. # Replace token.
  236. token, text = tokens[column]
  237. token += token_suffix
  238. tokens[column] = (token, text)
  239. elif p == end_pos:
  240. tokens.append((token_suffix, ' '))
  241. return Transformation(tokens)
  242. else:
  243. return Transformation(tokens)
  244. class BeforeInput(Processor):
  245. """
  246. Insert tokens before the input.
  247. :param get_tokens: Callable that takes a
  248. :class:`~prompt_toolkit.interface.CommandLineInterface` and returns the
  249. list of tokens to be inserted.
  250. """
  251. def __init__(self, get_tokens):
  252. assert callable(get_tokens)
  253. self.get_tokens = get_tokens
  254. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  255. if lineno == 0:
  256. tokens_before = self.get_tokens(cli)
  257. tokens = tokens_before + tokens
  258. shift_position = token_list_len(tokens_before)
  259. source_to_display = lambda i: i + shift_position
  260. display_to_source = lambda i: i - shift_position
  261. else:
  262. source_to_display = None
  263. display_to_source = None
  264. return Transformation(tokens, source_to_display=source_to_display,
  265. display_to_source=display_to_source)
  266. @classmethod
  267. def static(cls, text, token=Token):
  268. """
  269. Create a :class:`.BeforeInput` instance that always inserts the same
  270. text.
  271. """
  272. def get_static_tokens(cli):
  273. return [(token, text)]
  274. return cls(get_static_tokens)
  275. def __repr__(self):
  276. return '%s(get_tokens=%r)' % (
  277. self.__class__.__name__, self.get_tokens)
  278. class AfterInput(Processor):
  279. """
  280. Insert tokens after the input.
  281. :param get_tokens: Callable that takes a
  282. :class:`~prompt_toolkit.interface.CommandLineInterface` and returns the
  283. list of tokens to be appended.
  284. """
  285. def __init__(self, get_tokens):
  286. assert callable(get_tokens)
  287. self.get_tokens = get_tokens
  288. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  289. # Insert tokens after the last line.
  290. if lineno == document.line_count - 1:
  291. return Transformation(tokens=tokens + self.get_tokens(cli))
  292. else:
  293. return Transformation(tokens=tokens)
  294. @classmethod
  295. def static(cls, text, token=Token):
  296. """
  297. Create a :class:`.AfterInput` instance that always inserts the same
  298. text.
  299. """
  300. def get_static_tokens(cli):
  301. return [(token, text)]
  302. return cls(get_static_tokens)
  303. def __repr__(self):
  304. return '%s(get_tokens=%r)' % (
  305. self.__class__.__name__, self.get_tokens)
  306. class AppendAutoSuggestion(Processor):
  307. """
  308. Append the auto suggestion to the input.
  309. (The user can then press the right arrow the insert the suggestion.)
  310. :param buffer_name: The name of the buffer from where we should take the
  311. auto suggestion. If not given, we take the current buffer.
  312. """
  313. def __init__(self, buffer_name=None, token=Token.AutoSuggestion):
  314. self.buffer_name = buffer_name
  315. self.token = token
  316. def _get_buffer(self, cli):
  317. if self.buffer_name:
  318. return cli.buffers[self.buffer_name]
  319. else:
  320. return cli.current_buffer
  321. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  322. # Insert tokens after the last line.
  323. if lineno == document.line_count - 1:
  324. buffer = self._get_buffer(cli)
  325. if buffer.suggestion and buffer.document.is_cursor_at_the_end:
  326. suggestion = buffer.suggestion.text
  327. else:
  328. suggestion = ''
  329. return Transformation(tokens=tokens + [(self.token, suggestion)])
  330. else:
  331. return Transformation(tokens=tokens)
  332. class ShowLeadingWhiteSpaceProcessor(Processor):
  333. """
  334. Make leading whitespace visible.
  335. :param get_char: Callable that takes a :class:`CommandLineInterface`
  336. instance and returns one character.
  337. :param token: Token to be used.
  338. """
  339. def __init__(self, get_char=None, token=Token.LeadingWhiteSpace):
  340. assert get_char is None or callable(get_char)
  341. if get_char is None:
  342. def get_char(cli):
  343. if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
  344. return '.'
  345. else:
  346. return '\xb7'
  347. self.token = token
  348. self.get_char = get_char
  349. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  350. # Walk through all te tokens.
  351. if tokens and token_list_to_text(tokens).startswith(' '):
  352. t = (self.token, self.get_char(cli))
  353. tokens = explode_tokens(tokens)
  354. for i in range(len(tokens)):
  355. if tokens[i][1] == ' ':
  356. tokens[i] = t
  357. else:
  358. break
  359. return Transformation(tokens)
  360. class ShowTrailingWhiteSpaceProcessor(Processor):
  361. """
  362. Make trailing whitespace visible.
  363. :param get_char: Callable that takes a :class:`CommandLineInterface`
  364. instance and returns one character.
  365. :param token: Token to be used.
  366. """
  367. def __init__(self, get_char=None, token=Token.TrailingWhiteSpace):
  368. assert get_char is None or callable(get_char)
  369. if get_char is None:
  370. def get_char(cli):
  371. if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
  372. return '.'
  373. else:
  374. return '\xb7'
  375. self.token = token
  376. self.get_char = get_char
  377. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  378. if tokens and tokens[-1][1].endswith(' '):
  379. t = (self.token, self.get_char(cli))
  380. tokens = explode_tokens(tokens)
  381. # Walk backwards through all te tokens and replace whitespace.
  382. for i in range(len(tokens) - 1, -1, -1):
  383. char = tokens[i][1]
  384. if char == ' ':
  385. tokens[i] = t
  386. else:
  387. break
  388. return Transformation(tokens)
  389. class TabsProcessor(Processor):
  390. """
  391. Render tabs as spaces (instead of ^I) or make them visible (for instance,
  392. by replacing them with dots.)
  393. :param tabstop: (Integer) Horizontal space taken by a tab.
  394. :param get_char1: Callable that takes a `CommandLineInterface` and return a
  395. character (text of length one). This one is used for the first space
  396. taken by the tab.
  397. :param get_char2: Like `get_char1`, but for the rest of the space.
  398. """
  399. def __init__(self, tabstop=4, get_char1=None, get_char2=None, token=Token.Tab):
  400. assert isinstance(tabstop, Integer)
  401. assert get_char1 is None or callable(get_char1)
  402. assert get_char2 is None or callable(get_char2)
  403. self.get_char1 = get_char1 or get_char2 or (lambda cli: '|')
  404. self.get_char2 = get_char2 or get_char1 or (lambda cli: '\u2508')
  405. self.tabstop = tabstop
  406. self.token = token
  407. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  408. tabstop = int(self.tabstop)
  409. token = self.token
  410. # Create separator for tabs.
  411. separator1 = self.get_char1(cli)
  412. separator2 = self.get_char2(cli)
  413. # Transform tokens.
  414. tokens = explode_tokens(tokens)
  415. position_mappings = {}
  416. result_tokens = []
  417. pos = 0
  418. for i, token_and_text in enumerate(tokens):
  419. position_mappings[i] = pos
  420. if token_and_text[1] == '\t':
  421. # Calculate how many characters we have to insert.
  422. count = tabstop - (pos % tabstop)
  423. if count == 0:
  424. count = tabstop
  425. # Insert tab.
  426. result_tokens.append((token, separator1))
  427. result_tokens.append((token, separator2 * (count - 1)))
  428. pos += count
  429. else:
  430. result_tokens.append(token_and_text)
  431. pos += 1
  432. position_mappings[len(tokens)] = pos
  433. def source_to_display(from_position):
  434. " Maps original cursor position to the new one. "
  435. return position_mappings[from_position]
  436. def display_to_source(display_pos):
  437. " Maps display cursor position to the original one. "
  438. position_mappings_reversed = dict((v, k) for k, v in position_mappings.items())
  439. while display_pos >= 0:
  440. try:
  441. return position_mappings_reversed[display_pos]
  442. except KeyError:
  443. display_pos -= 1
  444. return 0
  445. return Transformation(
  446. result_tokens,
  447. source_to_display=source_to_display,
  448. display_to_source=display_to_source)
  449. class ConditionalProcessor(Processor):
  450. """
  451. Processor that applies another processor, according to a certain condition.
  452. Example::
  453. # Create a function that returns whether or not the processor should
  454. # currently be applied.
  455. def highlight_enabled(cli):
  456. return true_or_false
  457. # Wrapt it in a `ConditionalProcessor` for usage in a `BufferControl`.
  458. BufferControl(input_processors=[
  459. ConditionalProcessor(HighlightSearchProcessor(),
  460. Condition(highlight_enabled))])
  461. :param processor: :class:`.Processor` instance.
  462. :param filter: :class:`~prompt_toolkit.filters.CLIFilter` instance.
  463. """
  464. def __init__(self, processor, filter):
  465. assert isinstance(processor, Processor)
  466. self.processor = processor
  467. self.filter = to_cli_filter(filter)
  468. def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
  469. # Run processor when enabled.
  470. if self.filter(cli):
  471. return self.processor.apply_transformation(
  472. cli, document, lineno, source_to_display, tokens)
  473. else:
  474. return Transformation(tokens)
  475. def has_focus(self, cli):
  476. if self.filter(cli):
  477. return self.processor.has_focus(cli)
  478. else:
  479. return False
  480. def __repr__(self):
  481. return '%s(processor=%r, filter=%r)' % (
  482. self.__class__.__name__, self.processor, self.filter)