-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheditor.js
More file actions
553 lines (516 loc) · 18.8 KB
/
editor.js
File metadata and controls
553 lines (516 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
String.prototype.repeat = function(i) { // Some browsers don't support repeat, for example, Safari
return new Array(i + 1).join(this);
}
function get_editor_scroll() { // 获取编辑器的滚动位置
var line_markers = $('.ui-layout-east article > [data-line]');
var lines = []; // 逻辑行
line_markers.each(function() {
lines.push($(this).data('line'));
});
var pLines = []; // 物理行
var pLine = 0;
for(var i = 0; i < lines[lines.length - 1]; i++) {
if($.inArray(i + 1, lines) !== -1) {
pLines.push(pLine);
}
pLine += editor.session.getRowLength(i) // 因为有wrap,所以行高未必是1
}
var currentLine = editor.session.getScrollTop() / editor.renderer.lineHeight; // 当前滚动到的物理行
var lastMarker = false;
var nextMarker = false;
for(var i = 0; i < pLines.length; i++) {
if(pLines[i] < currentLine) {
lastMarker = i;
} else {
nextMarker = i;
break;
}
} // 当前滚动到了哪两个marker中间
var lastLine = 0;
var nextLine = editor.session.getScreenLength() - 1; // 最后一个物理行的顶部,所以 -1
if(lastMarker !== false) {
lastLine = pLines[lastMarker];
}
if(nextMarker !== false) {
nextLine = pLines[nextMarker];
} // 前后两个marker的物理行
var percentage = 0;
if(nextLine !== lastLine) { // 行首的情况下可能相等,0 不能作为除数
percentage = (currentLine - lastLine) / (nextLine - lastLine);
} // 当前位置在两个marker之间所处的百分比
return { lastMarker: lines[lastMarker], nextMarker: lines[nextMarker], percentage: percentage }; // 返回的是前后两个marker对应的逻辑行,以及当前位置在前后两个marker之间所处的百分比
}
function set_preview_scroll(editor_scroll) { // 设置预览的滚动位置
var lastPosition = 0;
var nextPosition = $('.ui-layout-east article').outerHeight() - $('.ui-layout-east').height(); // 这是总共可以scroll的最大幅度
if(editor_scroll.lastMarker !== undefined) { // 最开始的位置没有marker
lastPosition = $('.ui-layout-east article').find('>[data-line="' + editor_scroll.lastMarker + '"]').get(0).offsetTop;
}
if(editor_scroll.nextMarker !== undefined) { // 最末尾的位置没有marker
nextPosition = $('.ui-layout-east article').find('>[data-line="' + editor_scroll.nextMarker + '"]').get(0).offsetTop;
} // 查找出前后两个marker在页面上所处的滚动距离
scrollPosition = lastPosition + (nextPosition - lastPosition) * editor_scroll.percentage; // 按照左侧的百分比计算出右侧应该滚动到的位置
$('.ui-layout-east').animate({scrollTop: scrollPosition}, 16); // 加一点动画效果
}
function get_preview_scroll() {
var scroll = $('.ui-layout-east').scrollTop();
var lastMarker = false;
var nextMarker = false;
var line_markers = $('.ui-layout-east article > [data-line]');
for(var i = 0; i < line_markers.length; i++) {
if(line_markers[i].offsetTop < scroll) {
lastMarker = i;
} else {
nextMarker = i;
break;
}
}
var lastLine = 0;
var nextLine = $('.ui-layout-east article').outerHeight() - $('.ui-layout-east').height(); // 这是总共可以scroll的最大幅度
if(lastMarker !== false) {
lastLine = line_markers[lastMarker].offsetTop;
}
if(nextMarker !== false) {
nextLine = line_markers[nextMarker].offsetTop;
}
var percentage = 0;
if(nextLine !== lastLine) {
percentage = (scroll - lastLine) / (nextLine - lastLine);
}
return { lastMarker: lastMarker, nextMarker: nextMarker, percentage: percentage }; // 返回的是前后两个marker的编号,以及当前位置在前后两个marker之间所处的百分比
}
function set_editor_scroll(preview_scroll) {
var line_markers = $('.ui-layout-east article > [data-line]');
var lines = []; // 逻辑行
line_markers.each(function() {
lines.push($(this).data('line'));
});
var pLines = []; // 物理行
var pLine = 0;
for(var i = 0; i < lines[lines.length - 1]; i++) {
if($.inArray(i + 1, lines) !== -1) {
pLines.push(pLine);
}
pLine += editor.session.getRowLength(i) // 因为有wrap,所以行高未必是1
}
var lastLine = 0;
var nextLine = editor.session.getScreenLength() - 1; // 最后一个物理行的顶部
if(preview_scroll.lastMarker !== false) {
lastLine = pLines[preview_scroll.lastMarker]
}
if(preview_scroll.nextMarker !== false) {
nextLine = pLines[preview_scroll.nextMarker]
}
var scroll = ((nextLine - lastLine) * preview_scroll.percentage + lastLine) * editor.renderer.lineHeight;
editor.session.setScrollTop(scroll);
}
var sync_preview = _.debounce(function() { // 右侧预览和左侧的内容同步
if(!$('.ui-layout-east').is(':hover')) { // 鼠标不在右侧,否则不触发
set_preview_scroll(get_editor_scroll());
}
}, 16, false);
var sync_editor = _.debounce(function() { // 左侧的内容和右侧预览同步
if($('.ui-layout-east').is(':hover')) { // 鼠标要在右侧,否则不触发
set_editor_scroll(get_preview_scroll());
}
}, 16, false);
mermaid.ganttConfig = { // Configuration for Gantt diagrams
numberSectionStyles:4,
axisFormatter: [
["%I:%M", function (d) { // Within a day
return d.getHours();
}],
["w. %U", function (d) { // Monday a week
return d.getDay() == 1;
}],
["%a %d", function (d) { // Day within a week (not monday)
return d.getDay() && d.getDate() != 1;
}],
["%b %d", function (d) { // within a month
return d.getDate() != 1;
}],
["%m-%y", function (d) { // Month
return d.getMonth();
}]
]
};
function mermaid_init() {
mermaid.init(); // generate flowcharts, sequence diagrams, gantt diagrams...etc.
}
var modelist = ace.require('ace/ext/modelist').modesByName;
var highlight = ace.require('ace/ext/static_highlight');
var lazy_change = _.debounce(function() { // 用户停止输入128毫秒之后才会触发
$('.markdown-body').empty().append(marked(editor.session.getValue())); // realtime preview
$('pre > code').each(function(){ // code highlight
var code = $(this);
var language = (code.attr('class') || 'lang-javascript').substring(5).toLowerCase();
if(modelist[language] == undefined) {
language = 'javascript';
}
highlight(code[0], {
mode: 'ace/mode/' + language,
theme: 'ace/theme/github',
startLineNumber: 1,
showGutter: false,
trim: true,
},
function(highlighted){}
);
});
mermaid_init();
sync_preview();
}, 128, false);
var Vim = ace.require("ace/keyboard/vim").CodeMirror.Vim // vim commands
Vim.defineEx("write", "w", function(cm, input) {
console.log('write');
});
Vim.defineEx("quit", "q", function(cm, input) {
if(input.input === 'q') {
console.log('quit');
} else if(input.input === 'q!') {
console.log('quit without warning');
}
});
Vim.defineEx("wq", "wq", function(cm, input) {
console.log('write then quit');
});
var editor;
$(document).ready(function() {
$('body').layout({ // create 3-panels layout
resizerDblClickToggle: false,
resizable: false,
slidable: false,
togglerLength_open: '100%',
togglerLength_closed: '100%',
spacing_open: 0,
north: {
size: 0,
togglerTip_open: $('#toolbar').data('open-title'),
togglerTip_closed: $('#toolbar').data('closed-title')
},
east: {
size: '50%',
togglerTip_open: $('#preview').data('open-title'),
togglerTip_closed: $('#preview').data('closed-title'),
onresize: function() {
lazy_change(); // mermaid gantt diagram 宽度无法自适应, 只能每次重新生成
$('.markdown-body').css('padding-bottom', ($('.ui-layout-east').height() - parseInt($('.markdown-body').css('line-height')) + 1) + 'px'); // scroll past end
}
},
center: {
onresize: function() {
editor.session.setUseWrapMode(false); // ACE的wrap貌似有问题,这里手动触发一下。
editor.session.setUseWrapMode(true);
}
}
});
$('.markdown-body').css('padding-bottom', ($('.ui-layout-east').height() - parseInt($('.markdown-body').css('line-height')) + 1) + 'px'); // scroll past end
$('.ui-layout-east').scroll(function() {
sync_editor();
});
// editor on the left
editor = ace.edit("editor");
editor.session.setUseWorker(false);
editor.$blockScrolling = Infinity;
editor.renderer.setShowPrintMargin(false);
editor.session.setMode('ace/mode/markdown');
editor.session.setUseWrapMode(true);
editor.setScrollSpeed(1);
editor.setOption("scrollPastEnd", true);
editor.session.setFoldStyle('manual');
editor.focus();
editor.session.on('changeScrollTop', function(scroll) {
sync_preview();
});
// load preferences
var key_binding = $.cookie('key-binding');
if(key_binding == undefined) {
key_binding = 'default'
}
$('select#key-binding').val(key_binding);
if(key_binding !== 'default') {
editor.setKeyboardHandler(ace.require("ace/keyboard/" + key_binding).handler);
}
var font_size = $.cookie('editor-font-size');
if(font_size == undefined) {
font_size = '14';
}
$('select#editor-font-size').val(font_size);
editor.setFontSize(font_size + 'px');
var editor_theme = $.cookie('editor-theme');
if(editor_theme == undefined) {
editor_theme = 'tomorrow_night_eighties';
}
$('select#editor-theme').val(editor_theme);
editor.setTheme('ace/theme/' + editor_theme);
// change preferences
$('select#key-binding').change(function() {
var key_binding = $(this).val();
$.cookie('key-binding', key_binding, { expires: 10000 });
if(key_binding == 'default') {
editor.setKeyboardHandler(null);
} else {
editor.setKeyboardHandler(ace.require("ace/keyboard/" + key_binding).handler);
}
});
$('select#editor-font-size').change(function() {
var font_size = $(this).val();
$.cookie('editor-font-size', font_size, { expires: 10000 });
editor.setFontSize(font_size + 'px');
});
$('select#editor-theme').change(function() {
var editor_theme = $(this).val();
$.cookie('editor-theme', editor_theme, { expires: 10000 });
editor.setTheme('ace/theme/' + editor_theme);
});
// 编辑器的一些拓展方法
editor.selection.smartRange = function() {
var range = editor.selection.getRange();
if(!range.isEmpty()) {
return range; // 用户手动选中了一些文字,直接用这个
}
// 没有选中任何东西
var _range = range; // 备份原始range
range = editor.selection.getWordRange(range.start.row, range.start.column); // 当前单词的range
if(editor.session.getTextRange(range).trim().length == 0) { // 选中的东西是空或者全空白
range = _range; // 还使用原始的range
}
return range;
};
// 设置marked
var renderer = new marked.Renderer();
renderer.listitem = function(text) {
if(!/^\[[ x]\]\s/.test(text)) {
return marked.Renderer.prototype.listitem(text);
}
// 任务列表
var checkbox = $('<input type="checkbox" disabled/>');
if(/^\[x\]\s/.test(text)) { // 完成的任务列表
checkbox.attr('checked', true);
}
return $(marked.Renderer.prototype.listitem(text.substring(3))).addClass('task-list-item').prepend(checkbox)[0].outerHTML;
}
var mermaidError;
mermaid.parseError = function(err, hash){
mermaidError = err;
};
renderer.codespan = function(text) { // inline code
if(/^\$.+\$$/.test(text)) { // inline math
var raw = /^\$(.+)\$$/.exec(text)[1];
var line = raw.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'"); // unescape html characters
try{
return katex.renderToString(line, { displayMode: false });
} catch(err) {
return '<code>' + err + '</code>';
}
}
return marked.Renderer.prototype.codespan.apply(this, arguments);
}
renderer.code = function(code, language, escaped, line_number) {
code = code.trim();
var firstLine = code.split(/\n/)[0].trim();
if(language === 'math') { // 数学公式
var tex = '';
code.split(/\n\n/).forEach(function(line){ // 连续两个换行,则开始下一个公式
line = line.trim();
if(line.length > 0) {
try {
tex += katex.renderToString(line, { displayMode: true });
} catch(err) {
tex += '<pre>' + err + '</pre>';
}
}
});
return '<div data-line="' + line_number + '">' + tex + '</div>';
} else if(firstLine === 'gantt' || firstLine === 'sequenceDiagram' || firstLine.match(/^graph (?:TB|BT|RL|LR|TD);?$/)) { // mermaid
if(firstLine === 'sequenceDiagram') {
code += '\n'; // 如果末尾没有空行,则语法错误
}
if(mermaid.parse(code)) {
return '<div class="mermaid" data-line="' + line_number + '">' + code + '</div>';
} else {
return '<pre data-line="' + line_number + '">' + mermaidError + '</pre>';
}
} else {
return marked.Renderer.prototype.code.apply(this, arguments);
}
};
renderer.html = function(html) {
var result = marked.Renderer.prototype.html.apply(this, arguments);
var h = $(result.bold());
return h.html();
};
renderer.paragraph = function(text) {
var result = marked.Renderer.prototype.paragraph.apply(this, arguments);
var h = $(result.bold());
// h.find('script,iframe').remove();
return h.html();
};
marked.setOptions({
renderer: renderer,
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: true
});
// 实时监听用户的编辑
editor.session.on('change', function() {
lazy_change();
});
// h1 - h6 heading
$('.heading-icon').click(function() {
var level = $(this).data('level');
var p = editor.getCursorPosition();
p.column += level + 1; // 光标位置会产生偏移
editor.navigateTo(editor.getSelectionRange().start.row, 0); // navigateLineStart 在 wrap 的时候有问题
editor.insert('#'.repeat(level) + ' ');
editor.moveCursorToPosition(p); // 恢复光标位置
editor.focus();
});
// styling icons
$('.styling-icon').click(function() {
var modifier = $(this).data('modifier');
var range = editor.selection.smartRange();
var p = editor.getCursorPosition();
p.column += modifier.length; // 光标位置会产生偏移
editor.session.replace(range, modifier + editor.session.getTextRange(range) + modifier);
editor.moveCursorToPosition(p); // 恢复光标位置
editor.selection.clearSelection(); // 不知为何上一个语句会选中一部分文字
editor.focus();
});
// <hr/>
$('#horizontal-rule').click(function() {
var p = editor.getCursorPosition();
if(p.column == 0) { // 光标在行首
editor.selection.clearSelection();
editor.insert('\n---\n');
} else {
editor.navigateTo(editor.getSelectionRange().start.row, Number.MAX_VALUE); // navigateLineEnd 在 wrap 的时候有问题
editor.insert('\n\n---\n');
}
editor.focus();
});
// list icons
$('.list-icon').click(function() {
var prefix = $(this).data('prefix');
var p = editor.getCursorPosition();
p.column += prefix.length; // 光标位置会产生偏移
var range = editor.selection.getRange();
for(var i = range.start.row + 1; i < range.end.row + 2; i++) {
editor.gotoLine(i);
editor.insert(prefix);
}
editor.moveCursorToPosition(p); // 恢复光标位置
editor.focus();
});
$('#link-icon').click(function() {
var range = editor.selection.smartRange();
var text = editor.session.getTextRange(range);
if(text.trim().length == 0) {
text = $(this).data('sample-text');
}
var url = $(this).data('sample-url');
editor.session.replace(range, '[' + text + '](' + url + ')');
editor.focus();
});
$('#image-icon').click(function() {
var text = editor.session.getTextRange(editor.selection.getRange()).trim();
if(text.length == 0) {
text = $(this).data('sample-text');
}
var url = $(this).data('sample-url')
editor.insert('');
editor.focus();
});
$('#code-icon').click(function() {
var text = editor.session.getTextRange(editor.selection.getRange()).trim();
editor.insert('\n```\n' + text + '\n```\n');
editor.focus();
editor.navigateUp(2);
editor.navigateLineEnd();
});
$('#table-icon').click(function() {
var sample = $(this).data('sample');
editor.insert(''); // 删除选中的部分
var p = editor.getCursorPosition();
if(p.column == 0) { // 光标在行首
editor.selection.clearSelection();
editor.insert('\n' + sample + '\n\n');
} else {
editor.navigateTo(editor.getSelectionRange().start.row, Number.MAX_VALUE);
editor.insert('\n\n' + sample + '\n');
}
editor.focus();
});
// emoji icon
prompt_for_a_value('emoji', function(value){
if(/^:.+:$/.test(value)) {
value = /^:(.+):$/.exec(value)[1];
}
editor.insert('<img src="https://s.tylingsoft.com/emoji-icons/' + value + '.png" width="18"/>');
});
// Font Awesome icon
prompt_for_a_value('fa', function(value){
if(value.substring(0, 3) == 'fa-') {
value = value.substring(3);
}
editor.insert('<i class="fa fa-' + value + '"/>');
});
// Ionicons icon
prompt_for_a_value('ion', function(value){
if(value.substring(0, 4) == 'ion-') {
value = value.substring(4);
}
editor.insert('<i class="icon ion-' + value + '"/>');
});
$('#math-icon').click(function(){
var text = editor.session.getTextRange(editor.selection.getRange()).trim();
if(text.length == 0) {
text = $(this).data('sample');;
}
editor.insert('\n```math\n' + text + '\n```\n');
editor.focus();
});
$('.mermaid-icon').click(function(){
var text = editor.session.getTextRange(editor.selection.getRange()).trim();
if(text.length == 0) {
text = $(this).data('sample');
}
editor.insert('\n```\n' + text + '\n```\n');
editor.focus();
});
// modals
$(document).on('close', '.remodal', function(e) {
editor.focus(); // 关闭modal,编辑器自动获得焦点
});
// overwrite some ACE editor keyboard shortcuts
editor.commands.addCommands([
{
name: "preferences",
bindKey: { win: "Ctrl-,", mac: "Command-," },
exec: function (editor) {
$('i.fa-cog').click(); // show M+ preferences modal
}
}
]);
});
function prompt_for_a_value(key, action) {
$(document).on('opened', '#' + key + '-modal', function() {
$('#' + key + '-code').focus();
});
$('#' + key + '-code').keyup(function(e) {
if(e.which == 13) { // 回车键确认
$('#' + key + '-confirm').click();
}
});
$(document).on('confirm', '#' + key + '-modal', function() {
var value = $('#' + key + '-code').val().trim();
if(value.length > 0) {
action(value);
$('#' + key + '-code').val('');
}
});
}