1import asyncio
2import os
3import sys
4
5from IPython.core.debugger import Pdb
6from IPython.core.completer import IPCompleter
7from .ptutils import IPythonPTCompleter
8from .shortcuts import create_ipython_shortcuts
9
10from pathlib import Path
11from pygments.token import Token
12from prompt_toolkit.application import create_app_session
13from prompt_toolkit.shortcuts.prompt import PromptSession
14from prompt_toolkit.enums import EditingMode
15from prompt_toolkit.formatted_text import PygmentsTokens
16from prompt_toolkit.history import InMemoryHistory, FileHistory
17from concurrent.futures import ThreadPoolExecutor
18
19# we want to avoid ptk as much as possible when using subprocesses
20# as it uses cursor positioning requests, deletes color ....
21_use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ
22
23
24class TerminalPdb(Pdb):
25 """Standalone IPython debugger."""
26
27 def __init__(self, *args, pt_session_options=None, **kwargs):
28 Pdb.__init__(self, *args, **kwargs)
29 self._ptcomp = None
30 self.pt_init(pt_session_options)
31 self.thread_executor = ThreadPoolExecutor(1)
32
33 def pt_init(self, pt_session_options=None):
34 """Initialize the prompt session and the prompt loop
35 and store them in self.pt_app and self.pt_loop.
36
37 Additional keyword arguments for the PromptSession class
38 can be specified in pt_session_options.
39 """
40 if pt_session_options is None:
41 pt_session_options = {}
42
43 def get_prompt_tokens():
44 return [(Token.Prompt, self.prompt)]
45
46 if self._ptcomp is None:
47 compl = IPCompleter(
48 shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
49 )
50 # add a completer for all the do_ methods
51 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
52
53 def gen_comp(self, text):
54 return [m for m in methods_names if m.startswith(text)]
55 import types
56 newcomp = types.MethodType(gen_comp, compl)
57 compl.custom_matchers.insert(0, newcomp)
58 # end add completer.
59
60 self._ptcomp = IPythonPTCompleter(compl)
61
62 # setup history only when we start pdb
63 if self.shell.debugger_history is None:
64 if self.shell.debugger_history_file is not None:
65 p = Path(self.shell.debugger_history_file).expanduser()
66 if not p.exists():
67 p.touch()
68 self.debugger_history = FileHistory(os.path.expanduser(str(p)))
69 else:
70 self.debugger_history = InMemoryHistory()
71 else:
72 self.debugger_history = self.shell.debugger_history
73
74 options = dict(
75 message=(lambda: PygmentsTokens(get_prompt_tokens())),
76 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
77 key_bindings=create_ipython_shortcuts(self.shell),
78 history=self.debugger_history,
79 completer=self._ptcomp,
80 enable_history_search=True,
81 mouse_support=self.shell.mouse_support,
82 complete_style=self.shell.pt_complete_style,
83 style=getattr(self.shell, "style", None),
84 color_depth=self.shell.color_depth,
85 )
86
87 options.update(pt_session_options)
88 if not _use_simple_prompt:
89 self.pt_loop = asyncio.new_event_loop()
90 self.pt_app = PromptSession(**options)
91
92 def _prompt(self):
93 """
94 In case other prompt_toolkit apps have to run in parallel to this one (e.g. in madbg),
95 create_app_session must be used to prevent mixing up between them. According to the prompt_toolkit docs:
96
97 > If you need multiple applications running at the same time, you have to create a separate
98 > `AppSession` using a `with create_app_session():` block.
99 """
100 with create_app_session():
101 return self.pt_app.prompt()
102
103 def cmdloop(self, intro=None):
104 """Repeatedly issue a prompt, accept input, parse an initial prefix
105 off the received input, and dispatch to action methods, passing them
106 the remainder of the line as argument.
107
108 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
109 """
110 if not self.use_rawinput:
111 raise ValueError('Sorry ipdb does not support use_rawinput=False')
112
113 # In order to make sure that prompt, which uses asyncio doesn't
114 # interfere with applications in which it's used, we always run the
115 # prompt itself in a different thread (we can't start an event loop
116 # within an event loop). This new thread won't have any event loop
117 # running, and here we run our prompt-loop.
118 self.preloop()
119
120 if intro is not None:
121 self.intro = intro
122 if self.intro:
123 print(self.intro, file=self.stdout)
124 stop = None
125 while not stop:
126 if self.cmdqueue:
127 line = self.cmdqueue.pop(0)
128 else:
129 self._ptcomp.ipy_completer.namespace = self._curframe_locals
130 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
131
132 # Run the prompt in a different thread.
133 if not _use_simple_prompt:
134 try:
135 line = self.thread_executor.submit(self._prompt).result()
136 except EOFError:
137 line = "EOF"
138 else:
139 line = input("ipdb> ")
140
141 line = self.precmd(line)
142 stop = self.onecmd(line)
143 stop = self.postcmd(stop, line)
144 self.postloop()
145
146 def do_interact(self, arg):
147 # Imported here to break the import cycle
148 # debugger -> embed -> interactiveshell -> debugger.
149 from . import embed
150
151 ipshell = embed.InteractiveShellEmbed(
152 config=self.shell.config,
153 banner1="*interactive*",
154 exit_msg="*exiting interactive console...*",
155 )
156 global_ns = self.curframe.f_globals
157 ipshell(
158 module=sys.modules.get(global_ns["__name__"], None),
159 local_ns=self._curframe_locals,
160 )
161
162
163def set_trace(frame=None):
164 """
165 Start debugging from `frame`.
166
167 If frame is not specified, debugging starts from caller's frame.
168 """
169 TerminalPdb().set_trace(frame or sys._getframe().f_back)
170
171
172if __name__ == '__main__':
173 import pdb
174 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
175 # bdb.BdbQuit. When started through __main__ and an exception
176 # happened after hitting "c", this is needed in order to
177 # be able to quit the debugging session (see #9950).
178 old_trace_dispatch = pdb.Pdb.trace_dispatch
179 pdb.Pdb = TerminalPdb # type: ignore
180 pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
181 pdb.main()