jump-to-line.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. 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. function getJumpDialog(cm) {
  18. 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>';
  19. }
  20. function interpretLine(cm, string) {
  21. var num = Number(string)
  22. if (/^[-+]/.test(string)) return cm.getCursor().line + num
  23. else return num - 1
  24. }
  25. CodeMirror.commands.jumpToLine = function(cm) {
  26. var cur = cm.getCursor();
  27. dialog(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), (cur.line + 1) + ":" + cur.ch, function(posStr) {
  28. if (!posStr) return;
  29. var match;
  30. if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
  31. cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
  32. } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
  33. var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
  34. if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
  35. cm.setCursor(line - 1, cur.ch);
  36. } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
  37. cm.setCursor(interpretLine(cm, match[1]), cur.ch);
  38. }
  39. });
  40. };
  41. CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
  42. });