Coverage for src/homeassistant_repl/editor.py: 98%

103 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""The interactive shells' line editor: one prompt_toolkit buffer per 

2statement, not per line. 

3 

4A whole `for` loop is typed, edited and kept in history as one entry, so Up 

5brings back the complete block and any line of it can be changed before 

6running it again - the same as Python 3.13+'s own REPL. Enter runs the code 

7once it's a complete statement and the cursor is at the end, otherwise it 

8starts a new line, indented to match (one level deeper after a `:`). As in 

9the classic REPL, a block is finished by an empty line; Alt-Enter (Esc then 

10Enter) runs whatever is there straight away. 

11 

12Ctrl-C while code runs stops it - see run_interruptibly(). 

13""" 

14 

15from __future__ import annotations 

16 

17import ast 

18import asyncio 

19import codeop 

20import signal 

21import sys 

22from collections.abc import Awaitable, Callable 

23from pathlib import Path 

24from typing import Any 

25 

26from prompt_toolkit import PromptSession 

27from prompt_toolkit.application import run_in_terminal 

28from prompt_toolkit.completion import Completer 

29from prompt_toolkit.history import FileHistory 

30from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent 

31from prompt_toolkit.lexers import PygmentsLexer 

32from prompt_toolkit.styles import Style 

33from pygments.lexers.python import PythonLexer 

34from rich.text import Text 

35 

36from .complete import expression_at 

37from .completer import HaCompleter 

38from .local_session import console 

39from .shellhelp import doc_text 

40 

41INDENT = " " 

42 

43# A statement starting with one of these ends its block, so the line after it 

44# starts a level shallower. 

45_DEDENT_AFTER = ("return", "pass", "break", "continue", "raise") 

46 

47# The toolbar holds only the signature of the call being typed: plain, not 

48# the usual reversed bar. 

49_STYLE = Style.from_dict({ 

50 "bottom-toolbar": "noreverse", 

51 "signature": "", 

52 "signature.active": "bold underline", 

53 "signature.doc": "italic", 

54 "signature.ha": "fg:ansicyan", 

55}) 

56 

57_compiler = codeop.CommandCompiler() 

58_compiler.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT 

59 

60 

61def python_prompt( 

62 history: Path, completer: Completer | None = None 

63) -> PromptSession[str]: 

64 """A prompt reading one complete statement (or block) per call - with 

65 the signature of the call being typed under it, given an HaCompleter.""" 

66 session: PromptSession[str] = PromptSession( 

67 history=FileHistory(str(history)), 

68 lexer=PygmentsLexer(PythonLexer), 

69 multiline=True, 

70 key_bindings=_key_bindings(completer), 

71 prompt_continuation="... ", 

72 completer=completer, 

73 complete_while_typing=completer is not None, 

74 style=_STYLE, 

75 ) 

76 if isinstance(completer, HaCompleter): 

77 completer.signatures.attach(session) 

78 return session 

79 

80 

81def is_complete(source: str) -> bool: 

82 """True once `source` is ready to run: a complete statement, a block 

