interactiveshell.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. """IPython terminal interface using prompt_toolkit"""
  2. import os
  3. import sys
  4. import inspect
  5. from warnings import warn
  6. from typing import Union as UnionType, Optional
  7. from IPython.core.async_helpers import get_asyncio_loop
  8. from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
  9. from IPython.utils.py3compat import input
  10. from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
  11. from IPython.utils.process import abbrev_cwd
  12. from traitlets import (
  13. Bool,
  14. Unicode,
  15. Dict,
  16. Integer,
  17. List,
  18. observe,
  19. Instance,
  20. Type,
  21. default,
  22. Enum,
  23. Union,
  24. Any,
  25. validate,
  26. Float,
  27. )
  28. from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
  29. from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
  30. from prompt_toolkit.filters import HasFocus, Condition, IsDone
  31. from prompt_toolkit.formatted_text import PygmentsTokens
  32. from prompt_toolkit.history import History
  33. from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
  34. from prompt_toolkit.output import ColorDepth
  35. from prompt_toolkit.patch_stdout import patch_stdout
  36. from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
  37. from prompt_toolkit.styles import DynamicStyle, merge_styles
  38. from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
  39. from prompt_toolkit import __version__ as ptk_version
  40. from pygments.styles import get_style_by_name
  41. from pygments.style import Style
  42. from pygments.token import Token
  43. from .debugger import TerminalPdb, Pdb
  44. from .magics import TerminalMagics
  45. from .pt_inputhooks import get_inputhook_name_and_func
  46. from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
  47. from .ptutils import IPythonPTCompleter, IPythonPTLexer
  48. from .shortcuts import (
  49. KEY_BINDINGS,
  50. UNASSIGNED_ALLOWED_COMMANDS,
  51. create_ipython_shortcuts,
  52. create_identifier,
  53. RuntimeBinding,
  54. add_binding,
  55. )
  56. from .shortcuts.filters import KEYBINDING_FILTERS, filter_from_string
  57. from .shortcuts.auto_suggest import (
  58. NavigableAutoSuggestFromHistory,
  59. AppendAutoSuggestionInAnyLine,
  60. )
  61. PTK3 = ptk_version.startswith('3.')
  62. class _NoStyle(Style):
  63. pass
  64. _style_overrides_light_bg = {
  65. Token.Prompt: '#ansibrightblue',
  66. Token.PromptNum: '#ansiblue bold',
  67. Token.OutPrompt: '#ansibrightred',
  68. Token.OutPromptNum: '#ansired bold',
  69. }
  70. _style_overrides_linux = {
  71. Token.Prompt: '#ansibrightgreen',
  72. Token.PromptNum: '#ansigreen bold',
  73. Token.OutPrompt: '#ansibrightred',
  74. Token.OutPromptNum: '#ansired bold',
  75. }
  76. def _backward_compat_continuation_prompt_tokens(method, width: int, *, lineno: int):
  77. """
  78. Sagemath use custom prompt and we broke them in 8.19.
  79. """
  80. sig = inspect.signature(method)
  81. if "lineno" in inspect.signature(method).parameters or any(
  82. [p.kind == p.VAR_KEYWORD for p in sig.parameters.values()]
  83. ):
  84. return method(width, lineno=lineno)
  85. else:
  86. return method(width)
  87. def get_default_editor():
  88. try:
  89. return os.environ['EDITOR']
  90. except KeyError:
  91. pass
  92. except UnicodeError:
  93. warn("$EDITOR environment variable is not pure ASCII. Using platform "
  94. "default editor.")
  95. if os.name == 'posix':
  96. return 'vi' # the only one guaranteed to be there!
  97. else:
  98. return "notepad" # same in Windows!
  99. # conservatively check for tty
  100. # overridden streams can result in things like:
  101. # - sys.stdin = None
  102. # - no isatty method
  103. for _name in ('stdin', 'stdout', 'stderr'):
  104. _stream = getattr(sys, _name)
  105. try:
  106. if not _stream or not hasattr(_stream, "isatty") or not _stream.isatty():
  107. _is_tty = False
  108. break
  109. except ValueError:
  110. # stream is closed
  111. _is_tty = False
  112. break
  113. else:
  114. _is_tty = True
  115. _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
  116. def black_reformat_handler(text_before_cursor):
  117. """
  118. We do not need to protect against error,
  119. this is taken care at a higher level where any reformat error is ignored.
  120. Indeed we may call reformatting on incomplete code.
  121. """
  122. import black
  123. formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
  124. if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"):
  125. formatted_text = formatted_text[:-1]
  126. return formatted_text
  127. def yapf_reformat_handler(text_before_cursor):
  128. from yapf.yapflib import file_resources
  129. from yapf.yapflib import yapf_api
  130. style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
  131. formatted_text, was_formatted = yapf_api.FormatCode(
  132. text_before_cursor, style_config=style_config
  133. )
  134. if was_formatted:
  135. if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"):
  136. formatted_text = formatted_text[:-1]
  137. return formatted_text
  138. else:
  139. return text_before_cursor
  140. class PtkHistoryAdapter(History):
  141. """
  142. Prompt toolkit has it's own way of handling history, Where it assumes it can
  143. Push/pull from history.
  144. """
  145. def __init__(self, shell):
  146. super().__init__()
  147. self.shell = shell
  148. self._refresh()
  149. def append_string(self, string):
  150. # we rely on sql for that.
  151. self._loaded = False
  152. self._refresh()
  153. def _refresh(self):
  154. if not self._loaded:
  155. self._loaded_strings = list(self.load_history_strings())
  156. def load_history_strings(self):
  157. last_cell = ""
  158. res = []
  159. for __, ___, cell in self.shell.history_manager.get_tail(
  160. self.shell.history_load_length, include_latest=True
  161. ):
  162. # Ignore blank lines and consecutive duplicates
  163. cell = cell.rstrip()
  164. if cell and (cell != last_cell):
  165. res.append(cell)
  166. last_cell = cell
  167. yield from res[::-1]
  168. def store_string(self, string: str) -> None:
  169. pass
  170. class TerminalInteractiveShell(InteractiveShell):
  171. mime_renderers = Dict().tag(config=True)
  172. space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
  173. 'to reserve for the tab completion menu, '
  174. 'search history, ...etc, the height of '
  175. 'these menus will at most this value. '
  176. 'Increase it is you prefer long and skinny '
  177. 'menus, decrease for short and wide.'
  178. ).tag(config=True)
  179. pt_app: UnionType[PromptSession, None] = None
  180. auto_suggest: UnionType[
  181. AutoSuggestFromHistory, NavigableAutoSuggestFromHistory, None
  182. ] = None
  183. debugger_history = None
  184. debugger_history_file = Unicode(
  185. "~/.pdbhistory", help="File in which to store and read history"
  186. ).tag(config=True)
  187. simple_prompt = Bool(_use_simple_prompt,
  188. help="""Use `raw_input` for the REPL, without completion and prompt colors.
  189. Useful when controlling IPython as a subprocess, and piping
  190. STDIN/OUT/ERR. Known usage are: IPython's own testing machinery,
  191. and emacs' inferior-python subprocess (assuming you have set
  192. `python-shell-interpreter` to "ipython") available through the
  193. built-in `M-x run-python` and third party packages such as elpy.
  194. This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
  195. environment variable is set, or the current terminal is not a tty.
  196. Thus the Default value reported in --help-all, or config will often
  197. be incorrectly reported.
  198. """,
  199. ).tag(config=True)
  200. @property
  201. def debugger_cls(self):
  202. return Pdb if self.simple_prompt else TerminalPdb
  203. confirm_exit = Bool(True,
  204. help="""
  205. Set to confirm when you try to exit IPython with an EOF (Control-D
  206. in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
  207. you can force a direct exit without any confirmation.""",
  208. ).tag(config=True)
  209. editing_mode = Unicode('emacs',
  210. help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
  211. ).tag(config=True)
  212. emacs_bindings_in_vi_insert_mode = Bool(
  213. True,
  214. help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.",
  215. ).tag(config=True)
  216. modal_cursor = Bool(
  217. True,
  218. help="""
  219. Cursor shape changes depending on vi mode: beam in vi insert mode,
  220. block in nav mode, underscore in replace mode.""",
  221. ).tag(config=True)
  222. ttimeoutlen = Float(
  223. 0.01,
  224. help="""The time in milliseconds that is waited for a key code
  225. to complete.""",
  226. ).tag(config=True)
  227. timeoutlen = Float(
  228. 0.5,
  229. help="""The time in milliseconds that is waited for a mapped key
  230. sequence to complete.""",
  231. ).tag(config=True)
  232. autoformatter = Unicode(
  233. None,
  234. help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`",
  235. allow_none=True
  236. ).tag(config=True)
  237. auto_match = Bool(
  238. False,
  239. help="""
  240. Automatically add/delete closing bracket or quote when opening bracket or quote is entered/deleted.
  241. Brackets: (), [], {}
  242. Quotes: '', \"\"
  243. """,
  244. ).tag(config=True)
  245. mouse_support = Bool(False,
  246. help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
  247. ).tag(config=True)
  248. # We don't load the list of styles for the help string, because loading
  249. # Pygments plugins takes time and can cause unexpected errors.
  250. highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
  251. help="""The name or class of a Pygments style to use for syntax
  252. highlighting. To see available styles, run `pygmentize -L styles`."""
  253. ).tag(config=True)
  254. @validate('editing_mode')
  255. def _validate_editing_mode(self, proposal):
  256. if proposal['value'].lower() == 'vim':
  257. proposal['value']= 'vi'
  258. elif proposal['value'].lower() == 'default':
  259. proposal['value']= 'emacs'
  260. if hasattr(EditingMode, proposal['value'].upper()):
  261. return proposal['value'].lower()
  262. return self.editing_mode
  263. @observe('editing_mode')
  264. def _editing_mode(self, change):
  265. if self.pt_app:
  266. self.pt_app.editing_mode = getattr(EditingMode, change.new.upper())
  267. def _set_formatter(self, formatter):
  268. if formatter is None:
  269. self.reformat_handler = lambda x:x
  270. elif formatter == 'black':
  271. self.reformat_handler = black_reformat_handler
  272. elif formatter == "yapf":
  273. self.reformat_handler = yapf_reformat_handler
  274. else:
  275. raise ValueError
  276. @observe("autoformatter")
  277. def _autoformatter_changed(self, change):
  278. formatter = change.new
  279. self._set_formatter(formatter)
  280. @observe('highlighting_style')
  281. @observe('colors')
  282. def _highlighting_style_changed(self, change):
  283. self.refresh_style()
  284. def refresh_style(self):
  285. self._style = self._make_style_from_name_or_cls(self.highlighting_style)
  286. highlighting_style_overrides = Dict(
  287. help="Override highlighting format for specific tokens"
  288. ).tag(config=True)
  289. true_color = Bool(False,
  290. help="""Use 24bit colors instead of 256 colors in prompt highlighting.
  291. If your terminal supports true color, the following command should
  292. print ``TRUECOLOR`` in orange::
  293. printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
  294. """,
  295. ).tag(config=True)
  296. editor = Unicode(get_default_editor(),
  297. help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
  298. ).tag(config=True)
  299. prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
  300. prompts = Instance(Prompts)
  301. @default('prompts')
  302. def _prompts_default(self):
  303. return self.prompts_class(self)
  304. # @observe('prompts')
  305. # def _(self, change):
  306. # self._update_layout()
  307. @default('displayhook_class')
  308. def _displayhook_class_default(self):
  309. return RichPromptDisplayHook
  310. term_title = Bool(True,
  311. help="Automatically set the terminal title"
  312. ).tag(config=True)
  313. term_title_format = Unicode("IPython: {cwd}",
  314. help="Customize the terminal title format. This is a python format string. " +
  315. "Available substitutions are: {cwd}."
  316. ).tag(config=True)
  317. display_completions = Enum(('column', 'multicolumn','readlinelike'),
  318. help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
  319. "'readlinelike'. These options are for `prompt_toolkit`, see "
  320. "`prompt_toolkit` documentation for more information."
  321. ),
  322. default_value='multicolumn').tag(config=True)
  323. highlight_matching_brackets = Bool(True,
  324. help="Highlight matching brackets.",
  325. ).tag(config=True)
  326. extra_open_editor_shortcuts = Bool(False,
  327. help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
  328. "This is in addition to the F2 binding, which is always enabled."
  329. ).tag(config=True)
  330. handle_return = Any(None,
  331. help="Provide an alternative handler to be called when the user presses "
  332. "Return. This is an advanced option intended for debugging, which "
  333. "may be changed or removed in later releases."
  334. ).tag(config=True)
  335. enable_history_search = Bool(True,
  336. help="Allows to enable/disable the prompt toolkit history search"
  337. ).tag(config=True)
  338. autosuggestions_provider = Unicode(
  339. "NavigableAutoSuggestFromHistory",
  340. help="Specifies from which source automatic suggestions are provided. "
  341. "Can be set to ``'NavigableAutoSuggestFromHistory'`` (:kbd:`up` and "
  342. ":kbd:`down` swap suggestions), ``'AutoSuggestFromHistory'``, "
  343. " or ``None`` to disable automatic suggestions. "
  344. "Default is `'NavigableAutoSuggestFromHistory`'.",
  345. allow_none=True,
  346. ).tag(config=True)
  347. def _set_autosuggestions(self, provider):
  348. # disconnect old handler
  349. if self.auto_suggest and isinstance(
  350. self.auto_suggest, NavigableAutoSuggestFromHistory
  351. ):
  352. self.auto_suggest.disconnect()
  353. if provider is None:
  354. self.auto_suggest = None
  355. elif provider == "AutoSuggestFromHistory":
  356. self.auto_suggest = AutoSuggestFromHistory()
  357. elif provider == "NavigableAutoSuggestFromHistory":
  358. self.auto_suggest = NavigableAutoSuggestFromHistory()
  359. else:
  360. raise ValueError("No valid provider.")
  361. if self.pt_app:
  362. self.pt_app.auto_suggest = self.auto_suggest
  363. @observe("autosuggestions_provider")
  364. def _autosuggestions_provider_changed(self, change):
  365. provider = change.new
  366. self._set_autosuggestions(provider)
  367. shortcuts = List(
  368. trait=Dict(
  369. key_trait=Enum(
  370. [
  371. "command",
  372. "match_keys",
  373. "match_filter",
  374. "new_keys",
  375. "new_filter",
  376. "create",
  377. ]
  378. ),
  379. per_key_traits={
  380. "command": Unicode(),
  381. "match_keys": List(Unicode()),
  382. "match_filter": Unicode(),
  383. "new_keys": List(Unicode()),
  384. "new_filter": Unicode(),
  385. "create": Bool(False),
  386. },
  387. ),
  388. help="""Add, disable or modifying shortcuts.
  389. Each entry on the list should be a dictionary with ``command`` key
  390. identifying the target function executed by the shortcut and at least
  391. one of the following:
  392. - ``match_keys``: list of keys used to match an existing shortcut,
  393. - ``match_filter``: shortcut filter used to match an existing shortcut,
  394. - ``new_keys``: list of keys to set,
  395. - ``new_filter``: a new shortcut filter to set
  396. The filters have to be composed of pre-defined verbs and joined by one
  397. of the following conjunctions: ``&`` (and), ``|`` (or), ``~`` (not).
  398. The pre-defined verbs are:
  399. {}
  400. To disable a shortcut set ``new_keys`` to an empty list.
  401. To add a shortcut add key ``create`` with value ``True``.
  402. When modifying/disabling shortcuts, ``match_keys``/``match_filter`` can
  403. be omitted if the provided specification uniquely identifies a shortcut
  404. to be modified/disabled. When modifying a shortcut ``new_filter`` or
  405. ``new_keys`` can be omitted which will result in reuse of the existing
  406. filter/keys.
  407. Only shortcuts defined in IPython (and not default prompt-toolkit
  408. shortcuts) can be modified or disabled. The full list of shortcuts,
  409. command identifiers and filters is available under
  410. :ref:`terminal-shortcuts-list`.
  411. """.format(
  412. "\n ".join([f"- `{k}`" for k in KEYBINDING_FILTERS])
  413. ),
  414. ).tag(config=True)
  415. @observe("shortcuts")
  416. def _shortcuts_changed(self, change):
  417. if self.pt_app:
  418. self.pt_app.key_bindings = self._merge_shortcuts(user_shortcuts=change.new)
  419. def _merge_shortcuts(self, user_shortcuts):
  420. # rebuild the bindings list from scratch
  421. key_bindings = create_ipython_shortcuts(self)
  422. # for now we only allow adding shortcuts for a specific set of
  423. # commands; this is a security precution.
  424. allowed_commands = {
  425. create_identifier(binding.command): binding.command
  426. for binding in KEY_BINDINGS
  427. }
  428. allowed_commands.update(
  429. {
  430. create_identifier(command): command
  431. for command in UNASSIGNED_ALLOWED_COMMANDS
  432. }
  433. )
  434. shortcuts_to_skip = []
  435. shortcuts_to_add = []
  436. for shortcut in user_shortcuts:
  437. command_id = shortcut["command"]
  438. if command_id not in allowed_commands:
  439. allowed_commands = "\n - ".join(allowed_commands)
  440. raise ValueError(
  441. f"{command_id} is not a known shortcut command."
  442. f" Allowed commands are: \n - {allowed_commands}"
  443. )
  444. old_keys = shortcut.get("match_keys", None)
  445. old_filter = (
  446. filter_from_string(shortcut["match_filter"])
  447. if "match_filter" in shortcut
  448. else None
  449. )
  450. matching = [
  451. binding
  452. for binding in KEY_BINDINGS
  453. if (
  454. (old_filter is None or binding.filter == old_filter)
  455. and (old_keys is None or [k for k in binding.keys] == old_keys)
  456. and create_identifier(binding.command) == command_id
  457. )
  458. ]
  459. new_keys = shortcut.get("new_keys", None)
  460. new_filter = shortcut.get("new_filter", None)
  461. command = allowed_commands[command_id]
  462. creating_new = shortcut.get("create", False)
  463. modifying_existing = not creating_new and (
  464. new_keys is not None or new_filter
  465. )
  466. if creating_new and new_keys == []:
  467. raise ValueError("Cannot add a shortcut without keys")
  468. if modifying_existing:
  469. specification = {
  470. key: shortcut[key]
  471. for key in ["command", "filter"]
  472. if key in shortcut
  473. }
  474. if len(matching) == 0:
  475. raise ValueError(
  476. f"No shortcuts matching {specification} found in {KEY_BINDINGS}"
  477. )
  478. elif len(matching) > 1:
  479. raise ValueError(
  480. f"Multiple shortcuts matching {specification} found,"
  481. f" please add keys/filter to select one of: {matching}"
  482. )
  483. matched = matching[0]
  484. old_filter = matched.filter
  485. old_keys = list(matched.keys)
  486. shortcuts_to_skip.append(
  487. RuntimeBinding(
  488. command,
  489. keys=old_keys,
  490. filter=old_filter,
  491. )
  492. )
  493. if new_keys != []:
  494. shortcuts_to_add.append(
  495. RuntimeBinding(
  496. command,
  497. keys=new_keys or old_keys,
  498. filter=(
  499. filter_from_string(new_filter)
  500. if new_filter is not None
  501. else (
  502. old_filter
  503. if old_filter is not None
  504. else filter_from_string("always")
  505. )
  506. ),
  507. )
  508. )
  509. # rebuild the bindings list from scratch
  510. key_bindings = create_ipython_shortcuts(self, skip=shortcuts_to_skip)
  511. for binding in shortcuts_to_add:
  512. add_binding(key_bindings, binding)
  513. return key_bindings
  514. prompt_includes_vi_mode = Bool(True,
  515. help="Display the current vi mode (when using vi editing mode)."
  516. ).tag(config=True)
  517. prompt_line_number_format = Unicode(
  518. "",
  519. help="The format for line numbering, will be passed `line` (int, 1 based)"
  520. " the current line number and `rel_line` the relative line number."
  521. " for example to display both you can use the following template string :"
  522. " c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '"
  523. " This will display the current line number, with leading space and a width of at least 4"
  524. " character, as well as the relative line number 0 padded and always with a + or - sign."
  525. " Note that when using Emacs mode the prompt of the first line may not update.",
  526. ).tag(config=True)
  527. @observe('term_title')
  528. def init_term_title(self, change=None):
  529. # Enable or disable the terminal title.
  530. if self.term_title and _is_tty:
  531. toggle_set_term_title(True)
  532. set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
  533. else:
  534. toggle_set_term_title(False)
  535. def restore_term_title(self):
  536. if self.term_title and _is_tty:
  537. restore_term_title()
  538. def init_display_formatter(self):
  539. super(TerminalInteractiveShell, self).init_display_formatter()
  540. # terminal only supports plain text
  541. self.display_formatter.active_types = ["text/plain"]
  542. def init_prompt_toolkit_cli(self):
  543. if self.simple_prompt:
  544. # Fall back to plain non-interactive output for tests.
  545. # This is very limited.
  546. def prompt():
  547. prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
  548. lines = [input(prompt_text)]
  549. prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
  550. while self.check_complete('\n'.join(lines))[0] == 'incomplete':
  551. lines.append( input(prompt_continuation) )
  552. return '\n'.join(lines)
  553. self.prompt_for_code = prompt
  554. return
  555. # Set up keyboard shortcuts
  556. key_bindings = self._merge_shortcuts(user_shortcuts=self.shortcuts)
  557. # Pre-populate history from IPython's history database
  558. history = PtkHistoryAdapter(self)
  559. self._style = self._make_style_from_name_or_cls(self.highlighting_style)
  560. self.style = DynamicStyle(lambda: self._style)
  561. editing_mode = getattr(EditingMode, self.editing_mode.upper())
  562. self._use_asyncio_inputhook = False
  563. self.pt_app = PromptSession(
  564. auto_suggest=self.auto_suggest,
  565. editing_mode=editing_mode,
  566. key_bindings=key_bindings,
  567. history=history,
  568. completer=IPythonPTCompleter(shell=self),
  569. enable_history_search=self.enable_history_search,
  570. style=self.style,
  571. include_default_pygments_style=False,
  572. mouse_support=self.mouse_support,
  573. enable_open_in_editor=self.extra_open_editor_shortcuts,
  574. color_depth=self.color_depth,
  575. tempfile_suffix=".py",
  576. **self._extra_prompt_options(),
  577. )
  578. if isinstance(self.auto_suggest, NavigableAutoSuggestFromHistory):
  579. self.auto_suggest.connect(self.pt_app)
  580. def _make_style_from_name_or_cls(self, name_or_cls):
  581. """
  582. Small wrapper that make an IPython compatible style from a style name
  583. We need that to add style for prompt ... etc.
  584. """
  585. style_overrides = {}
  586. if name_or_cls == 'legacy':
  587. legacy = self.colors.lower()
  588. if legacy == 'linux':
  589. style_cls = get_style_by_name('monokai')
  590. style_overrides = _style_overrides_linux
  591. elif legacy == 'lightbg':
  592. style_overrides = _style_overrides_light_bg
  593. style_cls = get_style_by_name('pastie')
  594. elif legacy == 'neutral':
  595. # The default theme needs to be visible on both a dark background
  596. # and a light background, because we can't tell what the terminal
  597. # looks like. These tweaks to the default theme help with that.
  598. style_cls = get_style_by_name('default')
  599. style_overrides.update({
  600. Token.Number: '#ansigreen',
  601. Token.Operator: 'noinherit',
  602. Token.String: '#ansiyellow',
  603. Token.Name.Function: '#ansiblue',
  604. Token.Name.Class: 'bold #ansiblue',
  605. Token.Name.Namespace: 'bold #ansiblue',
  606. Token.Name.Variable.Magic: '#ansiblue',
  607. Token.Prompt: '#ansigreen',
  608. Token.PromptNum: '#ansibrightgreen bold',
  609. Token.OutPrompt: '#ansired',
  610. Token.OutPromptNum: '#ansibrightred bold',
  611. })
  612. # Hack: Due to limited color support on the Windows console
  613. # the prompt colors will be wrong without this
  614. if os.name == 'nt':
  615. style_overrides.update({
  616. Token.Prompt: '#ansidarkgreen',
  617. Token.PromptNum: '#ansigreen bold',
  618. Token.OutPrompt: '#ansidarkred',
  619. Token.OutPromptNum: '#ansired bold',
  620. })
  621. elif legacy =='nocolor':
  622. style_cls=_NoStyle
  623. style_overrides = {}
  624. else :
  625. raise ValueError('Got unknown colors: ', legacy)
  626. else :
  627. if isinstance(name_or_cls, str):
  628. style_cls = get_style_by_name(name_or_cls)
  629. else:
  630. style_cls = name_or_cls
  631. style_overrides = {
  632. Token.Prompt: '#ansigreen',
  633. Token.PromptNum: '#ansibrightgreen bold',
  634. Token.OutPrompt: '#ansired',
  635. Token.OutPromptNum: '#ansibrightred bold',
  636. }
  637. style_overrides.update(self.highlighting_style_overrides)
  638. style = merge_styles([
  639. style_from_pygments_cls(style_cls),
  640. style_from_pygments_dict(style_overrides),
  641. ])
  642. return style
  643. @property
  644. def pt_complete_style(self):
  645. return {
  646. 'multicolumn': CompleteStyle.MULTI_COLUMN,
  647. 'column': CompleteStyle.COLUMN,
  648. 'readlinelike': CompleteStyle.READLINE_LIKE,
  649. }[self.display_completions]
  650. @property
  651. def color_depth(self):
  652. return (ColorDepth.TRUE_COLOR if self.true_color else None)
  653. def _extra_prompt_options(self):
  654. """
  655. Return the current layout option for the current Terminal InteractiveShell
  656. """
  657. def get_message():
  658. return PygmentsTokens(self.prompts.in_prompt_tokens())
  659. if self.editing_mode == "emacs" and self.prompt_line_number_format == "":
  660. # with emacs mode the prompt is (usually) static, so we call only
  661. # the function once. With VI mode it can toggle between [ins] and
  662. # [nor] so we can't precompute.
  663. # here I'm going to favor the default keybinding which almost
  664. # everybody uses to decrease CPU usage.
  665. # if we have issues with users with custom Prompts we can see how to
  666. # work around this.
  667. get_message = get_message()
  668. options = {
  669. "complete_in_thread": False,
  670. "lexer": IPythonPTLexer(),
  671. "reserve_space_for_menu": self.space_for_menu,
  672. "message": get_message,
  673. "prompt_continuation": (
  674. lambda width, lineno, is_soft_wrap: PygmentsTokens(
  675. _backward_compat_continuation_prompt_tokens(
  676. self.prompts.continuation_prompt_tokens, width, lineno=lineno
  677. )
  678. )
  679. ),
  680. "multiline": True,
  681. "complete_style": self.pt_complete_style,
  682. "input_processors": [
  683. # Highlight matching brackets, but only when this setting is
  684. # enabled, and only when the DEFAULT_BUFFER has the focus.
  685. ConditionalProcessor(
  686. processor=HighlightMatchingBracketProcessor(chars="[](){}"),
  687. filter=HasFocus(DEFAULT_BUFFER)
  688. & ~IsDone()
  689. & Condition(lambda: self.highlight_matching_brackets),
  690. ),
  691. # Show auto-suggestion in lines other than the last line.
  692. ConditionalProcessor(
  693. processor=AppendAutoSuggestionInAnyLine(),
  694. filter=HasFocus(DEFAULT_BUFFER)
  695. & ~IsDone()
  696. & Condition(
  697. lambda: isinstance(
  698. self.auto_suggest, NavigableAutoSuggestFromHistory
  699. )
  700. ),
  701. ),
  702. ],
  703. }
  704. if not PTK3:
  705. options['inputhook'] = self.inputhook
  706. return options
  707. def prompt_for_code(self):
  708. if self.rl_next_input:
  709. default = self.rl_next_input
  710. self.rl_next_input = None
  711. else:
  712. default = ''
  713. # In order to make sure that asyncio code written in the
  714. # interactive shell doesn't interfere with the prompt, we run the
  715. # prompt in a different event loop.
  716. # If we don't do this, people could spawn coroutine with a
  717. # while/true inside which will freeze the prompt.
  718. with patch_stdout(raw=True):
  719. if self._use_asyncio_inputhook:
  720. # When we integrate the asyncio event loop, run the UI in the
  721. # same event loop as the rest of the code. don't use an actual
  722. # input hook. (Asyncio is not made for nesting event loops.)
  723. asyncio_loop = get_asyncio_loop()
  724. text = asyncio_loop.run_until_complete(
  725. self.pt_app.prompt_async(
  726. default=default, **self._extra_prompt_options()
  727. )
  728. )
  729. else:
  730. text = self.pt_app.prompt(
  731. default=default,
  732. inputhook=self._inputhook,
  733. **self._extra_prompt_options(),
  734. )
  735. return text
  736. def enable_win_unicode_console(self):
  737. # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
  738. # console by default, so WUC shouldn't be needed.
  739. warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
  740. DeprecationWarning,
  741. stacklevel=2)
  742. def init_io(self):
  743. if sys.platform not in {'win32', 'cli'}:
  744. return
  745. import colorama
  746. colorama.init()
  747. def init_magics(self):
  748. super(TerminalInteractiveShell, self).init_magics()
  749. self.register_magics(TerminalMagics)
  750. def init_alias(self):
  751. # The parent class defines aliases that can be safely used with any
  752. # frontend.
  753. super(TerminalInteractiveShell, self).init_alias()
  754. # Now define aliases that only make sense on the terminal, because they
  755. # need direct access to the console in a way that we can't emulate in
  756. # GUI or web frontend
  757. if os.name == 'posix':
  758. for cmd in ('clear', 'more', 'less', 'man'):
  759. self.alias_manager.soft_define_alias(cmd, cmd)
  760. def __init__(self, *args, **kwargs) -> None:
  761. super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
  762. self._set_autosuggestions(self.autosuggestions_provider)
  763. self.init_prompt_toolkit_cli()
  764. self.init_term_title()
  765. self.keep_running = True
  766. self._set_formatter(self.autoformatter)
  767. def ask_exit(self):
  768. self.keep_running = False
  769. rl_next_input = None
  770. def interact(self):
  771. self.keep_running = True
  772. while self.keep_running:
  773. print(self.separate_in, end='')
  774. try:
  775. code = self.prompt_for_code()
  776. except EOFError:
  777. if (not self.confirm_exit) \
  778. or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
  779. self.ask_exit()
  780. else:
  781. if code:
  782. self.run_cell(code, store_history=True)
  783. def mainloop(self):
  784. # An extra layer of protection in case someone mashing Ctrl-C breaks
  785. # out of our internal code.
  786. while True:
  787. try:
  788. self.interact()
  789. break
  790. except KeyboardInterrupt as e:
  791. print("\n%s escaped interact()\n" % type(e).__name__)
  792. finally:
  793. # An interrupt during the eventloop will mess up the
  794. # internal state of the prompt_toolkit library.
  795. # Stopping the eventloop fixes this, see
  796. # https://github.com/ipython/ipython/pull/9867
  797. if hasattr(self, '_eventloop'):
  798. self._eventloop.stop()
  799. self.restore_term_title()
  800. # try to call some at-exit operation optimistically as some things can't
  801. # be done during interpreter shutdown. this is technically inaccurate as
  802. # this make mainlool not re-callable, but that should be a rare if not
  803. # in existent use case.
  804. self._atexit_once()
  805. _inputhook = None
  806. def inputhook(self, context):
  807. if self._inputhook is not None:
  808. self._inputhook(context)
  809. active_eventloop: Optional[str] = None
  810. def enable_gui(self, gui: Optional[str] = None) -> None:
  811. if gui:
  812. from ..core.pylabtools import _convert_gui_from_matplotlib
  813. gui = _convert_gui_from_matplotlib(gui)
  814. if self.simple_prompt is True and gui is not None:
  815. print(
  816. f'Cannot install event loop hook for "{gui}" when running with `--simple-prompt`.'
  817. )
  818. print(
  819. "NOTE: Tk is supported natively; use Tk apps and Tk backends with `--simple-prompt`."
  820. )
  821. return
  822. if self._inputhook is None and gui is None:
  823. print("No event loop hook running.")
  824. return
  825. if self._inputhook is not None and gui is not None:
  826. newev, newinhook = get_inputhook_name_and_func(gui)
  827. if self._inputhook == newinhook:
  828. # same inputhook, do nothing
  829. self.log.info(
  830. f"Shell is already running the {self.active_eventloop} eventloop. Doing nothing"
  831. )
  832. return
  833. self.log.warning(
  834. f"Shell is already running a different gui event loop for {self.active_eventloop}. "
  835. "Call with no arguments to disable the current loop."
  836. )
  837. return
  838. if self._inputhook is not None and gui is None:
  839. self.active_eventloop = self._inputhook = None
  840. if gui and (gui not in {None, "webagg"}):
  841. # This hook runs with each cycle of the `prompt_toolkit`'s event loop.
  842. self.active_eventloop, self._inputhook = get_inputhook_name_and_func(gui)
  843. else:
  844. self.active_eventloop = self._inputhook = None
  845. self._use_asyncio_inputhook = gui == "asyncio"
  846. # Run !system commands directly, not through pipes, so terminal programs
  847. # work correctly.
  848. system = InteractiveShell.system_raw
  849. def auto_rewrite_input(self, cmd):
  850. """Overridden from the parent class to use fancy rewriting prompt"""
  851. if not self.show_rewritten_input:
  852. return
  853. tokens = self.prompts.rewrite_prompt_tokens()
  854. if self.pt_app:
  855. print_formatted_text(PygmentsTokens(tokens), end='',
  856. style=self.pt_app.app.style)
  857. print(cmd)
  858. else:
  859. prompt = ''.join(s for t, s in tokens)
  860. print(prompt, cmd, sep='')
  861. _prompts_before = None
  862. def switch_doctest_mode(self, mode):
  863. """Switch prompts to classic for %doctest_mode"""
  864. if mode:
  865. self._prompts_before = self.prompts
  866. self.prompts = ClassicPrompts(self)
  867. elif self._prompts_before:
  868. self.prompts = self._prompts_before
  869. self._prompts_before = None
  870. # self._update_layout()
  871. InteractiveShellABC.register(TerminalInteractiveShell)
  872. if __name__ == '__main__':
  873. TerminalInteractiveShell.instance().interact()