From 19c575e116f44b2b5b7287af4e15cdeb3e511c80 Mon Sep 17 00:00:00 2001 From: Aaron Gyes Date: Wed, 25 Sep 2019 04:03:47 -0700 Subject: [PATCH] builtin functions: colorize output if interactive We can also get rid of the | fish_indent --ansi stuff in type.fish --- share/functions/type.fish | 6 +----- src/builtin_functions.cpp | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/share/functions/type.fish b/share/functions/type.fish index 66df5ee6b..7145056c3 100644 --- a/share/functions/type.fish +++ b/share/functions/type.fish @@ -49,11 +49,7 @@ function type --description 'Print the type of a command' switch $mode case normal printf (_ '%s is a function with definition\n') $i - if isatty stdout - functions $i | fish_indent --ansi - else - functions $i | fish_indent - end + functions $i case type echo (_ 'function') case path diff --git a/src/builtin_functions.cpp b/src/builtin_functions.cpp index d55a43bae..b871bff9e 100644 --- a/src/builtin_functions.cpp +++ b/src/builtin_functions.cpp @@ -20,6 +20,7 @@ #include "event.h" #include "fallback.h" // IWYU pragma: keep #include "function.h" +#include "highlight.h" #include "io.h" #include "parser_keywords.h" #include "proc.h" @@ -261,7 +262,15 @@ static int report_function_metadata(const wchar_t *funcname, bool verbose, io_st if (metadata_as_comments) { if (std::wcscmp(path, L"stdin")) { - streams.out.append_format(L"# Defined in %ls @ line %d\n", path, line_number); + wcstring comment; + append_format(comment, L"# Defined in %ls @ line %d\n", path, line_number); + if (!streams.out_is_redirected && isatty(STDOUT_FILENO)) { + std::vector colors; + highlight_shell_no_io(comment, colors, comment.size(), nullptr, env_stack_t::globals()); + streams.out.append(str2wcstring(colorize(comment, colors))); + } else { + streams.out.append(comment); + } } } else { streams.out.append_format(L"%ls\n", path); @@ -426,7 +435,15 @@ int builtin_functions(parser_t &parser, io_streams_t &streams, wchar_t **argv) { if (i != optind) streams.out.append(L"\n"); const wchar_t *funcname = argv[optind]; report_function_metadata(funcname, opts.verbose, streams, parser, true); - streams.out.append(functions_def(funcname)); + wcstring def = functions_def(funcname); + + if (!streams.out_is_redirected && isatty(STDOUT_FILENO)) { + std::vector colors; + highlight_shell_no_io(def, colors, def.size(), nullptr, env_stack_t::globals()); + streams.out.append(str2wcstring(colorize(def, colors))); + } else { + streams.out.append(def); + } } } }