jump-to-line.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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") // 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. // default search panel location
  14. CodeMirror.defineOption("search", {bottom: false});
  15. function dialog(cm, text, shortText, deflt, f) {
  16. if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true, bottom: cm.options.search.bottom});
  17. else f(prompt(shortText, deflt));
  18. }
  19. function getJumpDialog(cm) {
  20. return cm.phrase("Jump to line:") + ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use line:column or scroll% syntax)") + '</span>';
  21. }
  22. function interpretLine(cm, string) {
  23. var num = Number(string)
  24. if (/^[-+]/.test(string)) return cm.getCursor().line + num
  25. else return num - 1
  26. }
  27. CodeMirror.commands.jumpToLine = function(cm) {
  28. var cur = cm.getCursor();
  29. dialog(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), (cur.line + 1) + ":" + cur.ch, function(posStr) {
  30. if (!posStr) return;
  31. var match;
  32. if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
  33. cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
  34. } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
  35. var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
  36. if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
  37. cm.setCursor(line - 1, cur.ch);
  38. } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
  39. cm.setCursor(interpretLine(cm, match[1]), cur.ch);
  40. }
  41. });
  42. };
  43. CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
  44. });