jump-to-line.js 1.9 KB

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