Path: blob/main/contrib/llvm-project/lldb/source/Core/Highlighter.cpp
39587 views
//===-- Highlighter.cpp ---------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Core/Highlighter.h"910#include "lldb/Target/Language.h"11#include "lldb/Utility/AnsiTerminal.h"12#include "lldb/Utility/StreamString.h"13#include <optional>1415using namespace lldb_private;16using namespace lldb_private::ansi;1718void HighlightStyle::ColorStyle::Apply(Stream &s, llvm::StringRef value) const {19s << m_prefix << value << m_suffix;20}2122void HighlightStyle::ColorStyle::Set(llvm::StringRef prefix,23llvm::StringRef suffix) {24m_prefix = FormatAnsiTerminalCodes(prefix);25m_suffix = FormatAnsiTerminalCodes(suffix);26}2728void DefaultHighlighter::Highlight(const HighlightStyle &options,29llvm::StringRef line,30std::optional<size_t> cursor_pos,31llvm::StringRef previous_lines,32Stream &s) const {33// If we don't have a valid cursor, then we just print the line as-is.34if (!cursor_pos || *cursor_pos >= line.size()) {35s << line;36return;37}3839// If we have a valid cursor, we have to apply the 'selected' style around40// the character below the cursor.4142// Split the line around the character which is below the cursor.43size_t column = *cursor_pos;44// Print the characters before the cursor.45s << line.substr(0, column);46// Print the selected character with the defined color codes.47options.selected.Apply(s, line.substr(column, 1));48// Print the rest of the line.49s << line.substr(column + 1U);50}5152static HighlightStyle::ColorStyle GetColor(const char *c) {53return HighlightStyle::ColorStyle(c, "${ansi.normal}");54}5556HighlightStyle HighlightStyle::MakeVimStyle() {57HighlightStyle result;58result.comment = GetColor("${ansi.fg.purple}");59result.scalar_literal = GetColor("${ansi.fg.red}");60result.keyword = GetColor("${ansi.fg.green}");61return result;62}6364const Highlighter &65HighlighterManager::getHighlighterFor(lldb::LanguageType language_type,66llvm::StringRef path) const {67Language *language = lldb_private::Language::FindPlugin(language_type, path);68if (language && language->GetHighlighter())69return *language->GetHighlighter();70return m_default;71}7273std::string Highlighter::Highlight(const HighlightStyle &options,74llvm::StringRef line,75std::optional<size_t> cursor_pos,76llvm::StringRef previous_lines) const {77StreamString s;78Highlight(options, line, cursor_pos, previous_lines, s);79s.Flush();80return s.GetString().str();81}828384