1 //===-- Highlighter.cpp -----------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/Highlighter.h"
11 #include "lldb/Target/Language.h"
12 #include "lldb/Utility/AnsiTerminal.h"
13 #include "lldb/Utility/StreamString.h"
15 using namespace lldb_private;
17 void HighlightStyle::ColorStyle::Apply(Stream &s, llvm::StringRef value) const {
18 s << m_prefix << value << m_suffix;
21 void HighlightStyle::ColorStyle::Set(llvm::StringRef prefix,
22 llvm::StringRef suffix) {
23 m_prefix = lldb_utility::ansi::FormatAnsiTerminalCodes(prefix);
24 m_suffix = lldb_utility::ansi::FormatAnsiTerminalCodes(suffix);
27 void DefaultHighlighter::Highlight(const HighlightStyle &options,
29 llvm::Optional<size_t> cursor_pos,
30 llvm::StringRef previous_lines,
32 // If we don't have a valid cursor, then we just print the line as-is.
33 if (!cursor_pos || *cursor_pos >= line.size()) {
38 // If we have a valid cursor, we have to apply the 'selected' style around
39 // the character below the cursor.
41 // Split the line around the character which is below the cursor.
42 size_t column = *cursor_pos;
43 // Print the characters before the cursor.
44 s << line.substr(0, column);
45 // Print the selected character with the defined color codes.
46 options.selected.Apply(s, line.substr(column, 1));
47 // Print the rest of the line.
48 s << line.substr(column + 1U);
51 static HighlightStyle::ColorStyle GetColor(const char *c) {
52 return HighlightStyle::ColorStyle(c, "${ansi.normal}");
55 HighlightStyle HighlightStyle::MakeVimStyle() {
56 HighlightStyle result;
57 result.comment = GetColor("${ansi.fg.purple}");
58 result.scalar_literal = GetColor("${ansi.fg.red}");
59 result.keyword = GetColor("${ansi.fg.green}");
64 HighlighterManager::getHighlighterFor(lldb::LanguageType language_type,
65 llvm::StringRef path) const {
66 Language *language = lldb_private::Language::FindPlugin(language_type, path);
67 if (language && language->GetHighlighter())
68 return *language->GetHighlighter();
72 std::string Highlighter::Highlight(const HighlightStyle &options,
74 llvm::Optional<size_t> cursor_pos,
75 llvm::StringRef previous_lines) const {
77 Highlight(options, line, cursor_pos, previous_lines, s);
79 return s.GetString().str();