Skip to content

Instantly share code, notes, and snippets.

@gabouh
Forked from deanebarker/PoorMansCodeEditor.html
Created February 26, 2018 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabouh/18049a57f4a23a1269c8eb3470a09fd9 to your computer and use it in GitHub Desktop.
Save gabouh/18049a57f4a23a1269c8eb3470a09fd9 to your computer and use it in GitHub Desktop.
Poor man's code editor in pure JavaScript.
<!--
This is a textarea that:
(1) Is styled(-ish) like a code editor
(2) Catches tabs and converts them to four (4) spaces
(3) Duplicates leading spaces from the last line
(4) Auto-expands to input
Pure inline HTML and JavaScript. No external dependencies. Has issues pre-IE-8, but should be otherwise okay.
One rule: you need to keep the min-height and max-height in the CSS, and they must be in "px" values.
-->
<html>
<body>
<textarea
wrap="off"
style="width: 100%; min-height: 200px; max-height: 1000px; font-family: monospace; padding: 10px; font-size: 12px; line-height: 16px; border-radius: 0; background-color: rgb(250,250,250); white-space: pre;"
spellcheck="false"
onkeydown="var tabReplacement = ' '; var keyCode = event.keyCode || event.which; if (keyCode == 9) { event.preventDefault(); var start = this.selectionStart; var end = this.selectionEnd; this.value = this.value.substring(0, start) + tabReplacement + this.value.substring(end); this.selectionEnd = start + tabReplacement.length; }"
onkeyup="var keyCode = event.keyCode || event.which; if(keyCode == 13) { var start = this.selectionStart; var lines = this.value.substring(0, start).split(/\r?\n/); if(lines.length == 1) { return; } var lastLine = lines[lines.length - 2]; var leadingSpaces = lastLine.substring(0, lastLine.search(/\S|$/)); var end = this.selectionEnd; this.value = this.value.substring(0, start) + leadingSpaces + this.value.substring(end); this.selectionEnd = start + leadingSpaces.length; }"
oninput="var maxHeight = this.style.maxHeight.replace('px',''); var minHeight = this.style.minHeight.replace('px',''); var newHeight = Math.max(this.scrollHeight, minHeight); newHeight = Math.min(newHeight, maxHeight); this.style.height = newHeight + 'px';"/></textarea> </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment