javascript-lint.js 2.5 KB

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