-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.tk.codeedit.js
52 lines (41 loc) · 1.48 KB
/
jquery.tk.codeedit.js
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
(function($){
var insertAt = function(text, startPos, endPos, replacement) {
return text.substring(0, startPos) + replacement + text.substring(endPos, text.length);
};
// http://stackoverflow.com/a/1738888/38729
$.fn.codeEdit = function() {
var $this = $(this);
$this.each(function() {
$this.keydown(function (e) {
if (e.keyCode == 9) { // tab
var insertedToken = "\t",
startPos = this.selectionStart,
endPos = this.selectionEnd,
scrollTop = this.scrollTop;
this.value = insertAt(this.value, startPos, endPos, insertedToken);
this.focus();
this.selectionStart = startPos + insertedToken.length;
this.selectionEnd = startPos + insertedToken.length;
this.scrollTop = scrollTop;
e.preventDefault();
} else if (e.keyCode == 13) { // enter
var startPos = this.selectionStart,
endPos = this.selectionEnd,
text = this.value,
textBeforeSelection = text.substr(0, startPos),
linesBeforeStart = textBeforeSelection.split("\n"),
lastLineBeforeStart = linesBeforeStart[linesBeforeStart.length - 1],
tabsOnTheBeginningOfLine = lastLineBeforeStart.match(/^([\s]*)/);
if (tabsOnTheBeginningOfLine.length) {
var tabs = "\n" + tabsOnTheBeginningOfLine[0];
this.value = insertAt(this.value, startPos, endPos, tabs);
this.selectionStart = startPos + tabs.length;
this.selectionEnd = startPos + tabs.length;
}
e.preventDefault();
}
});
});
return $this;
}
}($));