@@ -67,24 +67,58 @@ class PromptStripper:
6767 If any prompt is found on the first two lines,
6868 prompts will be stripped from the rest of the block.
6969 """
70- def __init__ (self , prompt_re , initial_re = None ):
70+ def __init__ (self , prompt_re , initial_re = None , * , doctest = False ):
7171 self .prompt_re = prompt_re
7272 self .initial_re = initial_re or prompt_re
73+ self .doctest = doctest
74+ if doctest :
75+ # Doctest/xdoctest prompts may be indented (e.g. " >>>").
76+ # We only treat "..." as a continuation prompt when the same pasted
77+ # block contains at least one ">>>" line, to avoid ambiguity with the
78+ # Python Ellipsis literal.
79+ self ._doctest_initial_re = re .compile (r'^\s*>>>' )
80+ self ._doctest_ps1_re = re .compile (r'^\s*>>>\s?' )
81+ self ._doctest_ps2_re = re .compile (r'^\s*\.\.\.\s?' )
7382
7483 def _strip (self , lines ):
7584 return [self .prompt_re .sub ('' , l , count = 1 ) for l in lines ]
7685
7786 def __call__ (self , lines ):
7887 if not lines :
7988 return lines
89+
90+ if self .doctest :
91+ if not any (self ._doctest_initial_re .match (l ) for l in lines ):
92+ return lines
93+
94+ stripped_any = False
95+ out_lines = []
96+ for l in lines :
97+ if self ._doctest_ps1_re .match (l ):
98+ new_l = self ._doctest_ps1_re .sub ('' , l , count = 1 )
99+ elif self ._doctest_ps2_re .match (l ):
100+ new_l = self ._doctest_ps2_re .sub ('' , l , count = 1 )
101+ else :
102+ new_l = l
103+ stripped_any = stripped_any or (new_l != l )
104+ out_lines .append (new_l )
105+
106+ if not stripped_any :
107+ return out_lines
108+
109+ # Only dedent when we actually stripped doctest prompts, so we don't
110+ # change the indentation semantics of normal pastes.
111+ return dedent ('' .join (out_lines )).splitlines (keepends = True )
112+
80113 if self .initial_re .match (lines [0 ]) or \
81114 (len (lines ) > 1 and self .prompt_re .match (lines [1 ])):
82115 return self ._strip (lines )
83116 return lines
84117
85118classic_prompt = PromptStripper (
86119 prompt_re = re .compile (r'^(>>>|\.\.\.)( |$)' ),
87- initial_re = re .compile (r'^>>>( |$)' )
120+ initial_re = re .compile (r'^>>>( |$)' ),
121+ doctest = True ,
88122)
89123
90124ipython_prompt = PromptStripper (
0 commit comments