can you code me a working html js editor with syntax highlighting and code completion
Assistant
Certainly! Creating a feature-rich code editor with syntax highlighting and code completion can be efficiently achieved using established libraries. One of the most popular and versatile libraries for this purpose is CodeMirror. Below, I'll provide a complete example of how to set up a working HTML/JavaScript editor using CodeMirror, complete with syntax highlighting and basic code completion.
Step-by-Step Guide
1. Setting Up the HTML Structure
Create an index.html file and add the following HTML structure. This includes linking to the necessary CodeMirror CSS and JS files via CDN.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML & JS Code Editor</title>
<!-- CodeMirror CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.css">
<!-- Optional: Theme -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/theme/material-darker.min.css">
<style>
/* Set the height of the editor */
.CodeMirror {
height: 500px;
}
body {
background-color: #2d2d2d;
color: #ccc;
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
color: #fff;
}
</style>
</head>
<body>
<h1>HTML & JavaScript Editor</h1>
<textarea id="code-editor"></textarea>
<!-- CodeMirror JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.js"></script>
<!-- Language Modes -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/htmlmixed/htmlmixed.min.js"></script>
<!-- Addon for Code Completion -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/show-hint.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/show-hint.min.css">
<!-- JavaScript Hint -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/javascript-hint.min.js"></script>
<!-- HTML Hint -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/html-hint.min.js"></script>
<!-- CSS Hint (optional) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/css-hint.min.js"></script>
<!-- Any other addons you might need -->
<script>
// Initialize CodeMirror editor
const editor = CodeMirror.fromTextArea(document.getElementById('code-editor'), {
mode: 'htmlmixed', // Supports HTML, CSS, and JavaScript
theme: 'material-darker',
lineNumbers: true,
autoCloseTags: true,
matchBrackets: true,
extraKeys: {
'Ctrl-Space': 'autocomplete'
},
hintOptions: {
// Enable auto-completion for JavaScript and HTML
tables: true
}
});
// Optional: Set some default code
const defaultCode = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Code</title>
<style>
body {
background-color: #f0f0f0;
}
/* Add more styles here */
</style>
</head>
<body>
<h1>Hello, World!</h1>
<script>
// Write your JavaScript here
function greet() {
console.log("Hello from JavaScript!");
}
greet();
</script>
</body>
</html>`;
editor.setValue(defaultCode);
// Enable auto-completion as you type (optional)
editor.on('inputRead', function onInputRead(editor, change) {
if (change.text[0] === '.') {
CodeMirror.showHint(editor, CodeMirror.hint.anyword);
}
});
</script>
</body>
</html>
2. Explanation of the Components
CodeMirror CSS and Theme:
The codemirror.min.css file includes the basic styling for the editor.
The material-darker theme is optional and provides a visually appealing dark theme. You can choose other themes from the CodeMirror Themes gallery.
CodeMirror JS and Language Modes:
The main codemirror.min.js script is essential for the editor's functionality.
Language modes like javascript, xml, and htmlmixed enable syntax highlighting for respective languages. htmlmixed is especially useful as it combines HTML, CSS, and JavaScript.
Addons for Code Completion:
The show-hint.min.js and its corresponding CSS enable the hinting (autocomplete) functionality.
Specific hint scripts like javascript-hint.min.js and html-hint.min.js provide context-aware suggestions for JavaScript and HTML code respectively.
Initialization Script:
The editor is initialized with desired configurations such as mode, theme, line numbers, auto-closing of tags, bracket matching, and key bindings for autocomplete (Ctrl-Space).
A default code snippet is provided to give users an immediate example upon loading.
An optional event listener (inputRead) triggers autocomplete suggestions when the user types a dot (.), which is common in JavaScript when accessing object properties.
3. Adding More Features (Optional)
Depending on your requirements, you can enhance the editor further:
Linting and Error Checking: Integrate additional addons or external libraries to provide real-time error checking.
Multiple Themes: Allow users to switch between different themes for better personalization.
Full-Fledged Code Completion: For more advanced code completion (like intelligent suggestions based on context), consider integrating more sophisticated solutions or server-side assistance.
4. Running the Editor
Save the File: Save the above HTML code in a file named index.html.
Open in Browser: Double-click the index.html file or open it in your preferred web browser.
Start Coding: You'll see a code editor with syntax highlighting. You can start typing HTML, CSS, or JavaScript, and use Ctrl-Space to trigger autocomplete suggestions.
5. Live Preview (Optional)
If you want to add a live preview pane to see the rendered HTML and the effects of your JavaScript/CSS in real-time, you can extend the setup as follows:
html
<!-- Add a preview section -->
<h2>Live Preview</h2>
<iframe id="preview" style="width:100%; height:500px; border:1px solid #ccc;"></iframe>
<script>
// Function to update the preview
function updatePreview() {
const previewFrame = document.getElementById('preview');
const preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
// Update preview initially
updatePreview();
// Update preview on changes with a debounce
let timeout;
editor.on('change', () => {
clearTimeout(timeout);
timeout = setTimeout(updatePreview, 500);
});
</script>
Explanation:
Iframe Preview:
An <iframe> is added below the editor to serve as a live preview of the HTML/CSS/JS code.
Update Function:
The updatePreview function writes the current code from the editor into the iframe, rendering the HTML.
Debounce Mechanism:
To prevent the preview from updating too frequently (which can be resource-intensive), a debounce mechanism ensures the preview updates 500 milliseconds after the user stops typing.
Complete Example with Live Preview
Here's the complete HTML file incorporating the live preview feature:
html
Usage:
Editing Code: Modify the HTML, CSS, or JavaScript in the editor on the left.
Viewing Results: The changes will reflect in the live preview on the right after a short delay.
Autocomplete: Press Ctrl + Space to trigger autocomplete suggestions or type a dot (.) in JavaScript to see property suggestions.
CodeMirror Addons: Explore various addons to enhance functionality.
Conclusion
By leveraging CodeMirror, you can create a powerful and customizable code editor with syntax highlighting and code completion features. This setup provides a solid foundation that you can further expand based on your specific requirements, such as integrating additional languages, advanced autocomplete features, or even saving/loading functionality.
Feel free to modify and enhance the example to suit your needs!
Dataset releases
Not yet included in a published release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML & JS Code Editor with Live Preview</title>
<!-- CodeMirror CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.css">
<!-- Optional: Theme -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/theme/material-darker.min.css">
<style>
/* Set the height of the editor */
.CodeMirror {
height: 500px;
}
body {
background-color: #2d2d2d;
color: #ccc;
font-family: Arial, sans-serif;
padding: 20px;
}
h1, h2 {
color: #fff;
}
#preview {
width: 100%;
height: 500px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>HTML & JavaScript Editor</h1>
<textarea id="code-editor"></textarea>
<h2>Live Preview</h2>
<iframe id="preview"></iframe>
<!-- CodeMirror JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.js"></script>
<!-- Language Modes -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/htmlmixed/htmlmixed.min.js"></script>
<!-- Addon for Code Completion -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/show-hint.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/show-hint.min.css">
<!-- JavaScript Hint -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/javascript-hint.min.js"></script>
<!-- HTML Hint -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/html-hint.min.js"></script>
<!-- CSS Hint (optional) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/hint/css-hint.min.js"></script>
<script>
// Initialize CodeMirror editor
const editor = CodeMirror.fromTextArea(document.getElementById('code-editor'), {
mode: 'htmlmixed', // Supports HTML, CSS, and JavaScript
theme: 'material-darker',
lineNumbers: true,
autoCloseTags: true,
matchBrackets: true,
extraKeys: {
'Ctrl-Space': 'autocomplete'
},
hintOptions: {
tables: true
}
});
// Set default code
const defaultCode = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Code</title>
<style>
body {
background-color: #f0f0f0;
}
/* Add more styles here */
</style>
</head>
<body>
<h1>Hello, World!</h1>
<script>
// Write your JavaScript here
function greet() {
console.log("Hello from JavaScript!");
}
greet();
</script>
</body>
</html>`;
editor.setValue(defaultCode);
// Function to update the preview
function updatePreview() {
const previewFrame = document.getElementById('preview');
const preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
// Update preview initially
updatePreview();
// Update preview on changes with a debounce
let timeout;
editor.on('change', () => {
clearTimeout(timeout);
timeout = setTimeout(updatePreview, 500);
});
// Enable auto-completion as you type (optional)
editor.on('inputRead', function onInputRead(editor, change) {
if (change.text[0] === '.') {
CodeMirror.showHint(editor, CodeMirror.hint.anyword);
}
});
</script>
</body>
</html>