RegularEditingEngine.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibGUI/RegularEditingEngine.h>
  8. #include <LibGUI/TextEditor.h>
  9. namespace GUI {
  10. CursorWidth RegularEditingEngine::cursor_width() const
  11. {
  12. return CursorWidth::NARROW;
  13. }
  14. bool RegularEditingEngine::on_key(KeyEvent const& event)
  15. {
  16. if (EditingEngine::on_key(event))
  17. return true;
  18. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  19. sort_selected_lines();
  20. return true;
  21. }
  22. return false;
  23. }
  24. static int strcmp_utf32(u32 const* s1, u32 const* s2, size_t n)
  25. {
  26. while (n-- > 0) {
  27. if (*s1++ != *s2++)
  28. return s1[-1] < s2[-1] ? -1 : 1;
  29. }
  30. return 0;
  31. }
  32. void RegularEditingEngine::sort_selected_lines()
  33. {
  34. if (!m_editor->is_editable())
  35. return;
  36. if (!m_editor->has_selection())
  37. return;
  38. size_t first_line;
  39. size_t last_line;
  40. get_selection_line_boundaries(first_line, last_line);
  41. auto& lines = m_editor->document().lines();
  42. auto start = lines.begin() + (int)first_line;
  43. auto end = lines.begin() + (int)last_line + 1;
  44. quick_sort(start, end, [](auto& a, auto& b) {
  45. return strcmp_utf32(a->code_points(), b->code_points(), min(a->length(), b->length())) < 0;
  46. });
  47. m_editor->did_change();
  48. m_editor->update();
  49. }
  50. }