interface.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. """
  2. The main `CommandLineInterface` class and logic.
  3. """
  4. from __future__ import unicode_literals
  5. import functools
  6. import os
  7. import signal
  8. import six
  9. import sys
  10. import textwrap
  11. import threading
  12. import time
  13. import types
  14. import weakref
  15. from subprocess import Popen
  16. from .application import Application, AbortAction
  17. from .buffer import Buffer
  18. from .buffer_mapping import BufferMapping
  19. from .completion import CompleteEvent, get_common_complete_suffix
  20. from .enums import SEARCH_BUFFER
  21. from .eventloop.base import EventLoop
  22. from .eventloop.callbacks import EventLoopCallbacks
  23. from .filters import Condition
  24. from .input import StdinInput, Input
  25. from .key_binding.input_processor import InputProcessor
  26. from .key_binding.input_processor import KeyPress
  27. from .key_binding.registry import Registry
  28. from .key_binding.vi_state import ViState
  29. from .keys import Keys
  30. from .output import Output
  31. from .renderer import Renderer, print_tokens
  32. from .search_state import SearchState
  33. from .utils import Event
  34. # Following import is required for backwards compatibility.
  35. from .buffer import AcceptAction
  36. __all__ = (
  37. 'AbortAction',
  38. 'CommandLineInterface',
  39. )
  40. class CommandLineInterface(object):
  41. """
  42. Wrapper around all the other classes, tying everything together.
  43. Typical usage::
  44. application = Application(...)
  45. cli = CommandLineInterface(application, eventloop)
  46. result = cli.run()
  47. print(result)
  48. :param application: :class:`~prompt_toolkit.application.Application` instance.
  49. :param eventloop: The :class:`~prompt_toolkit.eventloop.base.EventLoop` to
  50. be used when `run` is called. The easiest way to create
  51. an eventloop is by calling
  52. :meth:`~prompt_toolkit.shortcuts.create_eventloop`.
  53. :param input: :class:`~prompt_toolkit.input.Input` instance.
  54. :param output: :class:`~prompt_toolkit.output.Output` instance. (Probably
  55. Vt100_Output or Win32Output.)
  56. """
  57. def __init__(self, application, eventloop=None, input=None, output=None):
  58. assert isinstance(application, Application)
  59. assert isinstance(eventloop, EventLoop), 'Passing an eventloop is required.'
  60. assert output is None or isinstance(output, Output)
  61. assert input is None or isinstance(input, Input)
  62. from .shortcuts import create_output
  63. self.application = application
  64. self.eventloop = eventloop
  65. self._is_running = False
  66. # Inputs and outputs.
  67. self.output = output or create_output()
  68. self.input = input or StdinInput(sys.stdin)
  69. #: The input buffers.
  70. assert isinstance(application.buffers, BufferMapping)
  71. self.buffers = application.buffers
  72. #: EditingMode.VI or EditingMode.EMACS
  73. self.editing_mode = application.editing_mode
  74. #: Quoted insert. This flag is set if we go into quoted insert mode.
  75. self.quoted_insert = False
  76. #: Vi state. (For Vi key bindings.)
  77. self.vi_state = ViState()
  78. #: The `Renderer` instance.
  79. # Make sure that the same stdout is used, when a custom renderer has been passed.
  80. self.renderer = Renderer(
  81. self.application.style,
  82. self.output,
  83. use_alternate_screen=application.use_alternate_screen,
  84. mouse_support=application.mouse_support)
  85. #: Render counter. This one is increased every time the UI is rendered.
  86. #: It can be used as a key for caching certain information during one
  87. #: rendering.
  88. self.render_counter = 0
  89. #: When there is high CPU, postpone the renderering max x seconds.
  90. #: '0' means: don't postpone. '.5' means: try to draw at least twice a second.
  91. self.max_render_postpone_time = 0 # E.g. .5
  92. # Invalidate flag. When 'True', a repaint has been scheduled.
  93. self._invalidated = False
  94. #: The `InputProcessor` instance.
  95. self.input_processor = InputProcessor(application.key_bindings_registry, weakref.ref(self))
  96. self._async_completers = {} # Map buffer name to completer function.
  97. # Pointer to sub CLI. (In chain of CLI instances.)
  98. self._sub_cli = None # None or other CommandLineInterface instance.
  99. # Call `add_buffer` for each buffer.
  100. for name, b in self.buffers.items():
  101. self.add_buffer(name, b)
  102. # Events.
  103. self.on_buffer_changed = Event(self, application.on_buffer_changed)
  104. self.on_initialize = Event(self, application.on_initialize)
  105. self.on_input_timeout = Event(self, application.on_input_timeout)
  106. self.on_invalidate = Event(self, application.on_invalidate)
  107. self.on_render = Event(self, application.on_render)
  108. self.on_reset = Event(self, application.on_reset)
  109. self.on_start = Event(self, application.on_start)
  110. self.on_stop = Event(self, application.on_stop)
  111. # Trigger initialize callback.
  112. self.reset()
  113. self.on_initialize += self.application.on_initialize
  114. self.on_initialize.fire()
  115. @property
  116. def layout(self):
  117. return self.application.layout
  118. @property
  119. def clipboard(self):
  120. return self.application.clipboard
  121. @property
  122. def pre_run_callables(self):
  123. return self.application.pre_run_callables
  124. def add_buffer(self, name, buffer, focus=False):
  125. """
  126. Insert a new buffer.
  127. """
  128. assert isinstance(buffer, Buffer)
  129. self.buffers[name] = buffer
  130. if focus:
  131. self.buffers.focus(name)
  132. # Create asynchronous completer / auto suggestion.
  133. auto_suggest_function = self._create_auto_suggest_function(buffer)
  134. completer_function = self._create_async_completer(buffer)
  135. self._async_completers[name] = completer_function
  136. # Complete/suggest on text insert.
  137. def create_on_insert_handler():
  138. """
  139. Wrapper around the asynchronous completer and auto suggestion, that
  140. ensures that it's only called while typing if the
  141. `complete_while_typing` filter is enabled.
  142. """
  143. def on_text_insert(_):
  144. # Only complete when "complete_while_typing" is enabled.
  145. if buffer.completer and buffer.complete_while_typing():
  146. completer_function()
  147. # Call auto_suggest.
  148. if buffer.auto_suggest:
  149. auto_suggest_function()
  150. return on_text_insert
  151. buffer.on_text_insert += create_on_insert_handler()
  152. def buffer_changed(_):
  153. """
  154. When the text in a buffer changes.
  155. (A paste event is also a change, but not an insert. So we don't
  156. want to do autocompletions in this case, but we want to propagate
  157. the on_buffer_changed event.)
  158. """
  159. # Trigger on_buffer_changed.
  160. self.on_buffer_changed.fire()
  161. buffer.on_text_changed += buffer_changed
  162. def start_completion(self, buffer_name=None, select_first=False,
  163. select_last=False, insert_common_part=False,
  164. complete_event=None):
  165. """
  166. Start asynchronous autocompletion of this buffer.
  167. (This will do nothing if a previous completion was still in progress.)
  168. """
  169. buffer_name = buffer_name or self.current_buffer_name
  170. completer = self._async_completers.get(buffer_name)
  171. if completer:
  172. completer(select_first=select_first,
  173. select_last=select_last,
  174. insert_common_part=insert_common_part,
  175. complete_event=CompleteEvent(completion_requested=True))
  176. @property
  177. def current_buffer_name(self):
  178. """
  179. The name of the current :class:`.Buffer`. (Or `None`.)
  180. """
  181. return self.buffers.current_name(self)
  182. @property
  183. def current_buffer(self):
  184. """
  185. The currently focussed :class:`~.Buffer`.
  186. (This returns a dummy :class:`.Buffer` when none of the actual buffers
  187. has the focus. In this case, it's really not practical to check for
  188. `None` values or catch exceptions every time.)
  189. """
  190. return self.buffers.current(self)
  191. def focus(self, buffer_name):
  192. """
  193. Focus the buffer with the given name on the focus stack.
  194. """
  195. self.buffers.focus(self, buffer_name)
  196. def push_focus(self, buffer_name):
  197. """
  198. Push to the focus stack.
  199. """
  200. self.buffers.push_focus(self, buffer_name)
  201. def pop_focus(self):
  202. """
  203. Pop from the focus stack.
  204. """
  205. self.buffers.pop_focus(self)
  206. @property
  207. def terminal_title(self):
  208. """
  209. Return the current title to be displayed in the terminal.
  210. When this in `None`, the terminal title remains the original.
  211. """
  212. result = self.application.get_title()
  213. # Make sure that this function returns a unicode object,
  214. # and not a byte string.
  215. assert result is None or isinstance(result, six.text_type)
  216. return result
  217. @property
  218. def is_searching(self):
  219. """
  220. True when we are searching.
  221. """
  222. return self.current_buffer_name == SEARCH_BUFFER
  223. def reset(self, reset_current_buffer=False):
  224. """
  225. Reset everything, for reading the next input.
  226. :param reset_current_buffer: XXX: not used anymore. The reason for
  227. having this option in the past was when this CommandLineInterface
  228. is run multiple times, that we could reset the buffer content from
  229. the previous run. This is now handled in the AcceptAction.
  230. """
  231. # Notice that we don't reset the buffers. (This happens just before
  232. # returning, and when we have multiple buffers, we clearly want the
  233. # content in the other buffers to remain unchanged between several
  234. # calls of `run`. (And the same is true for the focus stack.)
  235. self._exit_flag = False
  236. self._abort_flag = False
  237. self._return_value = None
  238. self.renderer.reset()
  239. self.input_processor.reset()
  240. self.layout.reset()
  241. self.vi_state.reset()
  242. # Search new search state. (Does also remember what has to be
  243. # highlighted.)
  244. self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case))
  245. # Trigger reset event.
  246. self.on_reset.fire()
  247. @property
  248. def in_paste_mode(self):
  249. """ True when we are in paste mode. """
  250. return self.application.paste_mode(self)
  251. @property
  252. def is_ignoring_case(self):
  253. """ True when we currently ignore casing. """
  254. return self.application.ignore_case(self)
  255. def invalidate(self):
  256. """
  257. Thread safe way of sending a repaint trigger to the input event loop.
  258. """
  259. # Never schedule a second redraw, when a previous one has not yet been
  260. # executed. (This should protect against other threads calling
  261. # 'invalidate' many times, resulting in 100% CPU.)
  262. if self._invalidated:
  263. return
  264. else:
  265. self._invalidated = True
  266. # Trigger event.
  267. self.on_invalidate.fire()
  268. if self.eventloop is not None:
  269. def redraw():
  270. self._invalidated = False
  271. self._redraw()
  272. # Call redraw in the eventloop (thread safe).
  273. # Usually with the high priority, in order to make the application
  274. # feel responsive, but this can be tuned by changing the value of
  275. # `max_render_postpone_time`.
  276. if self.max_render_postpone_time:
  277. _max_postpone_until = time.time() + self.max_render_postpone_time
  278. else:
  279. _max_postpone_until = None
  280. self.eventloop.call_from_executor(
  281. redraw, _max_postpone_until=_max_postpone_until)
  282. # Depracated alias for 'invalidate'.
  283. request_redraw = invalidate
  284. def _redraw(self):
  285. """
  286. Render the command line again. (Not thread safe!) (From other threads,
  287. or if unsure, use :meth:`.CommandLineInterface.invalidate`.)
  288. """
  289. # Only draw when no sub application was started.
  290. if self._is_running and self._sub_cli is None:
  291. self.render_counter += 1
  292. self.renderer.render(self, self.layout, is_done=self.is_done)
  293. # Fire render event.
  294. self.on_render.fire()
  295. def _on_resize(self):
  296. """
  297. When the window size changes, we erase the current output and request
  298. again the cursor position. When the CPR answer arrives, the output is
  299. drawn again.
  300. """
  301. # Erase, request position (when cursor is at the start position)
  302. # and redraw again. -- The order is important.
  303. self.renderer.erase(leave_alternate_screen=False, erase_title=False)
  304. self.renderer.request_absolute_cursor_position()
  305. self._redraw()
  306. def _load_next_buffer_indexes(self):
  307. for buff, index in self._next_buffer_indexes.items():
  308. if buff in self.buffers:
  309. self.buffers[buff].working_index = index
  310. def _pre_run(self, pre_run=None):
  311. " Called during `run`. "
  312. if pre_run:
  313. pre_run()
  314. # Process registered "pre_run_callables" and clear list.
  315. for c in self.pre_run_callables:
  316. c()
  317. del self.pre_run_callables[:]
  318. def run(self, reset_current_buffer=False, pre_run=None):
  319. """
  320. Read input from the command line.
  321. This runs the eventloop until a return value has been set.
  322. :param reset_current_buffer: XXX: Not used anymore.
  323. :param pre_run: Callable that is called right after the reset has taken
  324. place. This allows custom initialisation.
  325. """
  326. assert pre_run is None or callable(pre_run)
  327. try:
  328. self._is_running = True
  329. self.on_start.fire()
  330. self.reset()
  331. # Call pre_run.
  332. self._pre_run(pre_run)
  333. # Run eventloop in raw mode.
  334. with self.input.raw_mode():
  335. self.renderer.request_absolute_cursor_position()
  336. self._redraw()
  337. self.eventloop.run(self.input, self.create_eventloop_callbacks())
  338. finally:
  339. # Clean up renderer. (This will leave the alternate screen, if we use
  340. # that.)
  341. # If exit/abort haven't been called set, but another exception was
  342. # thrown instead for some reason, make sure that we redraw in exit
  343. # mode.
  344. if not self.is_done:
  345. self._exit_flag = True
  346. self._redraw()
  347. self.renderer.reset()
  348. self.on_stop.fire()
  349. self._is_running = False
  350. # Return result.
  351. return self.return_value()
  352. try:
  353. # The following `run_async` function is compiled at runtime
  354. # because it contains syntax which is not supported on older Python
  355. # versions. (A 'return' inside a generator.)
  356. six.exec_(textwrap.dedent('''
  357. def run_async(self, reset_current_buffer=True, pre_run=None):
  358. """
  359. Same as `run`, but this returns a coroutine.
  360. This is only available on Python >3.3, with asyncio.
  361. """
  362. # Inline import, because it slows down startup when asyncio is not
  363. # needed.
  364. import asyncio
  365. @asyncio.coroutine
  366. def run():
  367. assert pre_run is None or callable(pre_run)
  368. try:
  369. self._is_running = True
  370. self.on_start.fire()
  371. self.reset()
  372. # Call pre_run.
  373. self._pre_run(pre_run)
  374. with self.input.raw_mode():
  375. self.renderer.request_absolute_cursor_position()
  376. self._redraw()
  377. yield from self.eventloop.run_as_coroutine(
  378. self.input, self.create_eventloop_callbacks())
  379. return self.return_value()
  380. finally:
  381. if not self.is_done:
  382. self._exit_flag = True
  383. self._redraw()
  384. self.renderer.reset()
  385. self.on_stop.fire()
  386. self._is_running = False
  387. return run()
  388. '''))
  389. except SyntaxError:
  390. # Python2, or early versions of Python 3.
  391. def run_async(self, reset_current_buffer=True, pre_run=None):
  392. """
  393. Same as `run`, but this returns a coroutine.
  394. This is only available on Python >3.3, with asyncio.
  395. """
  396. raise NotImplementedError
  397. def run_sub_application(self, application, done_callback=None, erase_when_done=False,
  398. _from_application_generator=False):
  399. # `erase_when_done` is deprecated, set Application.erase_when_done instead.
  400. """
  401. Run a sub :class:`~prompt_toolkit.application.Application`.
  402. This will suspend the main application and display the sub application
  403. until that one returns a value. The value is returned by calling
  404. `done_callback` with the result.
  405. The sub application will share the same I/O of the main application.
  406. That means, it uses the same input and output channels and it shares
  407. the same event loop.
  408. .. note:: Technically, it gets another Eventloop instance, but that is
  409. only a proxy to our main event loop. The reason is that calling
  410. 'stop' --which returns the result of an application when it's
  411. done-- is handled differently.
  412. """
  413. assert isinstance(application, Application)
  414. assert done_callback is None or callable(done_callback)
  415. if self._sub_cli is not None:
  416. raise RuntimeError('Another sub application started already.')
  417. # Erase current application.
  418. if not _from_application_generator:
  419. self.renderer.erase()
  420. # Callback when the sub app is done.
  421. def done():
  422. # Redraw sub app in done state.
  423. # and reset the renderer. (This reset will also quit the alternate
  424. # screen, if the sub application used that.)
  425. sub_cli._redraw()
  426. if erase_when_done or application.erase_when_done:
  427. sub_cli.renderer.erase()
  428. sub_cli.renderer.reset()
  429. sub_cli._is_running = False # Don't render anymore.
  430. self._sub_cli = None
  431. # Restore main application.
  432. if not _from_application_generator:
  433. self.renderer.request_absolute_cursor_position()
  434. self._redraw()
  435. # Deliver result.
  436. if done_callback:
  437. done_callback(sub_cli.return_value())
  438. # Create sub CommandLineInterface.
  439. sub_cli = CommandLineInterface(
  440. application=application,
  441. eventloop=_SubApplicationEventLoop(self, done),
  442. input=self.input,
  443. output=self.output)
  444. sub_cli._is_running = True # Allow rendering of sub app.
  445. sub_cli._redraw()
  446. self._sub_cli = sub_cli
  447. def exit(self):
  448. """
  449. Set exit. When Control-D has been pressed.
  450. """
  451. on_exit = self.application.on_exit
  452. self._exit_flag = True
  453. self._redraw()
  454. if on_exit == AbortAction.RAISE_EXCEPTION:
  455. def eof_error():
  456. raise EOFError()
  457. self._set_return_callable(eof_error)
  458. elif on_exit == AbortAction.RETRY:
  459. self.reset()
  460. self.renderer.request_absolute_cursor_position()
  461. self.current_buffer.reset()
  462. elif on_exit == AbortAction.RETURN_NONE:
  463. self.set_return_value(None)
  464. def abort(self):
  465. """
  466. Set abort. When Control-C has been pressed.
  467. """
  468. on_abort = self.application.on_abort
  469. self._abort_flag = True
  470. self._redraw()
  471. if on_abort == AbortAction.RAISE_EXCEPTION:
  472. def keyboard_interrupt():
  473. raise KeyboardInterrupt()
  474. self._set_return_callable(keyboard_interrupt)
  475. elif on_abort == AbortAction.RETRY:
  476. self.reset()
  477. self.renderer.request_absolute_cursor_position()
  478. self.current_buffer.reset()
  479. elif on_abort == AbortAction.RETURN_NONE:
  480. self.set_return_value(None)
  481. # Deprecated aliase for exit/abort.
  482. set_exit = exit
  483. set_abort = abort
  484. def set_return_value(self, document):
  485. """
  486. Set a return value. The eventloop can retrieve the result it by calling
  487. `return_value`.
  488. """
  489. self._set_return_callable(lambda: document)
  490. self._redraw() # Redraw in "done" state, after the return value has been set.
  491. def _set_return_callable(self, value):
  492. assert callable(value)
  493. self._return_value = value
  494. if self.eventloop:
  495. self.eventloop.stop()
  496. def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True):
  497. """
  498. Run function on the terminal above the prompt.
  499. What this does is first hiding the prompt, then running this callable
  500. (which can safely output to the terminal), and then again rendering the
  501. prompt which causes the output of this function to scroll above the
  502. prompt.
  503. :param func: The callable to execute.
  504. :param render_cli_done: When True, render the interface in the
  505. 'Done' state first, then execute the function. If False,
  506. erase the interface first.
  507. :param cooked_mode: When True (the default), switch the input to
  508. cooked mode while executing the function.
  509. :returns: the result of `func`.
  510. """
  511. # Draw interface in 'done' state, or erase.
  512. if render_cli_done:
  513. self._return_value = True
  514. self._redraw()
  515. self.renderer.reset() # Make sure to disable mouse mode, etc...
  516. else:
  517. self.renderer.erase()
  518. self._return_value = None
  519. # Run system command.
  520. if cooked_mode:
  521. with self.input.cooked_mode():
  522. result = func()
  523. else:
  524. result = func()
  525. # Redraw interface again.
  526. self.renderer.reset()
  527. self.renderer.request_absolute_cursor_position()
  528. self._redraw()
  529. return result
  530. def run_application_generator(self, coroutine, render_cli_done=False):
  531. """
  532. EXPERIMENTAL
  533. Like `run_in_terminal`, but takes a generator that can yield Application instances.
  534. Example:
  535. def f():
  536. yield Application1(...)
  537. print('...')
  538. yield Application2(...)
  539. cli.run_in_terminal_async(f)
  540. The values which are yielded by the given coroutine are supposed to be
  541. `Application` instances that run in the current CLI, all other code is
  542. supposed to be CPU bound, so except for yielding the applications,
  543. there should not be any user interaction or I/O in the given function.
  544. """
  545. # Draw interface in 'done' state, or erase.
  546. if render_cli_done:
  547. self._return_value = True
  548. self._redraw()
  549. self.renderer.reset() # Make sure to disable mouse mode, etc...
  550. else:
  551. self.renderer.erase()
  552. self._return_value = None
  553. # Loop through the generator.
  554. g = coroutine()
  555. assert isinstance(g, types.GeneratorType)
  556. def step_next(send_value=None):
  557. " Execute next step of the coroutine."
  558. try:
  559. # Run until next yield, in cooked mode.
  560. with self.input.cooked_mode():
  561. result = g.send(send_value)
  562. except StopIteration:
  563. done()
  564. except:
  565. done()
  566. raise
  567. else:
  568. # Process yielded value from coroutine.
  569. assert isinstance(result, Application)
  570. self.run_sub_application(result, done_callback=step_next,
  571. _from_application_generator=True)
  572. def done():
  573. # Redraw interface again.
  574. self.renderer.reset()
  575. self.renderer.request_absolute_cursor_position()
  576. self._redraw()
  577. # Start processing coroutine.
  578. step_next()
  579. def run_system_command(self, command):
  580. """
  581. Run system command (While hiding the prompt. When finished, all the
  582. output will scroll above the prompt.)
  583. :param command: Shell command to be executed.
  584. """
  585. def wait_for_enter():
  586. """
  587. Create a sub application to wait for the enter key press.
  588. This has two advantages over using 'input'/'raw_input':
  589. - This will share the same input/output I/O.
  590. - This doesn't block the event loop.
  591. """
  592. from .shortcuts import create_prompt_application
  593. registry = Registry()
  594. @registry.add_binding(Keys.ControlJ)
  595. @registry.add_binding(Keys.ControlM)
  596. def _(event):
  597. event.cli.set_return_value(None)
  598. application = create_prompt_application(
  599. message='Press ENTER to continue...',
  600. key_bindings_registry=registry)
  601. self.run_sub_application(application)
  602. def run():
  603. # Try to use the same input/output file descriptors as the one,
  604. # used to run this application.
  605. try:
  606. input_fd = self.input.fileno()
  607. except AttributeError:
  608. input_fd = sys.stdin.fileno()
  609. try:
  610. output_fd = self.output.fileno()
  611. except AttributeError:
  612. output_fd = sys.stdout.fileno()
  613. # Run sub process.
  614. # XXX: This will still block the event loop.
  615. p = Popen(command, shell=True,
  616. stdin=input_fd, stdout=output_fd)
  617. p.wait()
  618. # Wait for the user to press enter.
  619. wait_for_enter()
  620. self.run_in_terminal(run)
  621. def suspend_to_background(self, suspend_group=True):
  622. """
  623. (Not thread safe -- to be called from inside the key bindings.)
  624. Suspend process.
  625. :param suspend_group: When true, suspend the whole process group.
  626. (This is the default, and probably what you want.)
  627. """
  628. # Only suspend when the opperating system supports it.
  629. # (Not on Windows.)
  630. if hasattr(signal, 'SIGTSTP'):
  631. def run():
  632. # Send `SIGSTP` to own process.
  633. # This will cause it to suspend.
  634. # Usually we want the whole process group to be suspended. This
  635. # handles the case when input is piped from another process.
  636. if suspend_group:
  637. os.kill(0, signal.SIGTSTP)
  638. else:
  639. os.kill(os.getpid(), signal.SIGTSTP)
  640. self.run_in_terminal(run)
  641. def print_tokens(self, tokens, style=None):
  642. """
  643. Print a list of (Token, text) tuples to the output.
  644. (When the UI is running, this method has to be called through
  645. `run_in_terminal`, otherwise it will destroy the UI.)
  646. :param style: Style class to use. Defaults to the active style in the CLI.
  647. """
  648. print_tokens(self.output, tokens, style or self.application.style)
  649. @property
  650. def is_exiting(self):
  651. """
  652. ``True`` when the exit flag as been set.
  653. """
  654. return self._exit_flag
  655. @property
  656. def is_aborting(self):
  657. """
  658. ``True`` when the abort flag as been set.
  659. """
  660. return self._abort_flag
  661. @property
  662. def is_returning(self):
  663. """
  664. ``True`` when a return value has been set.
  665. """
  666. return self._return_value is not None
  667. def return_value(self):
  668. """
  669. Get the return value. Not that this method can throw an exception.
  670. """
  671. # Note that it's a method, not a property, because it can throw
  672. # exceptions.
  673. if self._return_value:
  674. return self._return_value()
  675. @property
  676. def is_done(self):
  677. return self.is_exiting or self.is_aborting or self.is_returning
  678. def _create_async_completer(self, buffer):
  679. """
  680. Create function for asynchronous autocompletion.
  681. (Autocomplete in other thread.)
  682. """
  683. complete_thread_running = [False] # By ref.
  684. def completion_does_nothing(document, completion):
  685. """
  686. Return `True` if applying this completion doesn't have any effect.
  687. (When it doesn't insert any new text.
  688. """
  689. text_before_cursor = document.text_before_cursor
  690. replaced_text = text_before_cursor[
  691. len(text_before_cursor) + completion.start_position:]
  692. return replaced_text == completion.text
  693. def async_completer(select_first=False, select_last=False,
  694. insert_common_part=False, complete_event=None):
  695. document = buffer.document
  696. complete_event = complete_event or CompleteEvent(text_inserted=True)
  697. # Don't start two threads at the same time.
  698. if complete_thread_running[0]:
  699. return
  700. # Don't complete when we already have completions.
  701. if buffer.complete_state or not buffer.completer:
  702. return
  703. # Otherwise, get completions in other thread.
  704. complete_thread_running[0] = True
  705. def run():
  706. completions = list(buffer.completer.get_completions(document, complete_event))
  707. def callback():
  708. """
  709. Set the new complete_state in a safe way. Don't replace an
  710. existing complete_state if we had one. (The user could have
  711. pressed 'Tab' in the meantime. Also don't set it if the text
  712. was changed in the meantime.
  713. """
  714. complete_thread_running[0] = False
  715. # When there is only one completion, which has nothing to add, ignore it.
  716. if (len(completions) == 1 and
  717. completion_does_nothing(document, completions[0])):
  718. del completions[:]
  719. # Set completions if the text was not yet changed.
  720. if buffer.text == document.text and \
  721. buffer.cursor_position == document.cursor_position and \
  722. not buffer.complete_state:
  723. set_completions = True
  724. select_first_anyway = False
  725. # When the common part has to be inserted, and there
  726. # is a common part.
  727. if insert_common_part:
  728. common_part = get_common_complete_suffix(document, completions)
  729. if common_part:
  730. # Insert the common part, update completions.
  731. buffer.insert_text(common_part)
  732. if len(completions) > 1:
  733. # (Don't call `async_completer` again, but
  734. # recalculate completions. See:
  735. # https://github.com/ipython/ipython/issues/9658)
  736. completions[:] = [
  737. c.new_completion_from_position(len(common_part))
  738. for c in completions]
  739. else:
  740. set_completions = False
  741. else:
  742. # When we were asked to insert the "common"
  743. # prefix, but there was no common suffix but
  744. # still exactly one match, then select the
  745. # first. (It could be that we have a completion
  746. # which does * expansion, like '*.py', with
  747. # exactly one match.)
  748. if len(completions) == 1:
  749. select_first_anyway = True
  750. if set_completions:
  751. buffer.set_completions(
  752. completions=completions,
  753. go_to_first=select_first or select_first_anyway,
  754. go_to_last=select_last)
  755. self.invalidate()
  756. elif not buffer.complete_state:
  757. # Otherwise, restart thread.
  758. async_completer()
  759. if self.eventloop:
  760. self.eventloop.call_from_executor(callback)
  761. self.eventloop.run_in_executor(run)
  762. return async_completer
  763. def _create_auto_suggest_function(self, buffer):
  764. """
  765. Create function for asynchronous auto suggestion.
  766. (AutoSuggest in other thread.)
  767. """
  768. suggest_thread_running = [False] # By ref.
  769. def async_suggestor():
  770. document = buffer.document
  771. # Don't start two threads at the same time.
  772. if suggest_thread_running[0]:
  773. return
  774. # Don't suggest when we already have a suggestion.
  775. if buffer.suggestion or not buffer.auto_suggest:
  776. return
  777. # Otherwise, get completions in other thread.
  778. suggest_thread_running[0] = True
  779. def run():
  780. suggestion = buffer.auto_suggest.get_suggestion(self, buffer, document)
  781. def callback():
  782. suggest_thread_running[0] = False
  783. # Set suggestion only if the text was not yet changed.
  784. if buffer.text == document.text and \
  785. buffer.cursor_position == document.cursor_position:
  786. # Set suggestion and redraw interface.
  787. buffer.suggestion = suggestion
  788. self.invalidate()
  789. else:
  790. # Otherwise, restart thread.
  791. async_suggestor()
  792. if self.eventloop:
  793. self.eventloop.call_from_executor(callback)
  794. self.eventloop.run_in_executor(run)
  795. return async_suggestor
  796. def stdout_proxy(self, raw=False):
  797. """
  798. Create an :class:`_StdoutProxy` class which can be used as a patch for
  799. `sys.stdout`. Writing to this proxy will make sure that the text
  800. appears above the prompt, and that it doesn't destroy the output from
  801. the renderer.
  802. :param raw: (`bool`) When True, vt100 terminal escape sequences are not
  803. removed/escaped.
  804. """
  805. return _StdoutProxy(self, raw=raw)
  806. def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
  807. """
  808. Return a context manager that will replace ``sys.stdout`` with a proxy
  809. that makes sure that all printed text will appear above the prompt, and
  810. that it doesn't destroy the output from the renderer.
  811. :param patch_stdout: Replace `sys.stdout`.
  812. :param patch_stderr: Replace `sys.stderr`.
  813. """
  814. return _PatchStdoutContext(
  815. self.stdout_proxy(raw=raw),
  816. patch_stdout=patch_stdout, patch_stderr=patch_stderr)
  817. def create_eventloop_callbacks(self):
  818. return _InterfaceEventLoopCallbacks(self)
  819. class _InterfaceEventLoopCallbacks(EventLoopCallbacks):
  820. """
  821. Callbacks on the :class:`.CommandLineInterface` object, to which an
  822. eventloop can talk.
  823. """
  824. def __init__(self, cli):
  825. assert isinstance(cli, CommandLineInterface)
  826. self.cli = cli
  827. @property
  828. def _active_cli(self):
  829. """
  830. Return the active `CommandLineInterface`.
  831. """
  832. cli = self.cli
  833. # If there is a sub CLI. That one is always active.
  834. while cli._sub_cli:
  835. cli = cli._sub_cli
  836. return cli
  837. def terminal_size_changed(self):
  838. """
  839. Report terminal size change. This will trigger a redraw.
  840. """
  841. self._active_cli._on_resize()
  842. def input_timeout(self):
  843. cli = self._active_cli
  844. cli.on_input_timeout.fire()
  845. def feed_key(self, key_press):
  846. """
  847. Feed a key press to the CommandLineInterface.
  848. """
  849. assert isinstance(key_press, KeyPress)
  850. cli = self._active_cli
  851. # Feed the key and redraw.
  852. # (When the CLI is in 'done' state, it should return to the event loop
  853. # as soon as possible. Ignore all key presses beyond this point.)
  854. if not cli.is_done:
  855. cli.input_processor.feed(key_press)
  856. cli.input_processor.process_keys()
  857. class _PatchStdoutContext(object):
  858. def __init__(self, new_stdout, patch_stdout=True, patch_stderr=True):
  859. self.new_stdout = new_stdout
  860. self.patch_stdout = patch_stdout
  861. self.patch_stderr = patch_stderr
  862. def __enter__(self):
  863. self.original_stdout = sys.stdout
  864. self.original_stderr = sys.stderr
  865. if self.patch_stdout:
  866. sys.stdout = self.new_stdout
  867. if self.patch_stderr:
  868. sys.stderr = self.new_stdout
  869. def __exit__(self, *a, **kw):
  870. if self.patch_stdout:
  871. sys.stdout = self.original_stdout
  872. if self.patch_stderr:
  873. sys.stderr = self.original_stderr
  874. class _StdoutProxy(object):
  875. """
  876. Proxy for stdout, as returned by
  877. :class:`CommandLineInterface.stdout_proxy`.
  878. """
  879. def __init__(self, cli, raw=False):
  880. assert isinstance(cli, CommandLineInterface)
  881. assert isinstance(raw, bool)
  882. self._lock = threading.RLock()
  883. self._cli = cli
  884. self._raw = raw
  885. self._buffer = []
  886. self.errors = sys.__stdout__.errors
  887. self.encoding = sys.__stdout__.encoding
  888. def _do(self, func):
  889. if self._cli._is_running:
  890. run_in_terminal = functools.partial(self._cli.run_in_terminal, func)
  891. self._cli.eventloop.call_from_executor(run_in_terminal)
  892. else:
  893. func()
  894. def _write(self, data):
  895. """
  896. Note: print()-statements cause to multiple write calls.
  897. (write('line') and write('\n')). Of course we don't want to call
  898. `run_in_terminal` for every individual call, because that's too
  899. expensive, and as long as the newline hasn't been written, the
  900. text itself is again overwritter by the rendering of the input
  901. command line. Therefor, we have a little buffer which holds the
  902. text until a newline is written to stdout.
  903. """
  904. if '\n' in data:
  905. # When there is a newline in the data, write everything before the
  906. # newline, including the newline itself.
  907. before, after = data.rsplit('\n', 1)
  908. to_write = self._buffer + [before, '\n']
  909. self._buffer = [after]
  910. def run():
  911. for s in to_write:
  912. if self._raw:
  913. self._cli.output.write_raw(s)
  914. else:
  915. self._cli.output.write(s)
  916. self._do(run)
  917. else:
  918. # Otherwise, cache in buffer.
  919. self._buffer.append(data)
  920. def write(self, data):
  921. with self._lock:
  922. self._write(data)
  923. def _flush(self):
  924. def run():
  925. for s in self._buffer:
  926. if self._raw:
  927. self._cli.output.write_raw(s)
  928. else:
  929. self._cli.output.write(s)
  930. self._buffer = []
  931. self._cli.output.flush()
  932. self._do(run)
  933. def flush(self):
  934. """
  935. Flush buffered output.
  936. """
  937. with self._lock:
  938. self._flush()
  939. class _SubApplicationEventLoop(EventLoop):
  940. """
  941. Eventloop used by sub applications.
  942. A sub application is an `Application` that is "spawned" by a parent
  943. application. The parent application is suspended temporarily and the sub
  944. application is displayed instead.
  945. It doesn't need it's own event loop. The `EventLoopCallbacks` from the
  946. parent application are redirected to the sub application. So if the event
  947. loop that is run by the parent application detects input, the callbacks
  948. will make sure that it's forwarded to the sub application.
  949. When the sub application has a return value set, it will terminate
  950. by calling the `stop` method of this event loop. This is used to
  951. transfer control back to the parent application.
  952. """
  953. def __init__(self, cli, stop_callback):
  954. assert isinstance(cli, CommandLineInterface)
  955. assert callable(stop_callback)
  956. self.cli = cli
  957. self.stop_callback = stop_callback
  958. def stop(self):
  959. self.stop_callback()
  960. def close(self):
  961. pass
  962. def run_in_executor(self, callback):
  963. self.cli.eventloop.run_in_executor(callback)
  964. def call_from_executor(self, callback, _max_postpone_until=None):
  965. self.cli.eventloop.call_from_executor(
  966. callback, _max_postpone_until=_max_postpone_until)
  967. def add_reader(self, fd, callback):
  968. self.cli.eventloop.add_reader(fd, callback)
  969. def remove_reader(self, fd):
  970. self.cli.eventloop.remove_reader(fd)