1 //===-- Highlighter.cpp -----------------------------------------*- C++ -*-===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Core/Highlighter.h" 10 11 #include "lldb/Target/Language.h" 12 #include "lldb/Utility/AnsiTerminal.h" 13 #include "lldb/Utility/StreamString.h" 14 15 using namespace lldb_private; 16 17 void HighlightStyle::ColorStyle::Apply(Stream &s, llvm::StringRef value) const { 18 s << m_prefix << value << m_suffix; 19 } 20 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); 25 } 26 27 void DefaultHighlighter::Highlight(const HighlightStyle &options, 28 llvm::StringRef line, 29 llvm::Optional<size_t> cursor_pos, 30 llvm::StringRef previous_lines, 31 Stream &s) const { 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()) { 34 s << line; 35 return; 36 } 37 38 // If we have a valid cursor, we have to apply the 'selected' style around 39 // the character below the cursor. 40 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); 49 } 50 51 static HighlightStyle::ColorStyle GetColor(const char *c) { 52 return HighlightStyle::ColorStyle(c, "${ansi.normal}"); 53 } 54 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}"); 60 return result; 61 } 62 63 const Highlighter & 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(); 69 return m_default; 70 } 71 72 std::string Highlighter::Highlight(const HighlightStyle &options, 73 llvm::StringRef line, 74 llvm::Optional<size_t> cursor_pos, 75 llvm::StringRef previous_lines) const { 76 StreamString s; 77 Highlight(options, line, cursor_pos, previous_lines, s); 78 s.Flush(); 79 return s.GetString().str(); 80 } 81