GMLSyntaxHighlighter.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGUI/GMLLexer.h>
  7. #include <LibGUI/GMLSyntaxHighlighter.h>
  8. #include <LibGUI/TextEditor.h>
  9. #include <LibGfx/Font.h>
  10. #include <LibGfx/Palette.h>
  11. namespace GUI {
  12. static Syntax::TextStyle style_for_token_type(const Gfx::Palette& palette, GMLToken::Type type)
  13. {
  14. switch (type) {
  15. case GMLToken::Type::LeftCurly:
  16. case GMLToken::Type::RightCurly:
  17. return { palette.syntax_punctuation() };
  18. case GMLToken::Type::ClassMarker:
  19. return { palette.syntax_keyword() };
  20. case GMLToken::Type::ClassName:
  21. return { palette.syntax_identifier(), true };
  22. case GMLToken::Type::Identifier:
  23. return { palette.syntax_identifier() };
  24. case GMLToken::Type::JsonValue:
  25. return { palette.syntax_string() };
  26. case GMLToken::Type::Comment:
  27. return { palette.syntax_comment() };
  28. default:
  29. return { palette.base_text() };
  30. }
  31. }
  32. bool GMLSyntaxHighlighter::is_identifier(u64 token) const
  33. {
  34. auto ini_token = static_cast<GUI::GMLToken::Type>(token);
  35. return ini_token == GUI::GMLToken::Type::Identifier;
  36. }
  37. void GMLSyntaxHighlighter::rehighlight(const Palette& palette)
  38. {
  39. auto text = m_client->get_text();
  40. GMLLexer lexer(text);
  41. auto tokens = lexer.lex();
  42. Vector<GUI::TextDocumentSpan> spans;
  43. for (auto& token : tokens) {
  44. GUI::TextDocumentSpan span;
  45. span.range.set_start({ token.m_start.line, token.m_start.column });
  46. span.range.set_end({ token.m_end.line, token.m_end.column });
  47. auto style = style_for_token_type(palette, token.m_type);
  48. span.attributes.color = style.color;
  49. span.attributes.bold = style.bold;
  50. span.is_skippable = false;
  51. span.data = static_cast<u64>(token.m_type);
  52. spans.append(span);
  53. }
  54. m_client->do_set_spans(move(spans));
  55. m_has_brace_buddies = false;
  56. highlight_matching_token_pair();
  57. m_client->do_update();
  58. }
  59. Vector<GMLSyntaxHighlighter::MatchingTokenPair> GMLSyntaxHighlighter::matching_token_pairs_impl() const
  60. {
  61. static Vector<MatchingTokenPair> pairs;
  62. if (pairs.is_empty()) {
  63. pairs.append({ static_cast<u64>(GMLToken::Type::LeftCurly), static_cast<u64>(GMLToken::Type::RightCurly) });
  64. }
  65. return pairs;
  66. }
  67. bool GMLSyntaxHighlighter::token_types_equal(u64 token1, u64 token2) const
  68. {
  69. return static_cast<GUI::GMLToken::Type>(token1) == static_cast<GUI::GMLToken::Type>(token2);
  70. }
  71. GMLSyntaxHighlighter::~GMLSyntaxHighlighter()
  72. {
  73. }
  74. }