summaryrefslogtreecommitdiffstats
path: root/Lib/_pyrepl/readline.py
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2024-05-31 09:51:53 (GMT)
committerGitHub <noreply@github.com>2024-05-31 09:51:53 (GMT)
commit38bf39cb4be279cce6c97da26afcc60859a01571 (patch)
tree54e2ae975d993aac16c5e88312fd64a2ed5776fe /Lib/_pyrepl/readline.py
parent7dae73b21b500e34ebb070a4d3774e09d83d6c1d (diff)
downloadcpython-38bf39cb4be279cce6c97da26afcc60859a01571.zip
cpython-38bf39cb4be279cce6c97da26afcc60859a01571.tar.gz
cpython-38bf39cb4be279cce6c97da26afcc60859a01571.tar.bz2
[3.13] gh-111201: Improve pyrepl auto indentation (GH-119606) (GH-119833)
- auto-indent when editing multi-line block - ignore comments (cherry picked from commit dae0375bd97f3821c5db1602a0653a3c5dc53c5b) Co-authored-by: Arnon Yaari <wiggin15@yahoo.com>
Diffstat (limited to 'Lib/_pyrepl/readline.py')
-rw-r--r--Lib/_pyrepl/readline.py27
1 files changed, 19 insertions, 8 deletions
diff --git a/Lib/_pyrepl/readline.py b/Lib/_pyrepl/readline.py
index ffa14a9..01da926 100644
--- a/Lib/_pyrepl/readline.py
+++ b/Lib/_pyrepl/readline.py
@@ -230,13 +230,24 @@ def _get_first_indentation(buffer: list[str]) -> str | None:
return None
-def _is_last_char_colon(buffer: list[str]) -> bool:
- i = len(buffer)
- while i > 0:
- i -= 1
- if buffer[i] not in " \t\n": # ignore whitespaces
- return buffer[i] == ":"
- return False
+def _should_auto_indent(buffer: list[str], pos: int) -> bool:
+ # check if last character before "pos" is a colon, ignoring
+ # whitespaces and comments.
+ last_char = None
+ while pos > 0:
+ pos -= 1
+ if last_char is None:
+ if buffer[pos] not in " \t\n": # ignore whitespaces
+ last_char = buffer[pos]
+ else:
+ # even if we found a non-whitespace character before
+ # original pos, we keep going back until newline is reached
+ # to make sure we ignore comments
+ if buffer[pos] == "\n":
+ break
+ if buffer[pos] == "#":
+ last_char = None
+ return last_char == ":"
class maybe_accept(commands.Command):
@@ -273,7 +284,7 @@ class maybe_accept(commands.Command):
for i in range(prevlinestart, prevlinestart + indent):
r.insert(r.buffer[i])
r.update_last_used_indentation()
- if _is_last_char_colon(r.buffer):
+ if _should_auto_indent(r.buffer, r.pos):
if r.last_used_indentation is not None:
indentation = r.last_used_indentation
else: