浏览代码

TextEditor: Add keyboard shortcut to (un)comment a range of lines

Kyle Lanmon 2 年之前
父节点
当前提交
62a3de0c0a
共有 1 个文件被更改,包括 24 次插入0 次删除
  1. 24 0
      Userland/Libraries/LibGUI/TextEditor.cpp

+ 24 - 0
Userland/Libraries/LibGUI/TextEditor.cpp

@@ -1008,6 +1008,30 @@ void TextEditor::keydown_event(KeyEvent& event)
         return;
     }
 
+    if (event.ctrl() && event.key() == KeyCode::Key_Slash) {
+        if (m_highlighter != nullptr) {
+            auto prefix = m_highlighter->comment_prefix().value_or(""sv);
+            auto suffix = m_highlighter->comment_suffix().value_or(""sv);
+            auto range = has_selection() ? selection() : TextRange { { m_cursor.line(), m_cursor.column() }, { m_cursor.line(), m_cursor.column() } };
+
+            auto is_already_commented = true;
+            for (size_t i = range.start().line(); i <= range.end().line(); i++) {
+                auto text = m_document->line(i).to_utf8().trim_whitespace();
+                if (!(text.starts_with(prefix) && text.ends_with(suffix))) {
+                    is_already_commented = false;
+                    break;
+                }
+            }
+
+            if (is_already_commented)
+                execute<UncommentSelection>(prefix, suffix, range);
+            else
+                execute<CommentSelection>(prefix, suffix, range);
+
+            return;
+        }
+    }
+
     event.ignore();
 }