nalgeon/codapi-js

basic editor syntax highlight integration

haraldF opened this issue · 9 comments

CodeMirror is too heavy, and basic editor is often too light :) Any chance to get e.g. https://highlightjs.org integrated in the basic editor? Thanks :)

Sure, you can use external editor mode with CodeJar and highlight.js. That's what I do on codapi.org.

Thanks for the comment. I'm using https://revealjs.com for some slides that use syntax highlighted code blocks. I'd love to be able to run & edit them right in the slides. I'm aware that I can use external editors, but it would be amazing if the basic editor could at least preserve syntax highlighting, or if there was some hook that I could re-syntax-highlight on every input.

CodeJar is the most basic editor you'll find.

True, but the <code> tags in my reveal.js slides aren't generated by me :/ Having something like editor="codejar" or maybe even editor="myJavaScriptHook()" would make my life a lot easier.

I don't get it. Okay, the code/pre tags are generated by reveal.js. What difference does that make? What prevents you from running CodeJar on those generated tags afterwards?

Sure I can hack my way around. I'm just thinking of people not being so fluent in JavaScript, might be nicer to offer a no-code solution for them to get a simple editor with syntax highlighting.

Yeah, maybe. I'd rather wait until I actually see these people.

FWIW, I've integrated HighlightJS with the basic editor. This is all that was needed:

const runButtons = document.querySelectorAll("codapi-toolbar button");

function rehighlightAssociatedCodeBlock(button) {
  const codeBlock = button.parentElement.parentElement.previousSibling.childNodes[0];
  codeBlock.innerHTML = hljs.highlightAuto(codeBlock.innerText).value
}

// Highlight all code samples
hljs.highlightAll();

// Refresh syntax-highlighting for code blocks on associated Run
runButtons.forEach(e => {
  e.addEventListener("click", () => rehighlightAssociatedCodeBlock(e));
});

The code samples loose their highlighting when the contenteditable becomes active and get re-highlighted when you click Run. Running the highlighting on the input event of the code is a pain and not worth it in my opinion over running a fully-featured editor like CodeMirror.

Hope this helps.

I don't like the idea of baking in the editor or even introducing dependencies of syntax highlighting packages like highlight.js or Prism.

In my experience, the basic mode works fine in almost all cases. The rest can be handled with external mode and a dozen of extra lines of JS.