How to Create HTML Syntax Highlighter ?

SEO Help and Tips

How to Create HTML Syntax Highlighter ?

syntax error highlighter is a complex task that depends on the programming language you want to support. However, I can provide you with a simple Python syntax error highlighter as an example. This highlighter will check for basic syntax errors using the ast module. Keep in mind that this is a basic example and may not cover all possible cases or complexities of real-world programming languages.

Here is the code sample to create HTML Syntax Highlighter:

  <script type='text/javascript'>
    import ast
import builtins

def highlight_syntax_errors(code):
    try:
        ast.parse(code, mode='exec')
        return "No syntax errors found."
    except SyntaxError as e:
        error_message = f"SyntaxError: {e.msg} (Line {e.lineno}, Column {e.offset})"
        return highlight_error_in_code(code, e.lineno, e.offset, error_message)

def highlight_error_in_code(code, lineno, offset, error_message):
    lines = code.split('\n')
    error_line = lines[lineno - 1]
    caret_position = ' ' * (offset - 1) + '^'
    highlighted_code = "\n".join(lines[:lineno - 1] + [error_line + "\n" + caret_position] + lines[lineno:])
    return f"{error_message}\n\nHighlighted code:\n{highlighted_code}"

if __name__ == "__main__":
    code = """
def greet(name)
    print("Hello, " + name)
    """
    result = highlight_syntax_errors(code)
    print(result)
</script>


Or,


  <script type='text/javascript'>
      //<![CDATA[
import code

def highlight_syntax_errors(code_str):
    try:
        code.compile_command(code_str, "<string>", "exec")
        return "No syntax errors found."
    except SyntaxError as e:
        error_message = f"SyntaxError: {e.msg} (Line {e.lineno}, Column {e.offset})"
        return highlight_error_in_code(code_str, e.lineno, e.offset, error_message)

def highlight_error_in_code(code_str, lineno, offset, error_message):
    lines = code_str.split('\n')
    error_line = lines[lineno - 1]
    caret_position = ' ' * (offset - 1) + '^'
    highlighted_code = "\n".join(lines[:lineno - 1] + [error_line + "\n" + caret_position] + lines[lineno:])
    return f"{error_message}\n\nHighlighted code:\n{highlighted_code}"

if __name__ == "__main__":
    code_str = """
def greet(name)
    print("Hello, " + name)
    """
    result = highlight_syntax_errors(code_str)
    print(result)
  //]]>
</script>

In this example, the highlight_syntax_errors function takes a string code as input, attempts to parse it using ast.parse, and returns either "No syntax errors found" or a formatted error message indicating the location of the syntax error in the code along with the highlighted code snippet.

Another way to Highlight Syntax error with display:

<head>
    <title>Syntax Error Highlighter</title>
    <style>
        .highlight {
            background-color: #ffcccc;
        }
    </style>
</head>

<body>
    <textarea id="code" rows="10" cols="80"></textarea>
    <button onclick="highlightSyntaxErrors()">Highlight Syntax Errors</button>
    <pre id="highlightedCode"></pre>

    <script>
        function highlightSyntaxErrors() {
            const codeTextarea = document.getElementById('code');
            const code = codeTextarea.value;
            const highlightedCodeElement = document.getElementById('highlightedCode');
            
            try {
                // Try to parse the code to detect syntax errors
                new Function(code);
                
                // If no syntax errors, display the code without highlights
                highlightedCodeElement.innerText = code;
            } catch (error) {
                // If syntax error found, display the error and highlight the code
                const errorLine = error.lineNumber - 1;
                const errorOffset = error.columnNumber - 1;
                const lines = code.split('\n');
                const highlightedLines = lines.map((line, index) => {
                    return index === errorLine ? '<span class="highlight">' + line + '</span>' : line;
                });
                highlightedCodeElement.innerHTML = highlightedLines.join('\n');
            }
        }
    </script>
</body>

Comments

Popular posts from this blog

How to fix SSL Certificate Issues?

How to Fix Website Mixed Content Issues?

How to Fix Mobile Responsiveness Issues?

Popular posts from this blog

How to fix SSL Certificate Issues?

How to Fix Website Mixed Content Issues?

How to Fix Mobile Responsiveness Issues?