Improve PyREPL auto-indentation
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
On second thought this issue should be an enhancement instead of a bug report. Sorry for the wrong template.
Bug description:
There are some cases where _pyrepl auto-indentation works not well.
Cases
- A line ending with
:in a multi-line string is wrongly indented.
Observed
>>> s = '''
... Note:
... ␣␣␣␣|
Expected
>>> s = '''
... Note:
... |
#inside strings is seen as a comment, the following:is ignored.
Observed
>>> if ' ' == '#':
... |
Expected
>>> if ' ' == '#':
... ␣␣␣␣|
- When the entire cursor line is a comment and is already indented, pressing Enter gives a further indent.
Observed
>>> def f():
... # foo⤶
... ␣␣␣␣␣␣␣␣|
Expected
>>> def f():
... # foo⤶
... ␣␣␣␣|
Possible solution
Currently _should_auto_indent() parses the buffer from right to left and stops at the first newline it encounters. Only the last line that is not a comment line of the buffer is parsed.
But by parsing from right to left we can't tell if a # starts a comment or is part of a string. For example if we, from right to left, encounter a " first and then a #, we don't know if the # is a comment. To know that, we need to know if the " is a string boundary, but the # might comment out the ", so we can't be sure. There is a information dependency cycle.
To fix this I made a change to parse the buffer from left to right, keeping track of whether current char is inside a string or a comment. This approach solves the above three cases. However the whole buffer is parsed on every call of _should_auto_indent(), with very long buffer, there might be noticeable delay when pressing Enter.
I think this is a big change. It affects how _should_auto_indent() works as a whole. I am hesitated to create a PR and just put it here first to hopefully get feedback.
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs
- gh-140710
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Lib/_pyrepl/readline.py 中的 _should_auto_indent() 开始,然后检查它如何从右到左解析 buffer。重现 issue 中描述的 multiline-string、string-comment 和 indented-comment 三种情况,并将其行为与建议的从左到右解析方法进行比较。当自动缩进与预期示例一致,且不会为较长的 buffer 引入明显延迟时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- cli
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100