Skip to content

Commit

Permalink
Text Editor: Improve CTRL+K commenting behaviour
Browse files Browse the repository at this point in the history
Closer to the script editors commenting behaviour:
- Only uncomments if ALL selected lines are comments (this also prevents erasing the beginning of lines)
- Preserves selection properly!
  • Loading branch information
Jowan-Spooner committed Sep 12, 2024
1 parent 975e1eb commit 0838ba8
Showing 1 changed file with 21 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,21 +91,37 @@ func _gui_input(event):
# Toggle the selected lines as comments
func toggle_comment() -> void:
var cursor: Vector2 = Vector2(get_caret_column(), get_caret_line())
var selection := Rect2i(
Vector2i(get_selection_origin_line(), get_selection_origin_column()),
Vector2i(get_caret_line(), get_caret_column()))
var from: int = cursor.y
var to: int = cursor.y
if has_selection():
from = get_selection_from_line()
to = get_selection_to_line()

var lines: PackedStringArray = text.split("\n")
var will_comment: bool = not lines[from].begins_with("# ")
var will_comment: bool = false
for i in range(from, to+1):
if not lines[i].begins_with("#"):
will_comment = true

for i in range(from, to + 1):
lines[i] = "# " + lines[i] if will_comment else lines[i].substr(2)
if will_comment:
lines[i] = "#" + lines[i]
else:
lines[i] = lines[i].trim_prefix("#")

text = "\n".join(lines)
select(from, 0, to, get_line_width(to))
set_caret_line(cursor.y)
set_caret_column(cursor.x)
if will_comment:
cursor.x += 1
selection.position.y += 1
selection.size.y += 1
else:
cursor.x -= 1
selection.position.y -= 1
selection.size.y -= 1
select(selection.position.x, selection.position.y, selection.size.x, selection.size.y)
text_changed.emit()


Expand Down

0 comments on commit 0838ba8

Please sign in to comment.