JAVASCRIPT   11

jump to line

Guest on 9th May 2022 01:46:39 AM

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

Raw Paste


Login or Register to edit or fork this paste. It's free.