INISyntaxHighlighter.cpp 2.5 KB

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