Bug 24193: Add CodeMirror linting of JavaScript, CSS, HTML, and YAML
[koha.git] / koha-tmpl / intranet-tmpl / lib / codemirror / javascript-lint.js
blobcc132d7f8250d19331368247cd4dedac0b6d0482
1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: https://codemirror.net/LICENSE
4 (function(mod) {
5   if (typeof exports == "object" && typeof module == "object") // CommonJS
6     mod(require("../../lib/codemirror"));
7   else if (typeof define == "function" && define.amd) // AMD
8     define(["../../lib/codemirror"], mod);
9   else // Plain browser env
10     mod(CodeMirror);
11 })(function(CodeMirror) {
12   "use strict";
13   // declare global: JSHINT
15   function validator(text, options) {
16     if (!window.JSHINT) {
17       if (window.console) {
18         window.console.error("Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run.");
19       }
20       return [];
21     }
22     if (!options.indent) // JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation
23       options.indent = 1; // JSHint default value is 4
24     JSHINT(text, options, options.globals);
25     var errors = JSHINT.data().errors, result = [];
26     if (errors) parseErrors(errors, result);
27     return result;
28   }
30   CodeMirror.registerHelper("lint", "javascript", validator);
32   function parseErrors(errors, output) {
33     for ( var i = 0; i < errors.length; i++) {
34       var error = errors[i];
35       if (error) {
36         if (error.line <= 0) {
37           if (window.console) {
38             window.console.warn("Cannot display JSHint error (invalid line " + error.line + ")", error);
39           }
40           continue;
41         }
43         var start = error.character - 1, end = start + 1;
44         if (error.evidence) {
45           var index = error.evidence.substring(start).search(/.\b/);
46           if (index > -1) {
47             end += index;
48           }
49         }
51         // Convert to format expected by validation service
52         var hint = {
53           message: error.reason,
54           severity: error.code ? (error.code.startsWith('W') ? "warning" : "error") : "error",
55           from: CodeMirror.Pos(error.line - 1, start),
56           to: CodeMirror.Pos(error.line - 1, end)
57         };
59         output.push(hint);
60       }
61     }
62   }
63 });