Certainly! Let's break down your Elixir syntax highlighter code step-by-step to understand its functionality. Afterward, I'll provide a reimagined version in R that aims to be more universal, performant, and capable of handling multiple languages in real-time.
1. Understanding the Elixir Syntax Highlighter
Overview
The provided Elixir script is a real-time syntax highlighter designed to read input (potentially from sources like IRC chatbots, system logs, or code editors), apply syntax highlighting based on predefined rules, and output the colored text to the terminal. It handles different programming languages like Elixir, TypeScript, JavaScript, C++, and Python within code blocks and supports Markdown-like formatting.
Detailed Breakdown
-
Module Definition and Configuration
defmodule ChatbotFormatter do
@default_config %{
max_width: 100,
indent: " ",
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"
}
}
...
end
- Purpose: Defines a module
ChatbotFormatter with a default configuration that includes maximum terminal width, indentation style, and ANSI color codes for various text styles and colors.
-
Entry Point (run/1)
def run(config \\ @default_config) do
width = get_terminal_width(config)
# Enable raw mode for real-time input handling
:io.setopts(:standard_io, [mode: :line, echo: false])
process_input(width, config)
end
- Purpose: Initializes the formatter with a configuration (defaulting to
@default_config), determines the terminal width, sets the standard IO to raw mode to handle real-time input without buffering, and starts processing input.
-
Processing Input (process_input/2)
defp process_input(width, config) do
case IO.getn("", 1) do
:eof ->
:ok
{:error, reason} ->
IO.puts("Error: #{reason}")
char ->
handle_char(char, width, config)
process_input(width, config)
end
end
- Purpose: Continuously reads one character at a time from standard input. Depending on the input:
- If End of File (
:eof), exit.
- If an error occurs, print the error.
- Otherwise, handle the character and continue processing.
-
Handling Individual Characters (handle_char/3)
defp handle_char(char, width, config) do
case char do
"\n" ->
IO.write("\n")
process_line(IO.gets(""), width, config)
_ ->
IO.write(config.colors.green <> char <> config.colors.reset)
end
end
- Purpose: Determines if the character is a newline:
- If newline, process the entire line.
- Otherwise, apply green color to the character and write it to the output.
-
Processing Lines (process_line/3)
defp process_line(line, width, config) do
trimmed_line = String.trim(line)
cond do
String.starts_with?(trimmed_line, "```") ->
process_code_block(trimmed_line, width, config)
true ->
format_ai_response(trimmed_line, width, config)
end
end
- Purpose: Determines if the line starts a code block (indicated by ```). If so, it processes the code block; otherwise, it formats the line as a standard AI response with Markdown highlighting.
-
Processing Code Blocks (process_code_block/3 and process_code_lines/2)
defp process_code_block(line, width, config) do
language = Regex.run(~r/```(\w+)/, line)
|> case do
[_, lang] -> lang
_ -> "text"
end
IO.puts(format_code_block_delimiter(language, config))
process_code_lines(width, config)
end
defp process_code_lines(width, config) do
case IO.gets("") do
"```\n" ->
IO.puts(format_code_block_delimiter("", config))
line ->
IO.puts(format_code(line, width, config))
process_code_lines(width, config)
end
end
process_code_block/3:
- Extracts the programming language from the code block delimiter.
- Prints the formatted code block delimiter with the language.
- Starts processing code lines within the block.
process_code_lines/2:
- Continues to read lines until it encounters the closing
```.
- Applies code formatting to each line within the block.
-
Formatting AI Responses (format_ai_response/4 and format_markdown/3)
defp format_ai_response(line, width, config) do
content = format_markdown(line, width, config)
[
"#{config.colors.magenta}┌#{"─" |> String.duplicate(width - 2)}┐#{config.colors.reset}\n",
content,
"#{config.colors.magenta}└#{"─" |> String.duplicate(width - 2)}┘#{config.colors.reset}\n"
]
|> Enum.join("")
|> IO.write()
end
defp format_markdown(line, width, config) do
line
|> highlight_markdown(config)
|> wrap_text(width - 4)
|> Enum.map(fn l ->
"#{config.colors.magenta}│#{config.colors.reset} #{l}#{String.duplicate(" ", max(0, width - String.length(strip_ansi(l)) - 3))}#{config.colors.magenta}│#{config.colors.reset}\n"
end)
|> Enum.join()
end
format_ai_response/4:
- Wraps the formatted Markdown content within a box drawn with magenta-colored lines.
format_markdown/3:
- Applies Markdown highlighting to the line.
- Wraps the text based on the terminal width.
- Adds vertical magenta lines on both sides for styling.
-
Formatting Code Blocks (format_code_block_delimiter/2 and format_code/3)
defp format_code_block_delimiter(language, config) do
"#{config.colors.yellow}```#{language}#{config.colors.reset}"
end
defp format_code(line, width, config) do
line
|> highlight_code(config)
|> (fn highlighted -> config.indent <> highlighted end).()
|> wrap_text(width - 4)
|> Enum.join("\n")
end
format_code_block_delimiter/2:
- Formats the opening and closing code block delimiters with yellow color.
format_code/3:
- Applies code syntax highlighting.
- Indents the line.
- Wraps the text based on the terminal width.
-
Syntax Highlighting Functions (highlight_markdown/2, highlight_code/2, and apply_highlight_rules/3)
defp highlight_markdown(line, config) do
rules = [
{~r/^(#+)\s+(.+)$/, fn _, hashes, title ->
"#{config.colors.cyan}#{config.colors.bold}#{hashes} #{title}#{config.colors.reset}"
end},
{~r/\*\*(.+?)\*\*/, "#{config.colors.bold}\\1#{config.colors.reset}"},
{~r/_(.+?)_/, "#{config.colors.italic}\\1#{config.colors.reset}"},
{~r/`(.+?)`/, "#{config.colors.yellow}\\1#{config.colors.reset}"},
{~r/\[(.+?)\]\((.+?)\)/, "#{config.colors.blue}[\\1]#{config.colors.reset}#{config.colors.green}(\\2)#{config.colors.reset}"},
{~r/^(\s*)([-*+])\s+(.+)$/, "\\1#{config.colors.red}\\2#{config.colors.reset} \\3"}
]
apply_highlight_rules(line, rules, config)
end
defp highlight_code(line, config) do
rules = [
{~r/\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/, :blue},
{~r/\b(string|number|boolean|any|void|null|undefined|true|false)\b/, :magenta},
{~r/"([^"]*)"/, :green},
{~r/'([^']*)'/, :green},
{~r/`([^`]*)`/, :green},
{~r/\b\d+(\.\d+)?\b/, :yellow},
{~r/[{}()\[\]]/, :cyan},
{~r/[+\-*\/%=<>!&|^]+/, :red},
{~r/(\/\/.*)$/, :gray}
]
apply_highlight_rules(line, rules, config)
end
defp apply_highlight_rules(text, rules, config) do
Enum.reduce(rules, text, fn
{regex, color}, acc when is_atom(color) ->
Regex.replace(regex, acc, "#{Map.get(config.colors, color)}\\0#{config.colors.reset}")
{regex, replacement}, acc when is_binary(replacement) ->
Regex.replace(regex, acc, replacement)
{regex, fun}, acc when is_function(fun) ->
Regex.replace(regex, acc, fun)
end)
end
highlight_markdown/2:
- Defines a set of regex rules to identify and apply styles to Markdown elements like headings, bold, italic, inline code, links, and lists.
highlight_code/2:
- Defines regex rules for various programming language constructs, strings, numbers, delimiters, operators, and comments.
apply_highlight_rules/3:
- Iteratively applies each regex rule to the text, replacing matches with colored versions based on the configuration.
-
Text Wrapping and ANSI Stripping (wrap_text/2, do_wrap_text/3, take_line/3, strip_ansi/1)
defp wrap_text(text, width) do
words = String.split(text, ~r/\s+/)
do_wrap_text(words, width, [])
end
defp do_wrap_text([], _, acc), do: Enum.reverse(acc)
defp do_wrap_text(words, width, acc) do
{line, rest} = take_line(words, width, [])
do_wrap_text(rest, width, [Enum.join(line, " ") | acc])
end
defp take_line([], _, acc), do: {Enum.reverse(acc), []}
defp take_line([word | rest], width, acc) do
new_line = [word | acc]
new_length = new_line |> Enum.join(" ") |> strip_ansi() |> String.length()
if new_length <= width do
take_line(rest, width, new_line)
else
{Enum.reverse(acc), [word | rest]}
end
end
defp strip_ansi(string) do
Regex.replace(~r/\x1b\[[0-9;]*[mG]/, string, "")
end
- Purpose:
wrap_text/2: Splits the text into words and initiates the wrapping process.
do_wrap_text/3: Recursively assembles lines that fit within the specified width.
take_line/3: Accumulates words into a line until adding another word would exceed the width.
strip_ansi/1: Removes ANSI escape codes to accurately calculate text length without color codes.
-
Terminal Width Detection (get_terminal_width/1)
defp get_terminal_width(config) do
case System.cmd("tput", ["cols"]) do
{result, 0} ->
width = String.trim(result) |> String.to_integer()
min(width, config.max_width)
_ -> config.max_width
end
end
- Purpose: Attempts to retrieve the current terminal's width using the
tput cols command. If successful, it uses the smaller value between the terminal width and the configured maximum width. If unsuccessful, it defaults to the configured maximum width.
-
Execution
ChatbotFormatter.run()
- Purpose: Initiates the syntax highlighter by calling the
run/1 function with the default configuration.
2. Rewriting the Syntax Highlighter in R
Creating a real-time, performant syntax highlighter in R presents unique challenges, as R is typically used for statistical computing rather than system-level text processing. However, with the help of appropriate packages and efficient coding practices, we can achieve a functional equivalent.
Key Requirements:
- Real-Time Processing: Handle input character-by-character or line-by-line with minimal latency.
- Multi-Language Support: Support syntax highlighting for TypeScript, JavaScript, C++, Elixir, and Python.
- Performance: Optimize for speed to handle interactive command-line applications seamlessly.
- Flexibility: Ability to integrate with various command-line tools (e.g., IRC chatbot, system logs viewer, code review editor).
Approach:
-
Reading Input:
- Use non-blocking or line-buffered input to read from standard input in real-time.
-
Syntax Highlighting:
- Define regex patterns for each supported language.
- Apply color codes using ANSI escape sequences.
-
Output:
- Write colored output to standard output efficiently.
-
Terminal Handling:
- Detect terminal width.
- Handle text wrapping and indentation.
-
Performance Optimization:
- Precompile regex patterns.
- Minimize computational overhead by structuring code efficiently.
Implementation in R
We'll utilize the following R packages:
crayon: For handling ANSI color codes.
stringr: For regex operations and string manipulation.
readline or base R functions: For reading input.
Prerequisites:
Before running the script, install the necessary packages if not already installed:
install.packages(c("crayon", "stringr"))
Complete R Script:
#!/usr/bin/env Rscript
# Load necessary libraries
suppressWarnings({
if (!require("crayon")) install.packages("crayon", repos = "http://cran.us.r-project.org")
if (!require("stringr")) install.packages("stringr", repos = "http://cran.us.r-project.org")
library(crayon)
library(stringr)
})
# Configuration
default_config <- list(
max_width = 100,
indent = " ",
colors = list(
reset = reset,
bold = bold,
italic = italic,
black = black,
red = red,
green = green,
yellow = yellow,
blue = blue,
magenta = magenta,
cyan = cyan,
white = white,
bg_magenta = bgMagenta,
gray = silver
)
)
# Function to get terminal width
get_terminal_width <- function(config) {
width <- tryCatch({
res <- system("tput cols", intern = TRUE)
as.numeric(trimws(res))
}, warning = function(w) { config$max_width },
error = function(e) { config$max_width })
min(width, config$max_width)
}
# Function to strip ANSI colors for length calculations
strip_ansi <- function(string) {
str_replace_all(string, "\\x1b\\[[0-9;]*[mG]", "")
}
# Function to wrap text
wrap_text <- function(text, width) {
str_wrap(text, width = width, simplify = TRUE)
}
# Functions to apply syntax highlighting
highlight_markdown <- function(line, config) {
# Define rules
patterns <- list(
"^(\#+)\\s+(.+)$" = function(m) {
paste0(config$colors$cyan, config$colors$bold, m[3], config$colors$reset)
},
"\\*\\*(.+?)\\*\\*" = function(m) {
paste0(config$colors$bold, m[2], config$colors$reset)
},
"\\_(.+?)\\_" = function(m) {
paste0(config$colors$italic, m[2], config$colors$reset)
},
"\\`(.+?)\\`" = function(m) {
paste0(config$colors$yellow, m[2], config$colors$reset)
},
"\\[(.+?)\\]\\((.+?)\\)" = function(m) {
paste0(config$colors$blue, "[", m[2], "]", config$colors$reset,
config$colors$green, "(", m[3], ")", config$colors$reset)
},
"^(\\s*)([-*+])\\s+(.+)$" = function(m) {
paste0(m[2], config$colors$reset, " ", m[4])
}
)
for (pattern in names(patterns)) {
line <- str_replace_all(line, pattern, patterns[[pattern]])
}
return(line)
}
highlight_code <- function(line, config, language = "text") {
# Define language-specific patterns
patterns <- list()
if (language %in% c("javascript", "typescript", "c++", "python", "elixir")) {
if (language %in% c("javascript", "typescript")) {
patterns <- list(
"\\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" =
config$colors$blue,
"\\b(string|number|boolean|any|void|null|undefined|true|false)\\b" =
config$colors$magenta,
"\"([^\"]*)\"" = config$colors$green,
"'([^']*)'" = config$colors$green,
"`([^`]*)`" = config$colors$green,
"\\b\\d+(\\.\\d+)?\\b" = config$colors$yellow,
"[\\{\\}\\(\\)\\[\\]]" = config$colors$cyan,
"[+\\-*/%=<>!&|^]+" = config$colors$red,
"//.*$" = config$colors$gray
}
} else if (language == "python") {
patterns <- list(
"\\b(def|class|return|if|elif|else|for|while|import|from|as|pass|break|continue|try|except|finally|with|lambda|yield|raise)\\b" =
config$colors$blue,
"\\b(True|False|None)\\b" = config$colors$magenta,
"\"([^\"]*)\"" = config$colors$green,
"'([^']*)'" = config$colors$green,
"\\b\\d+(\\.\\d+)?\\b" = config$colors$yellow,
"[\\{\\}\\(\\)\\[\\]]" = config$colors$cyan,
"[+\\-*/%=<>!&|^]+" = config$colors$red,
"#.*$" = config$colors$gray
}
} else if (language == "c++") {
patterns <- list(
"\\b(int|float|double|char|void|class|public|private|protected|if|else|for|while|return|new|delete|namespace|std|using|template|typename|virtual)\\b" =
config$colors$blue,
"\\b(true|false)\\b" = config$colors$magenta,
"\"([^\"]*)\"" = config$colors$green,
"'([^']*)'" = config$colors$green,
"\\b\\d+(\\.\\d+)?\\b" = config$colors$yellow,
"[\\{\\}\\(\\)\\[\\]]" = config$colors$cyan,
"[+\\-*/%=<>!&|^]+" = config$colors$red,
"//.*$" = config$colors$gray,
"/\\*.*\\*/" = config$colors$gray
)
} else if (language == "elixir") {
patterns <- list(
"\\b(defmodule|def|do|end|if|else|cond|case|fn|->|alias|import|require|use|case|with)\\b" =
config$colors$blue,
"\\b(true|false|nil)\\b" = config$colors$magenta,
"\"([^\"]*)\"" = config$colors$green,
"'([^']*)'" = config$colors$green,
"\\b\\d+(\\.\\d+)?\\b" = config$colors$yellow,
"[\\{\\}\\(\\)\\[\\]]" = config$colors$cyan,
"[+\\-*/%=<>!&|^]+" = config$colors$red,
"#.*$" = config$colors$gray
)
}
# Apply patterns
for (pattern in names(patterns)) {
color <- patterns[[pattern]]
line <- str_replace_all(line, pattern, paste0(color, "\\0", config$colors$reset))
}
}
return(line)
}
apply_highlight_rules <- function(text, rules, config) {
for (rule in names(rules)) {
replacement <- rules[[rule]]
if (is.function(replacement)) {
text <- str_replace_all(text, rule, replacement)
} else {
text <- str_replace_all(text, rule, paste0(replacement, "\\0", config$colors$reset))
}
}
return(text)
}
# Function to format and print AI response
format_ai_response <- function(line, width, config) {
content <- format_markdown(line, config)
wrapped_text <- wrap_text(content, width = width - 4)
top_border <- paste0(config$colors$magenta, "┌", str_dup("─", width - 2), "┐", config$colors$reset)
bottom_border <- paste0(config$colors$magenta, "└", str_dup("─", width - 2), "┘", config$colors$reset)
cat(top_border, "\n")
for (l in wrapped_text) {
padding <- str_dup(" ", max(0, width - nchar(strip_ansi(l)) - 3))
cat(paste0(config$colors$magenta, "│", config$colors$reset, " ", l, padding, config$colors$magenta, "│", config$colors$reset, "\n"))
}
cat(bottom_border, "\n")
}
# Function to format and print code blocks
format_code <- function(line, width, config, language = "text") {
highlighted_code <- highlight_code(line, config, language)
indented_code <- paste0(config$indent, highlighted_code)
wrapped_code <- wrap_text(indented_code, width = width - 4)
cat(wrapped_code, sep = "\n")
}
# Function to process code blocks
process_code_block <- function(language, width, config) {
repeat {
line <- readLines(con = stdin(), n = 1, warn = FALSE)
if (length(line) == 0 || line == "```") {
cat(format_code_block_delimiter(language, config), "\n")
break
} else {
format_code(line, width, config, language)
}
}
}
# Function to format code block delimiter
format_code_block_delimiter <- function(language, config) {
paste0(config$colors$yellow, "```", language, config$colors$reset)
}
# Main processing loop
run_formatter <- function(config = default_config) {
width <- get_terminal_width(config)
# Set terminal to raw mode (not straightforward in R; limited support)
# As a workaround, read lines continuously
con <- file("stdin")
open(con, "r")
repeat {
line <- readLines(con, n = 1, warn = FALSE)
if (length(line) == 0) break # EOF
trimmed_line <- str_trim(line)
if (str_starts(trimmed_line, "```")) {
# Extract language
language <- str_extract(trimmed_line, "^```(\\w+)") %>%
str_replace("^```", "") %>%
{ if (length(.) == 0) "text" else . }
cat(format_code_block_delimiter(language, config), "\n")
process_code_block(language, width, config)
} else {
format_ai_response(trimmed_line, width, config)
}
}
close(con)
}
# Execute the formatter
run_formatter()
Explanation of the R Script:
-
Libraries and Configuration:
crayon: Facilitates the use of ANSI color codes for styling terminal output.
stringr: Provides robust string manipulation functions.
default_config: Similar to the Elixir version, it sets up maximum width, indentation, and a palette of colors for formatting.
-
Terminal Width Detection:
get_terminal_width: Attempts to retrieve the terminal width using tput cols. If unsuccessful, defaults to max_width from the configuration.
-
Text Processing Utilities:
strip_ansi: Removes ANSI color codes to accurately calculate the visible length of strings.
wrap_text: Wraps text according to the specified width.
-
Syntax Highlighting Functions:
highlight_markdown: Applies Markdown-specific highlighting using regex patterns. Supports headings, bold, italic, inline code, links, and lists.
highlight_code: Applies language-specific syntax highlighting. Supports JavaScript, TypeScript, C++, Python, and Elixir by defining patterns for keywords, strings, numbers, delimiters, operators, and comments.
apply_highlight_rules: General function to apply a set of regex-based rules to text for highlighting.
-
Formatting Functions:
format_ai_response: Formats regular text responses within a styled box similar to the Elixir version.
format_code: Formats code lines by applying syntax highlighting, indentation, and wrapping.
process_code_block: Handles multi-line code blocks until the closing ``` is encountered.
format_code_block_delimiter: Styles the opening and closing ``` delimiters with the specified language.
-
Main Processing Loop (run_formatter):
- Continuously reads lines from standard input.
- Detects if a line starts a code block.
Usage Example:
To integrate this highlighter with a command-line application, you can pipe the output of the application into this script. For instance:
some_command | ./chatbot_highlighter.R
Or, to use it with an interactive prompt:
./chatbot_highlighter.R
Type input directly, and observe the real-time syntax highlighting.
Considerations for Enhanced Performance:
-
Precompiling Regex Patterns: R compiles regex patterns each time they're run. To optimize, you can precompile patterns using regex() from stringr or grepl with fixed patterns where possible.
-
Efficient String Operations: Minimize the number of string manipulations by combining multiple regex operations where feasible.
-
Parallel Processing: R is not inherently designed for parallel processing in this context, but if necessary, certain operations can be parallelized using the parallel package. However, for real-time performance, this might introduce additional overhead.
-
Alternative R Packages: Explore other packages like cli for more advanced terminal handling, though crayon suffices for ANSI color manipulation.
3. Potential Enhancements
To make the syntax highlighter more universal and performant, consider the following improvements:
-
Language Detection:
- Automatically detect the programming language within code blocks if not specified.
- Implement fuzzy matching for language names.
-
Asynchronous Processing:
- While R's capabilities here are limited, integrating with system-level tools or using R's
later package could simulate asynchronous behavior.
-
Buffering and Debouncing:
- Implement buffering strategies to batch process input, reducing the number of operations and enhancing performance.
-
Customization via Settings File:
- Allow users to specify customization options (like color schemes and regex patterns) via an external YAML or JSON settings file.
- Use the
yaml or jsonlite packages to parse configurations.
-
Extensive Error Handling:
- Add robust error handling to manage unexpected inputs or malformed code blocks gracefully.
-
Integration with Other Tools:
- Provide options to integrate with logging systems, chatbots, and editors through piping or inter-process communication.
Conclusion
While R is not traditionally used for real-time syntax highlighting in command-line applications, with careful structuring and the use of efficient libraries, it is possible to create a functional and versatile syntax highlighter. The provided script serves as a foundational implementation, which can be further enhanced to meet specific performance and feature requirements.
If you encounter performance limitations or require more advanced features, consider leveraging languages better suited for system-level text processing, such as Erlang, Go, or Rust. These languages offer superior concurrency models and performance optimizations for real-time applications.