SyntaxHighlighter.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SyntaxHighlighter.h"
  7. #include <LibCMake/CMakeCache/Lexer.h>
  8. namespace CMake::Cache {
  9. static Gfx::TextAttributes style_for_token_type(Gfx::Palette const& palette, Token::Type type)
  10. {
  11. switch (type) {
  12. case Token::Type::Comment:
  13. case Token::Type::HelpText:
  14. return { palette.syntax_comment() };
  15. case Token::Type::Key:
  16. return { palette.syntax_identifier() };
  17. case Token::Type::Type:
  18. return { palette.syntax_type() };
  19. case Token::Type::Colon:
  20. case Token::Type::Equals:
  21. return { palette.syntax_punctuation() };
  22. case Token::Type::Value:
  23. return { palette.syntax_string() };
  24. case Token::Type::Garbage:
  25. return { palette.red(), {}, false, Gfx::TextAttributes::UnderlineStyle::Wavy, palette.red() };
  26. default:
  27. return { palette.base_text() };
  28. }
  29. }
  30. bool SyntaxHighlighter::is_identifier(u64 token_type) const
  31. {
  32. auto cmake_token = static_cast<Token::Type>(token_type);
  33. return cmake_token == Token::Type::Key;
  34. }
  35. void SyntaxHighlighter::rehighlight(Gfx::Palette const& palette)
  36. {
  37. auto text = m_client->get_text();
  38. auto tokens = Lexer::lex(text).release_value_but_fixme_should_propagate_errors();
  39. Vector<Syntax::TextDocumentSpan> spans;
  40. auto highlight_span = [&](Token::Type type, Position const& start, Position const& end) {
  41. Syntax::TextDocumentSpan span;
  42. span.range.set_start({ start.line, start.column });
  43. span.range.set_end({ end.line, end.column });
  44. if (!span.range.is_valid())
  45. return;
  46. span.attributes = style_for_token_type(palette, type);
  47. span.is_skippable = false;
  48. span.data = static_cast<u64>(type);
  49. spans.append(move(span));
  50. };
  51. for (auto const& token : tokens) {
  52. highlight_span(token.type, token.start, token.end);
  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<SyntaxHighlighter::MatchingTokenPair> SyntaxHighlighter::matching_token_pairs_impl() const
  60. {
  61. static Vector<MatchingTokenPair> empty;
  62. return empty;
  63. }
  64. bool SyntaxHighlighter::token_types_equal(u64 token1, u64 token2) const
  65. {
  66. return static_cast<Token::Type>(token1) == static_cast<Token::Type>(token2);
  67. }
  68. }