83 ended by an empty line, or something that will never compile (run anyway, 

84 so the session reports the error like any other).""" 

85 lines = source.split("\n") 

86 if len(lines) > 1 and not lines[-1].strip(): 

87 return True 

88 try: 

89 # None means incomplete input: keep reading continuation lines. 

90 return _compiler(source, "<ha_repl>", "single") is not None 

91 except SyntaxError, OverflowError, ValueError: 

92 return True 

93 

94 

95def next_indent(line: str) -> str: 

96 """The indentation for the line following `line`.""" 

97 indent = line[: len(line) - len(line.lstrip())] 

98 stripped = line.strip() 

99 if stripped.endswith(":") and not stripped.startswith("#"): 

100 return indent + INDENT 

101 if stripped.split(" ", 1)[0] in _DEDENT_AFTER: 

102 return indent[: -len(INDENT)] 

103 return indent 

104 

105 

106def _key_bindings(completer: Completer | None = None) -> KeyBindings: 

107 kb = KeyBindings() 

108 

109 if isinstance(completer, HaCompleter): 

110 # Ctrl-Shift-Space, as VSCode's Trigger Parameter Hints - most 

111 # terminals send it as Ctrl-Space, so this takes both. 

112 @kb.add("c-space") 

113 def _describe(event: KeyPressEvent) -> None: 

114 document = event.current_buffer.document 

115 expression = expression_at( 

116 document.text_before_cursor, document.text_after_cursor 

117 ) 

118 if expression: 118 ↛ exitline 118 didn't return from function '_describe' because the condition on line 118 was always true

119 event.app.create_background_task(_show(completer, expression)) 

120 

121 @kb.add("enter") 

122 def _enter(event: KeyPressEvent) -> None: 

123 buffer = event.current_buffer 

124 if buffer.complete_state and buffer.complete_state.current_completion: 

125 # A completion picked from the menu is already in: just close it. 

126 buffer.complete_state = None 

127 return 

128 document = buffer.document 

129 if document.is_cursor_at_the_end and is_complete(document.text): 

130 _accept(event) 

131 else: 

132 buffer.insert_text("\n" + next_indent(document.current_line_before_cursor)) 

133 

134 @kb.add("escape", "enter") 

135 def _run_now(event: KeyPressEvent) -> None: 

136 _accept(event) 

137 

138 return kb 

139 

140 

141async def _show(completer: HaCompleter, expression: str) -> None: 

142 """What `expression` is, printed above the prompt, which keeps what's 

143 typed.""" 

144 found = await completer.describe(expression) 

145 text = ( 

146 doc_text(found) 

147 if found 

148 else Text(f"Can't tell what `{expression}` is without running it") 

149 ) 

150 await run_in_terminal(lambda: console.print(text)) 

151 

152 

153def _accept(event: KeyPressEvent) -> None: 

154 """Run the buffer, minus the empty line that ended a block - so history 

155 keeps just the code.""" 

156 buffer = event.current_buffer 

157 buffer.text = buffer.text.rstrip() 

158 buffer.validate_and_handle() 

159 

160 

161async def run_interruptibly( 

162 run: Awaitable[Any], interrupt: Callable[[], bool] | None = None 

163) -> None: 

164 """Await `run`, with Ctrl-C stopping it instead of the shell. 

165 

166 The first Ctrl-C goes to `interrupt`, if given: True means it has asked 

167 for the code to stop some other way (code running in Home Assistant, 

168 told to stop there) and `run` is left to finish with that code's own 

169 report of where it stopped. Otherwise, or on the next Ctrl-C, `run` is 

170 cancelled. Code that never gives the event loop back - a blocking call 

171 in local code - can't be cancelled, so a Ctrl-C arriving while the last 

172 one is still waiting for the loop raises KeyboardInterrupt in it instead. 

173 """ 

174 loop = asyncio.get_running_loop() 

175 task = asyncio.ensure_future(run) 

176 pending = False 

177 interrupted = False 

178 

179 def stop() -> None: 

180 nonlocal pending, interrupted 

181 pending = False 

182 if interrupt is not None and not interrupted and interrupt(): 

183 interrupted = True 

184 else: 

185 task.cancel() 

186 

187 def on_sigint(_signum: int, _frame: Any) -> None: 

188 nonlocal pending 

189 if pending: 

190 raise KeyboardInterrupt 

191 pending = True 

192 loop.call_soon_threadsafe(stop) 

193 

194 previous = signal.signal(signal.SIGINT, on_sigint) 

195 try: 

196 await task 

197 except asyncio.CancelledError: 

198 current = asyncio.current_task() 

199 if current is not None and current.cancelling(): 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true

200 raise 

201 print("Stopped", file=sys.stderr) 

202 finally: 

203 signal.signal(signal.SIGINT, previous)