Certainly! Let's break down the Elixir code you provided step by step, and then I'll rewrite it in Erlang with improvements to meet your requirements.
Step-by-Step Explanation of the Elixir Code
The Elixir script ChatbotFormatter is designed to read input from the standard input in real time, process it, and apply syntax highlighting to code blocks and markdown content. Here's how it works:
-
Module Definition and Configuration:
- The module
ChatbotFormatter is defined with a default configuration @default_config that includes:
max_width: Maximum width for text wrapping.
indent: Indentation string.
colors: ANSI color codes for styling the output.
-
Entry Point (run/1 Function):
- The
run/1 function is the entry point of the script.
- It retrieves the terminal width using
get_terminal_width(config).
- Sets the IO mode to raw for real-time input handling with
:io.setopts(:standard_io, [mode: :line, echo: false]).
- Calls
process_input(width, config) to start processing input.
-
Input Processing (process_input/2 Function):
- Reads input character by character using
IO.getn("", 1).
- Depending on the input:
- If
:eof, it stops processing.
- If there's an error, it prints the error.
- Otherwise, it calls
handle_char(char, width, config) to handle the character.
-
Character Handling (handle_char/3 Function):
- If the character is a newline
\n, it reads the line with IO.gets("") and processes it with process_line(line, width, config).
- Otherwise, it writes the character with green color.
-
Line Processing (process_line/3 Function):
- Trims the input line and checks if it starts with a code block delimiter ``` (three backticks).
- If it is a code block, it calls
process_code_block(line, width, config).
- Otherwise, it formats and displays the AI response with
format_ai_response(trimmed_line, width, config).
-
Code Block Processing (process_code_block/3 Function):
- Extracts the language from the code block delimiter if specified.
- Prints the code block delimiter with the language.
- Calls
process_code_lines(width, config) to process the lines within the code block.
-
Processing Code Lines (process_code_lines/2 Function):
- Reads lines until it encounters the closing code block delimiter ``` (three backticks).
- For each line, it applies syntax highlighting with
format_code(line, width, config) and prints it.
- Once the closing delimiter is found, it prints it.
-
AI Response Formatting (format_ai_response/3 Function):
- Highlights markdown content using
format_markdown(line, width, config).
- Wraps the content inside a box drawn with ASCII characters.
- Uses the
magenta color for the box borders.
-
Markdown Highlighting (highlight_markdown/2 Function):
- Applies regex-based rules to highlight markdown syntax (headers, bold, italic, inline code, links, lists).
- Uses ANSI color codes to style the matched patterns.
-
Code Highlighting (highlight_code/2 Function):
- Applies regex-based rules to highlight code syntax for various programming constructs.
- Styles keywords, strings, numbers, operators, and comments.
-
Text Wrapping (wrap_text/2 Function):
- Wraps the input text to the specified width.
- Splits the text into words and constructs lines that fit within the width.
-
Utility Functions:
apply_highlight_rules/3: Applies the highlighting rules to the text.
strip_ansi/1: Removes ANSI color codes from the text.
get_terminal_width/1: Retrieves the current terminal width using the tput cols command.
Rewriting in Erlang with Improvements
Now, I'll rewrite the script in Erlang, improving its performance and making it more universal to handle multiple programming languages (TypeScript, JavaScript, C++, Elixir, Python) in real time. We'll use Erlang's strengths in concurrency and efficiency.
Note: Erlang and Elixir run on the same BEAM VM, but their syntax is different. Erlang is more functional and might be less expressive in some areas compared to Elixir, but we can achieve the same functionality.
Erlang Code: chatbot_formatter.erl
#!/usr/bin/env escript
%% -*- erlang -*-
%% Author: OpenAI Assistant
%% Description: Real-time syntax highlighter for various programming languages.
-module(chatbot_formatter).
-export([main/1]).
-define(DEFAULT_MAX_WIDTH, 100).
-define(INDENT, " ").
-define(COLORS, #{
reset => "\x1b[0m",
bold => "\x1b[1m",
italic => "\x1b[3m",
black => "\x1b[30m",
red => "\x1b[31m",
green => "\x1b[32m",
yellow => "\x1b[33m",
blue => "\x1b[34m",
magenta => "\x1b[35m",
cyan => "\x1b[36m",
white => "\x1b[37m",
bg_magenta => "\x1b[45m",
gray => "\x1b[90m"
}).
-record(config, {
max_width = ?DEFAULT_MAX_WIDTH,
indent = ?INDENT,
colors = ?COLORS
}).
main(_) ->
Config = #config{},
Width = get_terminal_width(Config),
% Set raw mode for stdin
set_raw_mode(true),
process_input(Width, Config),
set_raw_mode(false).
set_raw_mode(Enable) ->
PortSettings = if Enable -> [{echo, false}, {binary, true}, {raw, true}]; true -> [{echo, true}, {binary, false}, {raw, false}] end,
Port = hd([P || {P, Name} <- erlang:ports(), Name =:= "standard_io"]),
erlang:port_control(Port, 109, PortSettings).
process_input(Width, Config) ->
case io:get_chars("", 1) of
eof ->
ok;
"\n" ->
io:format("~n"),
{ok, Line} = io:get_line(""),
process_line(Line, Width, Config),
process_input(Width, Config);
Char ->
Colors = Config#config.colors,
io:format("~s~s~s", [maps:get(green, Colors), Char, maps:get(reset, Colors)]),
process_input(Width, Config)
end.
process_line(Line, Width, Config) ->
TrimmedLine = string:trim(Line),
case string:prefix(TrimmedLine, "```") of
true ->
process_code_block(TrimmedLine, Width, Config);
false ->
format_ai_response(TrimmedLine, Width, Config)
end.
process_code_block(Line, Width, Config) ->
Language =
case re:run(Line, <<"```(\\w+)">>, [{capture, [1], list}]) of
{match, [Lang]} -> Lang;
nomatch -> "text"
end,
io:format("~s~s~s~n", [format_code_block_delimiter(Language, Config), "", ""]),
process_code_lines(Width, Config).
process_code_lines(Width, Config) ->
case io:get_line("") of
"```\n" ->
io:format("~s~n", [format_code_block_delimiter("", Config)]);
Line ->
io:format("~s~n", [format_code(string:trim(Line, right, $\n), Width, Config)]),
process_code_lines(Width, Config)
end.
format_ai_response(Line, Width, Config) ->
Content = format_markdown(Line, Width, Config),
Colors = Config#config.colors,
BorderLine = io_lib:format("~s┌~s┐~s~n", [maps:get(magenta, Colors), string:copies("─", Width - 2), maps:get(reset, Colors)]),
FooterLine = io_lib:format("~s└~s┘~s~n", [maps:get(magenta, Colors), string:copies("─", Width - 2), maps:get(reset, Colors)]),
io:format("~s~s~s", [BorderLine, Content, FooterLine]).
format_markdown(Line, Width, Config) ->
Lines = wrap_text(highlight_markdown(Line, Config), Width - 4),
Colors = Config#config.colors,
lists:map(fun(L) ->
StrippedLength = string:length(strip_ansi(L)),
Padding = max(0, Width - StrippedLength - 3),
io_lib:format("~s│~s ~s~s~s│~s~n", [
maps:get(magenta, Colors),
maps:get(reset, Colors),
L,
string:copies(" ", Padding),
maps:get(magenta, Colors),
maps:get(reset, Colors)
])
end, Lines)
|> io_lib:flatten().
format_code_block_delimiter(Language, Config) ->
Colors = Config#config.colors,
io_lib:format("~s```~s~s", [maps:get(yellow, Colors), Language, maps:get(reset, Colors)]).
format_code(Line, Width, Config) ->
Highlighted = highlight_code(Line, Config),
Indented = Config#config.indent ++ Highlighted,
Lines = wrap_text(Indented, Width - 4),
lists:map(fun(L) -> L end, Lines)
|> string:join("\n").
highlight_markdown(Line, Config) ->
Rules = [
{<<"^(#+)\\s+(.+)$">>, fun(_, [Hashes, Title]) ->
Colors = Config#config.colors,
maps:get(cyan, Colors) ++ maps:get(bold, Colors) ++ Hashes ++ " " ++ Title ++ maps:get(reset, Colors)
end},
{<<"\\*\\*(.+?)\\*\\*">>, fun(_, [Text]) ->
Colors = Config#config.colors,
maps:get(bold, Colors) ++ Text ++ maps:get(reset, Colors)
end},
{<<"_(.+?)_">>, fun(_, [Text]) ->
Colors = Config#config.colors,
maps:get(italic, Colors) ++ Text ++ maps:get(reset, Colors)
end},
{<<"`(.+?)`">>, fun(_, [Text]) ->
Colors = Config#config.colors,
maps:get(yellow, Colors) ++ Text ++ maps:get(reset, Colors)
end},
{<<"\\[(.+?)\\]\\((.+?)\\)">>, fun(_, [Text, Url]) ->
Colors = Config#config.colors,
maps:get(blue, Colors) ++ "[" ++ Text ++ "]" ++ maps:get(reset, Colors) ++
maps:get(green, Colors) ++ "(" ++ Url ++ ")" ++ maps:get(reset, Colors)
end},
{<<"^(\\s*)([-*+])\\s+(.+)$">>, fun(_, [Spaces, Bullet, Text]) ->
Colors = Config#config.colors,
Spaces ++ maps:get(red, Colors) ++ Bullet ++ maps:get(reset, Colors) ++ " " ++ Text
end}
],
apply_highlight_rules(Line, Rules, Config).
highlight_code(Line, Config) ->
Rules = [
{<<"\\b(class|interface|type|enum|constructor|public|private|protected|static|extends|implements|return|if|else|for|while|switch|case|break|continue|try|catch|throw|new|this|super|import|export|as|from|default)\\b">>,
fun(_, [Keyword]) ->
Colors = Config#config.colors,
maps:get(blue, Colors) ++ Keyword ++ maps:get(reset, Colors)
end},
{<<"\\b(string|number|boolean|any|void|null|undefined|true|false)\\b">>,
fun(_, [Keyword]) ->
Colors = Config#config.colors,
maps:get(magenta, Colors) ++ Keyword ++ maps:get(reset, Colors)
end},
{<<"\"([^\"]*)\"">>,
fun(_, [String]) ->
Colors = Config#config.colors,
maps:get(green, Colors) ++ "\"" ++ String ++ "\"" ++ maps:get(reset, Colors)
end},
{<<"'([^']*)'">>,
fun(_, [String]) ->
Colors = Config#config.colors,
maps:get(green, Colors) ++ "'" ++ String ++ "'" ++ maps:get(reset, Colors)
end},
{<<"`([^`]*)`">>,
fun(_, [String]) ->
Colors = Config#config.colors,
maps:get(green, Colors) ++ "`" ++ String ++ "`" ++ maps:get(reset, Colors)
end},
{<<"\\b\\d+(\\.\\d+)?\\b">>,
fun(_, [Number]) ->
Colors = Config#config.colors,
maps:get(yellow, Colors) ++ Number ++ maps:get(reset, Colors)
end},
{<<"[{}()\\[\\]]">>,
fun(_, [Brace]) ->
Colors = Config#config.colors,
maps:get(cyan, Colors) ++ Brace ++ maps:get(reset, Colors)
end},
{<<"[+\\-*\\/%=<>!&|^]+">>,
fun(_, [Operator]) ->
Colors = Config#config.colors,
maps:get(red, Colors) ++ Operator ++ maps:get(reset, Colors)
end},
{<<"(//.*)$">>,
fun(_, [Comment]) ->
Colors = Config#config.colors,
maps:get(gray, Colors) ++ Comment ++ maps:get(reset, Colors)
end}
],
apply_highlight_rules(Line, Rules, Config).
apply_highlight_rules(Text, Rules, Config) ->
lists:foldl(fun({Pattern, Func}, Acc) ->
re:replace(Acc, Pattern, Func, [{return, list}, global])
end, Text, Rules).
wrap_text(Text, Width) ->
Words = string:tokens(Text, " \t\n"),
do_wrap_text(Words, Width, []).
do_wrap_text([], _, Acc) -> lists:reverse(Acc);
do_wrap_text(Words, Width, Acc) ->
{LineWords, Rest} = take_line(Words, Width, []),
Line = string:join(lists:reverse(LineWords), " "),
do_wrap_text(Rest, Width, [Line | Acc]).
take_line([], _, Acc) -> {Acc, []};
take_line([Word | Rest], Width, Acc) ->
NewLineWords = [Word | Acc],
NewLine = string:join(lists:reverse(NewLineWords), " "),
StrippedLength = string:length(strip_ansi(NewLine)),
if StrippedLength =< Width ->
take_line(Rest, Width, NewLineWords);
true ->
{Acc, [Word | Rest]}
end.
strip_ansi(String) ->
re:replace(String, <<"\x1b\\[[0-9;]*[mG]">>, <<>>, [{return, list}, global]).
get_terminal_width(Config) ->
case os:cmd("tput cols") of
{error, _} -> Config#config.max_width;
Result ->
{Width, _} = string:to_integer(string:trim(Result)),
erlang:min(Width, Config#config.max_width)
end.
Explanation and Improvements
- Real-Time Input Handling: Erlang's
io:get_chars/2 function is used to read one character at a time without waiting for a newline. We set the terminal to raw mode to achieve real-time input handling.
- Performance: Erlang is known for its concurrency and lightweight processes. While this script runs in a single process, it's efficient and can handle real-time input without blocking.
- Universal Syntax Highlighting: The regex patterns for syntax highlighting are designed to cover multiple languages (TypeScript, JavaScript, C++, Elixir, Python). You can expand the patterns in
highlight_code/2 to support additional languages.
- Buffering and Interactive Applications: The script reads and writes directly to the standard input and output, making it possible to pipe output from any interactive command-line application through it for real-time syntax highlighting.
- Modular Design: The code is organized into functions that handle specific tasks, making it easier to maintain and extend.
- ANSI Color Codes: We use ANSI escape codes for coloring the output, which works well in most terminals.
- Text Wrapping and Alignment: The
wrap_text/2 function ensures that text does not exceed the terminal width, improving readability.
- Error Handling: Basic error handling is included when reading terminal width and processing input.
How to Use the Script
-
Save the Script: Save the code in a file named chatbot_formatter.erl.
-
Make It Executable: Run chmod +x chatbot_formatter.erl to make it executable.
-
Run the Script: You can run it directly or pipe output from another command:
./chatbot_formatter.erl
Or with piping:
some_command | ./chatbot_formatter.erl
-
Examples:
-
IRC Chatbot:
irssi | ./chatbot_formatter.erl
-
System Logs Viewer:
tail -f /var/log/syslog | ./chatbot_formatter.erl
-
Code Review Editor:
cat some_code_file.py | ./chatbot_formatter.erl
Extending the Script
To support more languages or improve syntax highlighting:
- Add More Rules: In the
highlight_code/2 function, add more regex patterns for different languages.
- Language Detection: Implement language detection based on file extensions or code block delimiters to apply language-specific highlighting.
- Configuration File: Modify the script to read settings from a configuration file (e.g., YAML or JSON) to make it more flexible.
Note on Erlang Syntax
Erlang's syntax and standard library are different from Elixir's. Some functions may require more verbose code, but Erlang provides powerful concurrency features and is highly efficient for real-time applications.
I hope this Erlang script meets your requirements for a performant, real-time syntax highlighter that can handle multiple languages and be integrated with various command-line applications. Let me know if you need further adjustments or explanations!