UNPKG

2.02 kBJavaScriptView Raw
1// CodeMirror, copyright (c) by Marijn Haverbeke and others
2// Distributed under an MIT license: https://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 function getJumpDialog(cm) {
22 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>';
23 }
24
25 function interpretLine(cm, string) {
26 var num = Number(string)
27 if (/^[-+]/.test(string)) return cm.getCursor().line + num
28 else return num - 1
29 }
30
31 CodeMirror.commands.jumpToLine = function(cm) {
32 var cur = cm.getCursor();
33 dialog(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), (cur.line + 1) + ":" + cur.ch, function(posStr) {
34 if (!posStr) return;
35
36 var match;
37 if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
38 cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
39 } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
40 var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
41 if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
42 cm.setCursor(line - 1, cur.ch);
43 } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
44 cm.setCursor(interpretLine(cm, match[1]), cur.ch);
45 }
46 });
47 };
48
49 CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
50});