Skip to content

Commit

Permalink
feat(keymap): add indent/dedent in insert mode
Browse files Browse the repository at this point in the history
  • Loading branch information
liljaylj committed Sep 4, 2023
1 parent 490cf90 commit 1f87714
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
21 changes: 11 additions & 10 deletions src/prompt_toolkit/buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1936,29 +1936,32 @@ def indent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
Indent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
current_col = buffer.document.cursor_position_col
line_range = range(from_row, to_row)

# Apply transformation.
new_text = buffer.transform_lines(line_range, lambda l: " " * count + l)
indent_content = " " * count
new_text = buffer.transform_lines(line_range, lambda l: indent_content + l)
buffer.document = Document(
new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
)

# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
# Place cursor in the same position in text after indenting
buffer.cursor_position += current_col + len(indent_content)


def unindent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
"""
Unindent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
current_col = buffer.document.cursor_position_col
line_range = range(from_row, to_row)

indent_content = " " * count

def transform(text: str) -> str:
remove = " " * count
remove = indent_content
if text.startswith(remove):
return text[len(remove) :]
else:
Expand All @@ -1970,10 +1973,8 @@ def transform(text: str) -> str:
new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
)

# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
# Place cursor in the same position in text after dedent
buffer.cursor_position += current_col - len(indent_content)


def reshape_text(buffer: Buffer, from_row: int, to_row: int) -> None:
Expand Down
2 changes: 2 additions & 0 deletions src/prompt_toolkit/key_binding/bindings/vi.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,7 @@ def _prev_line(event: E) -> None:
)

@handle(">", ">", filter=vi_navigation_mode)
@handle("c-t", filter=vi_insert_mode)
def _indent(event: E) -> None:
"""
Indent lines.
Expand All @@ -971,6 +972,7 @@ def _indent(event: E) -> None:
indent(buffer, current_row, current_row + event.arg)

@handle("<", "<", filter=vi_navigation_mode)
@handle("c-d", filter=vi_insert_mode)
def _unindent(event: E) -> None:
"""
Unindent lines.
Expand Down

0 comments on commit 1f87714

Please sign in to comment.