INISyntaxHighlighter.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2020, Hüseyin Aslıtürk <asliturk@hotmail.com>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibGUI/INILexer.h>
  8. #include <LibGUI/INISyntaxHighlighter.h>
  9. #include <LibGfx/Palette.h>
  10. namespace GUI {
  11. static Syntax::TextStyle style_for_token_type(Gfx::Palette const& palette, IniToken::Type type)
  12. {
  13. switch (type) {
  14. case IniToken::Type::LeftBracket:
  15. case IniToken::Type::RightBracket:
  16. case IniToken::Type::Section:
  17. return { palette.syntax_keyword(), true };
  18. case IniToken::Type::Name:
  19. return { palette.syntax_identifier() };
  20. case IniToken::Type::Value:
  21. return { palette.syntax_string() };
  22. case IniToken::Type::Comment:
  23. return { palette.syntax_comment() };
  24. case IniToken::Type::Equal:
  25. return { palette.syntax_operator(), true };
  26. default:
  27. return { palette.base_text() };
  28. }
  29. }
  30. bool IniSyntaxHighlighter::is_identifier(u64 token) const
  31. {
  32. auto ini_token = static_cast<GUI::IniToken::Type>(token);
  33. return ini_token == GUI::IniToken::Type::Name;
  34. }
  35. void IniSyntaxHighlighter::rehighlight(Palette const& palette)
  36. {
  37. auto text = m_client->get_text();
  38. IniLexer lexer(text);
  39. auto tokens = lexer.lex();
  40. Vector<GUI::TextDocumentSpan> spans;
  41. for (auto& token : tokens) {
  42. GUI::TextDocumentSpan span;
  43. span.range.set_start({ token.m_start.line, token.m_start.column });
  44. span.range.set_end({ token.m_end.line, token.m_end.column });
  45. auto style = style_for_token_type(palette, token.m_type);
  46. span.attributes.color = style.color;
  47. span.attributes.bold = style.bold;
  48. span.is_skippable = token.m_type == IniToken::Type::Whitespace;
  49. span.data = static_cast<u64>(token.m_type);
  50. spans.append(span);
  51. }
  52. m_client->do_set_spans(move(spans));
  53. m_has_brace_buddies = false;
  54. highlight_matching_token_pair();
  55. m_client->do_update();
  56. }
  57. Vector<IniSyntaxHighlighter::MatchingTokenPair> IniSyntaxHighlighter::matching_token_pairs_impl() const
  58. {
  59. static Vector<MatchingTokenPair> pairs;
  60. if (pairs.is_empty()) {
  61. pairs.append({ static_cast<u64>(IniToken::Type::LeftBracket), static_cast<u64>(IniToken::Type::RightBracket) });
  62. }
  63. return pairs;
  64. }
  65. bool IniSyntaxHighlighter::token_types_equal(u64 token1, u64 token2) const
  66. {
  67. return static_cast<GUI::IniToken::Type>(token1) == static_cast<GUI::IniToken::Type>(token2);
  68. }
  69. }