javascript-lint.js 2.0 KB

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