245

I am storing a number of HTML blocks inside a CMS for reasons of easier maintenance. They are represented by <textarea>s.

Does anybody know a JavaScript Widget of some sort that can do syntax highlighting for HTML within a textarea or similar, while still staying a plain text editor (no WYSIWYG or advanced functions)?

Volker E.
  • 5,911
  • 11
  • 47
  • 64
Pekka
  • 442,112
  • 142
  • 972
  • 1,088

11 Answers11

260

It's not possible to achieve the required level of control over presentation in a regular <textarea>.

If you're OK with that, try CodeMirror or Ace or Monaco (used in VS Code).

See Comparison of JavaScript-based source code editors on Wikipedia.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Nickolay
  • 31,095
  • 13
  • 107
  • 185
  • 3
    Actually, Bespin uses a regular textarea fallback for adding support for screen readers (so disabled people can easily use it too). – Eli Grey Oct 24 '09 at 21:44
  • 4
    CodeMirror looks exactly like what I need. As long as it behaves like a textarea, I am comfortable with it not being one. – Pekka Oct 24 '09 at 21:47
  • 1
    Thanks for you answer. Found this after reading your response and its blowing my mind ! :) https://github.com/securingsincity/react-ace – currenthandle Feb 21 '18 at 08:08
  • it is 100% possible to do syntax hightlighting with a normal text area that's litterally what all those things they named run off of just usually people make the textarea in JS instead of just plain ol' html so this response isnt valid this question is just asking for something that would usually be made by advanced programmers – RagDev Jun 06 '22 at 13:58
32

Here is the response I've done to a similar question (Online Code Editor) on programmers:

First, you can take a look to this article:
Wikipedia ― Comparison of JavaScript-based source code editors.

For more, here is some tools that seem to fit with your request:

  • EditAreaDemo as FileEditor who is a Yii Extension ― (Apache Software License, BSD, LGPL)

    Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).

  • CodePressDemo of Joomla! CodePress Plugin ― (LGPL) ― It doesn't work in Chrome and it looks like development has ceased.

    CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.

  • CodeMirrorOne of the many demo ― (MIT-style license + optional commercial support)

    CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content ― computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation

  • Ace Ajax.org Cloud9 EditorDemo ― (Mozilla tri-license (MPL/GPL/LGPL))

    Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.

Community
  • 1
  • 1
Pascal Qyy
  • 4,442
  • 4
  • 31
  • 46
  • 2
    Oh this is so utterly depressing... A 100 projects that are supposed to do this, and absolutely none that just work. – RobinJ Feb 24 '13 at 15:48
  • Ace editor's license has been changed to BSD https://github.com/ajaxorg/ace/blob/master/LICENSE – S.Krishna Jul 27 '17 at 11:49
19

CodePress does this, as does EditArea. Both are open source.

thomas-peter
  • 7,738
  • 6
  • 43
  • 58
Anonymous
  • 191
  • 1
  • 2
13

You can Highlight text in a <textarea>, using a <div> carefully placed behind it.

check out Highlight Text Inside a Textarea.

E99
  • 157
  • 1
  • 3
11

I would recommend EditArea for live editing of a syntax hightlighted textarea.

Shef
  • 44,808
  • 15
  • 79
  • 90
Daniel Bardi
  • 352
  • 4
  • 7
8

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');


var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');
  }

  return text;
}

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);
  $highlights.html(highlightedText);
}

function handleScroll() {
  var scrollTop = $textarea.scrollTop();
  $backdrop.scrollTop(scrollTop);

  var scrollLeft = $textarea.scrollLeft();
  $backdrop.scrollLeft(scrollLeft);
}

function fixIOS() {
  $highlights.css({
    'padding-left': '+=3px',
    'padding-right': '+=3px'
  });
}

function bindEvents() {
  $textarea.on({
    'input': handleInput,
    'scroll': handleScroll
  });
}

if (isIOS) {
  fixIOS();
}

bindEvents();
handleInput();
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;
}

.container,
.backdrop,
textarea {
  width: 460px;
  height: 180px;
}

.highlights,
textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;
}

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;
}

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;
}

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;
}

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;
}

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  </div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>

Original Pen: https://codepen.io/lonekorean/pen/gaLEMR

A5H1Q
  • 544
  • 7
  • 15
7

Update: Bespin is now ACE, which is mentioned by the highest rated answer here. Use ACE instead.

Gotta go with Bespin by Mozilla. It's built using HTML5 features (so it's quick and fast, but doesn't support legacy browsers though), but definitely amazing to use and beats everything I've come across - probably beacause it's Mozilla backing it, and they develop Firefox so yeah... There's also a jQuery Plugin which contains a extension for it to make it a bit easier to use with jQuery.

balupton
  • 47,113
  • 32
  • 131
  • 182
5

In summary, these are the one we can go with:

In order to save your time and energy, it is good to investigate further within these scope.

Ritesh Aryal
  • 825
  • 9
  • 13
1

The only editor I know of that has syntax highlighting and a fallback to a textarea is Mozilla Bespin. Google around for embedding Bespin to see how to embed the editor. The only site I know of that uses this right now is the very alpha Mozilla Jetpack Gallery (in the submit a Jetpack page) and you may want to see how they include it.

There's also a blog post on embedding and reusing the Bespin editor that may help you.

Eli Grey
  • 35,104
  • 14
  • 75
  • 93
0

Why are you representing them as textareas? This is my favorite:

http://alexgorbatchev.com/wiki/SyntaxHighlighter

But if you are using a CMS, there's probably a better plugin. For example, wordpress has an evolved version:

http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/

Matrym
  • 16,643
  • 33
  • 95
  • 140
0

This is doable by adding an overlay code block infront of textarea, and use that to apply syntax highlighting as mentioned by couple of others.

However there are some edge cases to take care of. This article goes in detail about them: https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code

Thankfully, author has created it as a custom element https://github.com/WebCoder49/code-input

Usage example https://codepen.io/WebCoder49/pen/jOypJOx

demo of content editable

aarjithn
  • 1,151
  • 8
  • 20