#C247. Text Editor Syntax Highlighter
Text Editor Syntax Highlighter
Text Editor Syntax Highlighter
You are required to implement a simple text editor that supports syntax highlighting for different programming languages. The editor supports three operations:
- ADD: Add a new programming language along with its syntax highlighting rules. Each rule consists of a category (for example,
keywords
,comments
, orstrings
) and a list of regex patterns. The regex patterns must be valid according to LaTeX-standard regex formatting. If any pattern is invalid, the editor should output the error message in the format:Invalid regex pattern: [pattern] in category: [category]
. - SWITCH: Switch the editor to a language that has been added. If the language is not supported, output the error message:
Language '[language]' not supported
. - COLORIZE: Given multiple lines of code, apply syntax highlighting based on the currently selected language. Each match found for a regex is wrapped in tags of the category name. For example, if the category is
keywords
and the worddef
is matched, it will be replaced by<keywords>def</keywords>
. If no language is selected, output the error:No language selected
.
The operations are provided from standard input and the output (if any) must be printed to standard output. When a COLORIZE
command is issued, output the resulting text after processing all regex substitutions.
Note: Regex patterns should be considered in LaTeX format, so ensure that backslashes are escaped appropriately.
inputFormat
The input begins with an integer indicating the number of operations. Each operation is given on one or more lines in one of the following formats:
ADD [language] [number_of_categories]
For each category, the next line contains:[category] [number_of_patterns]
followed by that many lines with the regex patterns.SWITCH [language]
COLORIZE [number_of_lines]
Followed by the specified number of lines of code.
Process each operation in sequence. If an error occurs during an operation, print the appropriate error message and terminate the program immediately.
outputFormat
For each COLORIZE
operation, print the resulting text after applying all regex substitutions. In cases where an error is encountered, the program should only output the corresponding error message.
3
ADD python 3
keywords 2
\bdef\b
\bclass\b
comments 1
#.*
strings 2
'[^']*'
"[^"]*"
SWITCH python
COLORIZE 4
def my_function():
# This is a comment
print("Hello, World!")
return 'abc'
def my_function():
<comments># This is a comment</comments>
print(<strings>"Hello, World!"</strings>)
return <strings>'abc'</strings></code></pre>