r""" Insert \n at the cursor position. Also add necessary padding.
(buffer: Buffer)
| 308 | |
| 309 | |
| 310 | def auto_newline(buffer: Buffer) -> None: |
| 311 | r""" |
| 312 | Insert \n at the cursor position. Also add necessary padding. |
| 313 | """ |
| 314 | insert_text = buffer.insert_text |
| 315 | |
| 316 | if buffer.document.current_line_after_cursor: |
| 317 | # When we are in the middle of a line. Always insert a newline. |
| 318 | insert_text("\n") |
| 319 | else: |
| 320 | # Go to new line, but also add indentation. |
| 321 | current_line = buffer.document.current_line_before_cursor.rstrip() |
| 322 | insert_text("\n") |
| 323 | |
| 324 | # Unident if the last line ends with 'pass', remove four spaces. |
| 325 | unindent = current_line.rstrip().endswith(" pass") |
| 326 | |
| 327 | # Copy whitespace from current line |
| 328 | current_line2 = current_line[4:] if unindent else current_line |
| 329 | |
| 330 | for c in current_line2: |
| 331 | if c.isspace(): |
| 332 | insert_text(c) |
| 333 | else: |
| 334 | break |
| 335 | |
| 336 | # If the last line ends with a colon, add four extra spaces. |
| 337 | if current_line[-1:] == ":": |
| 338 | for x in range(4): |
| 339 | insert_text(" ") |