1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-27 12:07:19 +00:00

Merge branch 'codemirror_keymap' of https://github.com/jbolila/TiddlyWiki5 into jbolila-codemirror_keymap

This commit is contained in:
Jermolene 2014-01-24 21:39:55 +00:00
commit 9539664e46
9 changed files with 4564 additions and 36 deletions

View File

@ -12,23 +12,59 @@ Extend the edit-text widget to use CodeMirror
/*global $tw: false */ /*global $tw: false */
"use strict"; "use strict";
if($tw.browser) { var CODEMIRROR_OPTIONS = "$:/config/CodeMirror", configOptions;
require("$:/plugins/tiddlywiki/codemirror/codemirror.js"); /* e.g. to allow vim key bindings
} * {
* "require": [
* "$:/plugins/tiddlywiki/codemirror/addon/dialog.js",
* "$:/plugins/tiddlywiki/codemirror/addon/searchcursor.js",
* "$:/plugins/tiddlywiki/codemirror/keymap/vim.js"
* ],
* "configuration": {
* "keyMap": "vim",
* "showCursorWhenSelecting": true
* }
*}
*/
var EditTextWidget = require("$:/core/modules/widgets/edit-text.js")["edit-text"]; var EditTextWidget = require("$:/core/modules/widgets/edit-text.js")["edit-text"];
if($tw.browser) {
require("$:/plugins/tiddlywiki/codemirror/codemirror.js");
configOptions = $tw.wiki.getTiddlerData(CODEMIRROR_OPTIONS,{});
if(configOptions) {
if(configOptions["require"]) {
if(typeof configOptions["require"] === 'object' &&
Object.prototype.toString.call(configOptions["require"]) == '[object Array]') {
for (var idx=0; idx < configOptions["require"].length; idx++) {
require(configOptions["require"][idx]);
}
}
else {
require(configOptions["require"]);
}
}
EditTextWidget._configuration = configOptions["configuration"];
}
}
/* /*
The edit-text widget calls this method just after inserting its dom nodes The edit-text widget calls this method just after inserting its dom nodes
*/ */
EditTextWidget.prototype.postRender = function() { EditTextWidget.prototype.postRender = function() {
var self = this, var self = this,
cm; cm, config, cv, cm_opts = {
if($tw.browser && window.CodeMirror && this.editTag === "textarea") {
cm = CodeMirror.fromTextArea(this.domNodes[0],{
lineWrapping: true, lineWrapping: true,
lineNumbers: true lineNumbers: true
}); };
if($tw.browser && window.CodeMirror && this.editTag === "textarea") {
if(EditTextWidget._configuration) {
for (cv in EditTextWidget._configuration) { cm_opts[cv] = EditTextWidget._configuration[cv]; }
}
cm = CodeMirror.fromTextArea(this.domNodes[0], cm_opts);
cm.on("change",function() { cm.on("change",function() {
self.saveChanges(cm.getValue()); self.saveChanges(cm.getValue());
}); });

View File

@ -0,0 +1,32 @@
.CodeMirror-dialog {
position: absolute;
left: 0; right: 0;
background: white;
z-index: 15;
padding: .1em .8em;
overflow: hidden;
color: #333;
}
.CodeMirror-dialog-top {
border-bottom: 1px solid #eee;
top: 0;
}
.CodeMirror-dialog-bottom {
border-top: 1px solid #eee;
bottom: 0;
}
.CodeMirror-dialog input {
border: none;
outline: none;
background: transparent;
width: 20em;
color: inherit;
font-family: monospace;
}
.CodeMirror-dialog button {
font-size: 70%;
}

View File

@ -0,0 +1,121 @@
// Open simple dialogs on top of an editor. Relies on dialog.css.
(function() {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom) {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
} else {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
}
if (typeof template == "string") {
dialog.innerHTML = template;
} else { // Assuming it's a detached DOM element.
dialog.appendChild(template);
}
return dialog;
}
function closeNotification(cm, newVal) {
if (cm.state.currentNotificationClose)
cm.state.currentNotificationClose();
cm.state.currentNotificationClose = newVal;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, me = this;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 13 || e.keyCode == 27) {
CodeMirror.e_stop(e);
close();
me.focus();
if (e.keyCode == 13) callback(inp.value);
}
});
if (options && options.onKeyUp) {
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
}
if (options && options.value) inp.value = options.value;
inp.focus();
CodeMirror.on(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
button.focus();
CodeMirror.on(button, "blur", close);
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
/*
* openNotification
* Opens a notification, that can be closed with an optional timer
* (default 5000ms timer) and always closes on click.
*
* If a notification is opened while another is opened, it will close the
* currently opened one and open the new one immediately.
*/
CodeMirror.defineExtension("openNotification", function(template, options) {
closeNotification(this, close);
var dialog = dialogDiv(this, template, options && options.bottom);
var duration = options && (options.duration === undefined ? 5000 : options.duration);
var closed = false, doneTimer;
function close() {
if (closed) return;
closed = true;
clearTimeout(doneTimer);
dialog.parentNode.removeChild(dialog);
}
CodeMirror.on(dialog, 'click', function(e) {
CodeMirror.e_preventDefault(e);
close();
});
if (duration)
doneTimer = setTimeout(close, options.duration);
});
})();

View File

@ -0,0 +1,143 @@
(function(){
var Pos = CodeMirror.Pos;
function SearchCursor(doc, query, pos, caseFold) {
this.atOccurrence = false; this.doc = doc;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
for (;;) {
query.lastIndex = cutOff;
var newMatch = query.exec(line);
if (!newMatch) break;
match = newMatch;
start = match.index;
cutOff = match.index + (match[0].length || 1);
if (cutOff == line.length) break;
}
var matchLen = (match && match[0].length) || 0;
if (!matchLen) {
if (start == 0 && line.length == 0) {match = undefined;}
else if (start != doc.getLine(pos.line).length) {
matchLen++;
}
}
} else {
query.lastIndex = pos.ch;
var line = doc.getLine(pos.line), match = query.exec(line);
var matchLen = (match && match[0].length) || 0;
var start = match && match.index;
if (start + matchLen != line.length && !matchLen) matchLen = 1;
}
if (match && matchLen)
return {from: Pos(pos.line, start),
to: Pos(pos.line, start + matchLen),
match: match};
};
} else { // String query
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1) {
if (!query.length) {
// Empty string would match anything and never progress, so
// we define it to match nothing instead.
this.matches = function() {};
} else {
this.matches = function(reverse, pos) {
var line = fold(doc.getLine(pos.line)), len = query.length, match;
if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
: (match = line.indexOf(query, pos.ch)) != -1)
return {from: Pos(pos.line, match),
to: Pos(pos.line, match + len)};
};
}
} else {
this.matches = function(reverse, pos) {
var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln));
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
if (reverse ? offsetA > pos.ch || offsetA != match.length
: offsetA < pos.ch || offsetA != line.length - match.length)
return;
for (;;) {
if (reverse ? !ln : ln == doc.lineCount() - 1) return;
line = fold(doc.getLine(ln += reverse ? -1 : 1));
match = target[reverse ? --idx : ++idx];
if (idx > 0 && idx < target.length - 1) {
if (line != match) return;
else continue;
}
var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
return;
var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB);
return {from: reverse ? end : start, to: reverse ? start : end};
}
};
}
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = Pos(line, 0);
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); }
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
}
else {
var maxLine = this.doc.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = Pos(pos.line + 1, 0);
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText) {
if (!this.atOccurrence) return;
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold);
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
})();

