- Lightweight (2.45 kB only)
- No dependencies
- Preserves indentation on a new line
- Adds closing brackets, quotes
- Indents line with the Tab key
- Supports undo/redo
Install CodeJar π― Β via npm:
npm i codejarCreate an element and init the CodeJar π―:
<div class="editor"></div>
<script>
  let jar = CodeJar(document.querySelector('.editor'), highlight)
</script>Second argument to CodeJar is a highlighting function (like Prism.js, highlight.js):
const highlight = (editor: HTMLElement) => {
  const code = editor.textContent
  code = code.replace('foo', '<span style="color: red">foo</span>')
  editor.innerHTML = code
}
const jar = CodeJar(editor, highlight)Third argument to CodeJar is options:
- tab: stringreplaces "tabs" with given string. Default:- \t.- Note: use css rule tab-sizeto customize size.
 
- Note: use css rule 
- indentOn: RegExpallows auto indent rule to be customized. Default- /[({\[]$/.
- moveToNewLine: RegExpchecks in extra newline character need to be added. Default- /^[)}\]]/.
- spellcheck: booleanenables spellchecking on the editor. Default- false.
- catchTab: booleancatches Tab keypress events and replaces it with- tabstring. Default:- true.
- preserveIdent: booleankeeps indent levels on new line. Default- true.
- addClosing: booleanautomatically adds closing brackets, quotes. Default- true.
- historyrecords history. Default- true.
- windowwindow object. Default:- window.
- autocloseobject- open stringcharacters that triggers the autoclose function
- close stringcharacters that correspond to the opening ones and close the object.
 
const options = {
  tab: ' '.repeat(4), // default is '\t'
  indentOn: /[(\[]$/, // default is /{$/
  autoclose: { 
    open: `([{*`, // default is `([{'"`
    close: `)]}*` // default is `)]}'"`
  }
}
const jar = CodeJar(editor, highlight, options)Updates the code.
jar.updateCode(`let foo = bar`)Updates the options.
jar.updateOptions({tab: '\t'})Calls callback on code updates.
jar.onUpdate(code => {
  console.log(code)
})Return current code.
let code = jar.toString()Saves current cursor position.
let pos = jar.save()Restore cursor position.
jar.restore(pos)Saves current editor state to history.
Removes event listeners from editor.
- react-codejar - a React wrapper for CodeJar.
- ngx-codejar - an Angular wrapper for CodeJar.
- codejar-linenumbers - an JS library for line numbers.
