I finally decided it myself. I am not a JS expert, but I share my decision if it is useful to someone else.
IMPORTANT : I received the original code from this project . This project was dependent on Angular and Angular-codemirror. I have not used Angular anywhere in my application, so I extracted and configured it for use without Angular.
The goal is to be able to define a dictionary / word map to be used for autocomplete. The solution is very simple. in the parent element myTextAreaId you should create a span / div as follows:
<div class="codeMirrorDictionaryHintDiv" codemirror-dictionary-hint="[ 'Soccer', 'Cricket', 'Baseball', 'Kho Kho' ]"></div>
Then ... the code looks for the closest element with the css class codeMirrorDictionaryHintDiv , extracts the codemirror-dictionary-hint attribute, evaluates it to extract a Javascript array from it, and then simply sets this as the input dictionary for the hint function.
Code:
var dictionary = []; try { // JSON.parse fails loudly, requiring a try-catch to prevent error propagation var dictionary = JSON.parse( document.getElementById('myTextAreaId') .closest('.codeMirrorDictionaryHintDiv') .getAttribute('codemirror-dictionary-hint') ) || []; } catch(e) {} // Register our custom Codemirror hint plugin. CodeMirror.registerHelper('hint', 'dictionaryHint', function(editor) { var cur = editor.getCursor(); var curLine = editor.getLine(cur.line); var start = cur.ch; var end = start; while (end < curLine.length && /[\w$]/.test(curLine.charAt(end))) ++end; while (start && /[\w$]/.test(curLine.charAt(start - 1))) --start; var curWord = start !== end && curLine.slice(start, end); var regex = new RegExp('^' + curWord, 'i'); return { list: (!curWord ? [] : dictionary.filter(function(item) { return item.match(regex); })).sort(), from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end) } }); CodeMirror.commands.autocomplete = function(cm) { CodeMirror.showHint(cm, CodeMirror.hint.dictionaryHint); };
source share