View File

@ -1,4 +1,4 @@
// CodeMirror version 3.19.1 // CodeMirror version 3.20
// //
// CodeMirror is the only global var we claim // CodeMirror is the only global var we claim
window.CodeMirror = (function() { window.CodeMirror = (function() {
@ -9,9 +9,13 @@ window.CodeMirror = (function() {
// Crude, but necessary to handle a number of hard-to-feature-detect // Crude, but necessary to handle a number of hard-to-feature-detect
// bugs and behavior differences. // bugs and behavior differences.
var gecko = /gecko\/\d/i.test(navigator.userAgent); var gecko = /gecko\/\d/i.test(navigator.userAgent);
// IE11 currently doesn't count as 'ie', since it has almost none of
// the same bugs as earlier versions. Use ie_gt10 to handle
// incompatibilities in that version.
var ie = /MSIE \d/.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent);
var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
var ie_gt10 = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
var webkit = /WebKit\//.test(navigator.userAgent); var webkit = /WebKit\//.test(navigator.userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
var chrome = /Chrome\//.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent);
@ -908,7 +912,7 @@ window.CodeMirror = (function() {
doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
if (doc.frontier >= cm.display.showingFrom) { // Visible if (doc.frontier >= cm.display.showingFrom) { // Visible
var oldStyles = line.styles; var oldStyles = line.styles;
line.styles = highlightLine(cm, line, state); line.styles = highlightLine(cm, line, state, true);
var ischange = !oldStyles || oldStyles.length != line.styles.length; var ischange = !oldStyles || oldStyles.length != line.styles.length;
for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
if (ischange) { if (ischange) {
@ -917,7 +921,7 @@ window.CodeMirror = (function() {
} }
line.stateAfter = copyState(doc.mode, state); line.stateAfter = copyState(doc.mode, state);
} else { } else {
processLine(cm, line, state); processLine(cm, line.text, state);
line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
} }
++doc.frontier; ++doc.frontier;
@ -961,7 +965,7 @@ window.CodeMirror = (function() {
if (!state) state = startState(doc.mode); if (!state) state = startState(doc.mode);
else state = copyState(doc.mode, state); else state = copyState(doc.mode, state);
doc.iter(pos, n, function(line) { doc.iter(pos, n, function(line) {
processLine(cm, line, state); processLine(cm, line.text, state);
var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
line.stateAfter = save ? copyState(doc.mode, state) : null; line.stateAfter = save ? copyState(doc.mode, state) : null;
++pos; ++pos;
@ -1385,8 +1389,10 @@ window.CodeMirror = (function() {
} }
if (!updated && op.selectionChanged) updateSelection(cm); if (!updated && op.selectionChanged) updateSelection(cm);
if (op.updateScrollPos) { if (op.updateScrollPos) {
display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop; var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, newScrollPos.scrollTop));
display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft; var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, newScrollPos.scrollLeft));
display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
alignHorizontally(cm); alignHorizontally(cm);
if (op.scrollToPos) if (op.scrollToPos)
scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
@ -1905,7 +1911,6 @@ window.CodeMirror = (function() {
if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
cm.replaceSelection(text, null, "paste"); cm.replaceSelection(text, null, "paste");
focusInput(cm); focusInput(cm);
onFocus(cm);
} }
} }
catch(e){} catch(e){}
@ -2761,10 +2766,10 @@ window.CodeMirror = (function() {
for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
if (pos < indentation) indentString += spaceStr(indentation - pos); if (pos < indentation) indentString += spaceStr(indentation - pos);
if (indentString == curSpaceString) if (indentString != curSpaceString)
setSelection(cm.doc, Pos(n, curSpaceString.length), Pos(n, curSpaceString.length));
else
replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
else if (doc.sel.head.line == n && doc.sel.head.ch < curSpaceString.length)
setSelection(doc, Pos(n, curSpaceString.length), Pos(n, curSpaceString.length), 1);
line.stateAfter = null; line.stateAfter = null;
} }
@ -2865,7 +2870,7 @@ window.CodeMirror = (function() {
CodeMirror.prototype = { CodeMirror.prototype = {
constructor: CodeMirror, constructor: CodeMirror,
focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, focus: function(){window.focus(); focusInput(this); fastPoll(this);},
setOption: function(option, value) { setOption: function(option, value) {
var options = this.options, old = options[option]; var options = this.options, old = options[option];
@ -3278,8 +3283,14 @@ window.CodeMirror = (function() {
clearCaches(cm); clearCaches(cm);
regChange(cm); regChange(cm);
}, true); }, true);
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
cm.refresh();
}, true);
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
option("electricChars", true); option("electricChars", true);
option("rtlMoveVisually", !windows); option("rtlMoveVisually", !windows);
option("wholeLineUpdateBefore", true);
option("theme", "default", function(cm) { option("theme", "default", function(cm) {
themeChanged(cm); themeChanged(cm);
@ -3312,8 +3323,14 @@ window.CodeMirror = (function() {
option("resetSelectionOnContextMenu", true); option("resetSelectionOnContextMenu", true);
option("readOnly", false, function(cm, val) { option("readOnly", false, function(cm, val) {
if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} if (val == "nocursor") {
else if (!val) resetInput(cm, true); onBlur(cm);
cm.display.input.blur();
cm.display.disabled = true;
} else {
cm.display.disabled = false;
if (!val) resetInput(cm, true);
}
}); });
option("dragDrop", true); option("dragDrop", true);
@ -4247,6 +4264,7 @@ window.CodeMirror = (function() {
this.height = estimateHeight ? estimateHeight(this) : 1; this.height = estimateHeight ? estimateHeight(this) : 1;
}; };
eventMixin(Line); eventMixin(Line);
Line.prototype.lineNo = function() { return lineNo(this); };
function updateLine(line, text, markedSpans, estimateHeight) { function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text; line.text = text;
@ -4267,7 +4285,7 @@ window.CodeMirror = (function() {
// Run the given mode's parser over a line, update the styles // Run the given mode's parser over a line, update the styles
// array, which contains alternating fragments of text and CSS // array, which contains alternating fragments of text and CSS
// classes. // classes.
function runMode(cm, text, mode, state, f) { function runMode(cm, text, mode, state, f, forceToEnd) {
var flattenSpans = mode.flattenSpans; var flattenSpans = mode.flattenSpans;
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
var curStart = 0, curStyle = null; var curStart = 0, curStyle = null;
@ -4276,6 +4294,7 @@ window.CodeMirror = (function() {
while (!stream.eol()) { while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) { if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false; flattenSpans = false;
if (forceToEnd) processLine(cm, text, state, stream.pos);
stream.pos = text.length; stream.pos = text.length;
style = null; style = null;
} else { } else {
@ -4295,12 +4314,14 @@ window.CodeMirror = (function() {
} }
} }
function highlightLine(cm, line, state) { function highlightLine(cm, line, state, forceToEnd) {
// A styles array always starts with a number identifying the // A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation). // mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen]; var st = [cm.state.modeGen];
// Compute the base array of styles // Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);}); runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
st.push(end, style);
}, forceToEnd);
// Run overlays, adjust style array. // Run overlays, adjust style array.
for (var o = 0; o < cm.state.overlays.length; ++o) { for (var o = 0; o < cm.state.overlays.length; ++o) {
@ -4339,10 +4360,11 @@ window.CodeMirror = (function() {
// Lightweight form of highlight -- proceed over this line and // Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. // update state, but don't save a style array.
function processLine(cm, line, state) { function processLine(cm, text, state, startAt) {
var mode = cm.doc.mode; var mode = cm.doc.mode;
var stream = new StringStream(line.text, cm.options.tabSize); var stream = new StringStream(text, cm.options.tabSize);
if (line.text == "" && mode.blankLine) mode.blankLine(state); stream.start = stream.pos = startAt || 0;
if (text == "" && mode.blankLine) mode.blankLine(state);
while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
mode.token(stream, state); mode.token(stream, state);
stream.start = stream.pos; stream.start = stream.pos;
@ -4399,7 +4421,7 @@ window.CodeMirror = (function() {
// Work around problem with the reported dimensions of single-char // Work around problem with the reported dimensions of single-char
// direction spans on IE (issue #1129). See also the comment in // direction spans on IE (issue #1129). See also the comment in
// cursorCoords. // cursorCoords.
if (measure && ie && (order = getOrder(line))) { if (measure && (ie || ie_gt10) && (order = getOrder(line))) {
var l = order.length - 1; var l = order.length - 1;
if (order[l].from == order[l].to) --l; if (order[l].from == order[l].to) --l;
var last = order[l], prev = order[l - 1]; var last = order[l], prev = order[l - 1];
@ -4417,17 +4439,23 @@ window.CodeMirror = (function() {
return builder; return builder;
} }
var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g; function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + ch.charCodeAt(0).toString(16);
return token;
}
function buildToken(builder, text, style, startStyle, endStyle, title) { function buildToken(builder, text, style, startStyle, endStyle, title) {
if (!text) return; if (!text) return;
if (!tokenSpecialChars.test(text)) { var special = builder.cm.options.specialChars;
if (!special.test(text)) {
builder.col += text.length; builder.col += text.length;
var content = document.createTextNode(text); var content = document.createTextNode(text);
} else { } else {
var content = document.createDocumentFragment(), pos = 0; var content = document.createDocumentFragment(), pos = 0;
while (true) { while (true) {
tokenSpecialChars.lastIndex = pos; special.lastIndex = pos;
var m = tokenSpecialChars.exec(text); var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos; var skipped = m ? m.index - pos : text.length - pos;
if (skipped) { if (skipped) {
content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
@ -4440,8 +4468,7 @@ window.CodeMirror = (function() {
content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
builder.col += tabWidth; builder.col += tabWidth;
} else { } else {
var token = elt("span", "\u2022", "cm-invalidchar"); var token = builder.cm.options.specialCharPlaceholder(m[0]);
token.title = "\\u" + m[0].charCodeAt(0).toString(16);
content.appendChild(token); content.appendChild(token);
builder.col += 1; builder.col += 1;
} }
@ -4594,7 +4621,8 @@ window.CodeMirror = (function() {
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
// First adjust the line structure // First adjust the line structure
if (from.ch == 0 && to.ch == 0 && lastText == "") { if (from.ch == 0 && to.ch == 0 && lastText == "" &&
(!doc.cm || doc.cm.options.wholeLineUpdateBefore)) {
// This is a whole-line replace. Treated specially to make // This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to. // sure line objects move the way they are supposed to.
for (var i = 0, e = text.length - 1, added = []; i < e; ++i) for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
@ -5481,7 +5509,7 @@ window.CodeMirror = (function() {
return true; return true;
} }
var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\u1DC0\u1DFF\u20D0\u20FF\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff\uFE20\uFE2F]/;
// DOM UTILITIES // DOM UTILITIES
@ -5910,7 +5938,7 @@ window.CodeMirror = (function() {
// THE END // THE END
CodeMirror.version = "3.19.1"; CodeMirror.version = "3.20.0";
return CodeMirror; return CodeMirror;
})(); })();

View File

@ -0,0 +1,387 @@
(function() {
"use strict";
var Pos = CodeMirror.Pos;
function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
// Kill 'ring'
var killRing = [];
function addToRing(str) {
killRing.push(str);
if (killRing.length > 50) killRing.shift();
}
function growRingTop(str) {
if (!killRing.length) return addToRing(str);
killRing[killRing.length - 1] += str;
}
function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
var lastKill = null;
function kill(cm, from, to, mayGrow, text) {
if (text == null) text = cm.getRange(from, to);
if (mayGrow && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
growRingTop(text);
else
addToRing(text);
cm.replaceRange("", from, to, "+delete");
if (mayGrow) lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
else lastKill = null;
}
// Boundaries of various units
function byChar(cm, pos, dir) {
return cm.findPosH(pos, dir, "char", true);
}
function byWord(cm, pos, dir) {
return cm.findPosH(pos, dir, "word", true);
}
function byLine(cm, pos, dir) {
return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
}
function byPage(cm, pos, dir) {
return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
}
function byParagraph(cm, pos, dir) {
var no = pos.line, line = cm.getLine(no);
var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
var fst = cm.firstLine(), lst = cm.lastLine();
for (;;) {
no += dir;
if (no < fst || no > lst)
return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
line = cm.getLine(no);
var hasText = /\S/.test(line);
if (hasText) sawText = true;
else if (sawText) return Pos(no, 0);
}
}
function bySentence(cm, pos, dir) {
var line = pos.line, ch = pos.ch;
var text = cm.getLine(pos.line), sawWord = false;
for (;;) {
var next = text.charAt(ch + (dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
continue;
}
if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
if (!sawWord) sawWord = /\w/.test(next);
ch += dir;
}
}
function byExpr(cm, pos, dir) {
var wrap;
if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, true))
&& wrap.match && (wrap.forward ? 1 : -1) == dir)
return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
for (var first = true;; first = false) {
var token = cm.getTokenAt(pos);
var after = Pos(pos.line, dir < 0 ? token.start : token.end);
if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
var newPos = cm.findPosH(after, dir, "char");
if (posEq(after, newPos)) return pos;
else pos = newPos;
} else {
return after;
}
}
}
// Prefixes (only crudely supported)
function getPrefix(cm, precise) {
var digits = cm.state.emacsPrefix;
if (!digits) return precise ? null : 1;
clearPrefix(cm);
return digits == "-" ? -1 : Number(digits);
}
function repeated(cmd) {
var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
return function(cm) {
var prefix = getPrefix(cm);
f(cm);
for (var i = 1; i < prefix; ++i) f(cm);
};
}
function findEnd(cm, by, dir) {
var pos = cm.getCursor(), prefix = getPrefix(cm);
if (prefix < 0) { dir = -dir; prefix = -prefix; }
for (var i = 0; i < prefix; ++i) {
var newPos = by(cm, pos, dir);
if (posEq(newPos, pos)) break;
pos = newPos;
}
return pos;
}
function move(by, dir) {
var f = function(cm) {
cm.extendSelection(findEnd(cm, by, dir));
};
f.motion = true;
return f;
}
function killTo(cm, by, dir) {
kill(cm, cm.getCursor(), findEnd(cm, by, dir), true);
}
function addPrefix(cm, digit) {
if (cm.state.emacsPrefix) {
if (digit != "-") cm.state.emacsPrefix += digit;
return;
}
// Not active yet
cm.state.emacsPrefix = digit;
cm.on("keyHandled", maybeClearPrefix);
cm.on("inputRead", maybeDuplicateInput);
}
var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
function maybeClearPrefix(cm, arg) {
if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
clearPrefix(cm);
}
function clearPrefix(cm) {
cm.state.emacsPrefix = null;
cm.off("keyHandled", maybeClearPrefix);
cm.off("inputRead", maybeDuplicateInput);
}
function maybeDuplicateInput(cm, event) {
var dup = getPrefix(cm);
if (dup > 1 && event.origin == "+input") {
var one = event.text.join("\n"), txt = "";
for (var i = 1; i < dup; ++i) txt += one;
cm.replaceSelection(txt, "end", "+input");
}
}
function addPrefixMap(cm) {
cm.state.emacsPrefixMap = true;
cm.addKeyMap(prefixMap);
cm.on("keyHandled", maybeRemovePrefixMap);
cm.on("inputRead", maybeRemovePrefixMap);
}
function maybeRemovePrefixMap(cm, arg) {
if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
cm.removeKeyMap(prefixMap);
cm.state.emacsPrefixMap = false;
cm.off("keyHandled", maybeRemovePrefixMap);
cm.off("inputRead", maybeRemovePrefixMap);
}
// Utilities
function setMark(cm) {
cm.setCursor(cm.getCursor());
cm.setExtending(true);
cm.on("change", function() { cm.setExtending(false); });
}
function getInput(cm, msg, f) {
if (cm.openDialog)
cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
else
f(prompt(msg, ""));
}
function operateOnWord(cm, op) {
var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
cm.replaceRange(op(cm.getRange(start, end)), start, end);
cm.setCursor(end);
}
function toEnclosingExpr(cm) {
var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
var stack = [];
while (line >= cm.firstLine()) {
var text = cm.getLine(line);
for (var i = ch == null ? text.length : ch; i > 0;) {
var ch = text.charAt(--i);
if (ch == ")")
stack.push("(");
else if (ch == "]")
stack.push("[");
else if (ch == "}")
stack.push("{");
else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
return cm.extendSelection(Pos(line, i));
}
--line; ch = null;
}
}
// Actual keymap
var keyMap = CodeMirror.keyMap.emacs = {
"Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));},
"Ctrl-K": repeated(function(cm) {
var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
var text = cm.getRange(start, end);
if (!/\S/.test(text)) {
text += "\n";
end = Pos(start.line + 1, 0);
}
kill(cm, start, end, true, text);
}),
"Alt-W": function(cm) {
addToRing(cm.getSelection());
},
"Ctrl-Y": function(cm) {
var start = cm.getCursor();
cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
cm.setSelection(start, cm.getCursor());
},
"Alt-Y": function(cm) {cm.replaceSelection(popFromRing());},
"Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,
"Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
"Right": move(byChar, 1), "Left": move(byChar, -1),
"Ctrl-D": function(cm) { killTo(cm, byChar, 1); },
"Delete": function(cm) { killTo(cm, byChar, 1); },
"Ctrl-H": function(cm) { killTo(cm, byChar, -1); },
"Backspace": function(cm) { killTo(cm, byChar, -1); },
"Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
"Alt-D": function(cm) { killTo(cm, byWord, 1); },
"Alt-Backspace": function(cm) { killTo(cm, byWord, -1); },
"Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
"Down": move(byLine, 1), "Up": move(byLine, -1),
"Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"End": "goLineEnd", "Home": "goLineStart",
"Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
"PageUp": move(byPage, -1), "PageDown": move(byPage, 1),
"Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),
"Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
"Alt-K": function(cm) { killTo(cm, bySentence, 1); },
"Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1); },
"Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1); },
"Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1),
"Shift-Ctrl-Alt-2": function(cm) {
cm.setSelection(findEnd(cm, byExpr, 1), cm.getCursor());
},
"Ctrl-Alt-T": function(cm) {
var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
},
"Ctrl-Alt-U": repeated(toEnclosingExpr),
"Alt-Space": function(cm) {
var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
while (from && /\s/.test(text.charAt(from - 1))) --from;
while (to < text.length && /\s/.test(text.charAt(to))) ++to;
cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
},
"Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
"Ctrl-T": repeated(function(cm) {
var pos = cm.getCursor();
if (pos.ch < cm.getLine(pos.line).length) pos = Pos(pos.line, pos.ch + 1);
var from = cm.findPosH(pos, -2, "char");
var range = cm.getRange(from, pos);
if (range.length != 2) return;
cm.setSelection(from, pos);
cm.replaceSelection(range.charAt(1) + range.charAt(0), "end");
}),
"Alt-C": repeated(function(cm) {
operateOnWord(cm, function(w) {
var letter = w.search(/\w/);
if (letter == -1) return w;
return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
});
}),
"Alt-U": repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toUpperCase(); });
}),
"Alt-L": repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toLowerCase(); });
}),
"Alt-;": "toggleComment",
"Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
"Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
"Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
"Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
"Alt-/": "autocomplete",
"Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
"Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");},
"Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
"Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");},
"Ctrl-U": addPrefixMap
};
CodeMirror.keyMap["emacs-Ctrl-X"] = {
"Tab": function(cm) {
cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
},
"Ctrl-X": function(cm) {
cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
},
"Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close",
"Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); },
auto: "emacs", nofallthrough: true, disableInput: true
};
CodeMirror.keyMap["emacs-Alt-G"] = {
"G": function(cm) {
var prefix = getPrefix(cm, true);
if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
getInput(cm, "Goto line", function(str) {
var num;
if (str && !isNaN(num = Number(str)) && num == num|0 && num > 0)
cm.setCursor(num - 1);
});
},
auto: "emacs", nofallthrough: true, disableInput: true
};
CodeMirror.keyMap["emacs-Ctrl-Q"] = {
"Tab": repeated("insertTab"),
auto: "emacs", nofallthrough: true
};
var prefixMap = {"Ctrl-G": clearPrefix};
function regPrefix(d) {
prefixMap[d] = function(cm) { addPrefix(cm, d); };
keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
prefixPreservingKeys["Ctrl-" + d] = true;
}
for (var i = 0; i < 10; ++i) regPrefix(String(i));
regPrefix("-");
})();

View File

@ -0,0 +1,43 @@
// A number of additional default bindings that are too obscure to
// include in the core codemirror.js file.
(function() {
"use strict";
var Pos = CodeMirror.Pos;
function moveLines(cm, start, end, dist) {
if (!dist || start > end) return 0;
var from = cm.clipPos(Pos(start, 0)), to = cm.clipPos(Pos(end));
var text = cm.getRange(from, to);
if (start <= cm.firstLine())
cm.replaceRange("", from, Pos(to.line + 1, 0));
else
cm.replaceRange("", Pos(from.line - 1), to);
var target = from.line + dist;
if (target <= cm.firstLine()) {
cm.replaceRange(text + "\n", Pos(target, 0));
return cm.firstLine() - from.line;
} else {
var targetPos = cm.clipPos(Pos(target - 1));
cm.replaceRange("\n" + text, targetPos);
return targetPos.line + 1 - from.line;
}
}
function moveSelectedLines(cm, dist) {
var head = cm.getCursor("head"), anchor = cm.getCursor("anchor");
cm.operation(function() {
var moved = moveLines(cm, Math.min(head.line, anchor.line), Math.max(head.line, anchor.line), dist);
cm.setSelection(Pos(anchor.line + moved, anchor.ch), Pos(head.line + moved, head.ch));
});
}
CodeMirror.commands.moveLinesUp = function(cm) { moveSelectedLines(cm, -1); };
CodeMirror.commands.moveLinesDown = function(cm) { moveSelectedLines(cm, 1); };
CodeMirror.keyMap["default"]["Alt-Up"] = "moveLinesUp";
CodeMirror.keyMap["default"]["Alt-Down"] = "moveLinesDown";
})();

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,41 @@
"title": "$:/plugins/tiddlywiki/codemirror/codemirror.css", "title": "$:/plugins/tiddlywiki/codemirror/codemirror.css",
"tags": "[[$:/tags/stylesheet]]" "tags": "[[$:/tags/stylesheet]]"
} }
},{
"file": "addon/dialog.css",
"fields": {
"type": "text/css",
"title": "$:/plugins/tiddlywiki/codemirror/addon/dialog.css",
"tags": "[[$:/tags/stylesheet]]"
}
},{
"file": "addon/dialog.js",
"fields": {
"type": "application/javascript",
"title": "$:/plugins/tiddlywiki/codemirror/addon/dialog.js",
"module-type": "library"
}
},{
"file": "addon/searchcursor.js",
"fields": {
"type": "application/javascript",
"title": "$:/plugins/tiddlywiki/codemirror/addon/searchcursor.js",
"module-type": "library"
}
},{
"file": "keymap/vim.js",
"fields": {
"type": "application/javascript",
"title": "$:/plugins/tiddlywiki/codemirror/keymap/vim.js",
"module-type": "library"
}
},{
"file": "keymap/emacs.js",
"fields": {
"type": "application/javascript",
"title": "$:/plugins/tiddlywiki/codemirror/keymap/emacs.js",
"module-type": "library"
}
} }
] ]
} }