jump-to-line.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // Defines jumpToLine command. Uses dialog.js if present.
  4. ;(function (mod) {
  5. if (typeof exports == 'object' && typeof module == 'object')
  6. // CommonJS
  7. mod(require('../../lib/codemirror'), require('../dialog/dialog'))
  8. else if (typeof define == 'function' && define.amd)
  9. // AMD
  10. define(['../../lib/codemirror', '../dialog/dialog'], mod)
  11. // Plain browser env
  12. else mod(CodeMirror)
  13. })(function (CodeMirror) {
  14. 'use strict'
  15. // default search panel location
  16. CodeMirror.defineOption('search', { bottom: false })
  17. function dialog(cm, text, shortText, deflt, f) {
  18. if (cm.openDialog) cm.openDialog(text, f, { value: deflt, selectValueOnOpen: true, bottom: cm.options.search.bottom })
  19. else f(prompt(shortText, deflt))
  20. }
  21. function getJumpDialog(cm) {
  22. return (
  23. cm.phrase('Jump to line:') +
  24. ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' +
  25. cm.phrase('(Use line:column or scroll% syntax)') +
  26. '</span>'
  27. )
  28. }
  29. function interpretLine(cm, string) {
  30. var num = Number(string)
  31. if (/^[-+]/.test(string)) return cm.getCursor().line + num
  32. else return num - 1
  33. }
  34. CodeMirror.commands.jumpToLine = function (cm) {
  35. var cur = cm.getCursor()
  36. dialog(cm, getJumpDialog(cm), cm.phrase('Jump to line:'), cur.line + 1 + ':' + cur.ch, function (posStr) {
  37. if (!posStr) return
  38. var match
  39. if ((match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr))) {
  40. cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
  41. } else if ((match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr))) {
  42. var line = Math.round((cm.lineCount() * Number(match[1])) / 100)
  43. if (/^[-+]/.test(match[1])) line = cur.line + line + 1
  44. cm.setCursor(line - 1, cur.ch)
  45. } else if ((match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr))) {
  46. cm.setCursor(interpretLine(cm, match[1]), cur.ch)
  47. }
  48. })
  49. }
  50. CodeMirror.keyMap['default']['Alt-G'] = 'jumpToLine'
  51. })