View | Details | Raw Unified | Return to bug 11559
Collapse All | Expand All

(-)a/cataloguing/addbiblio.pl (+6 lines)
Lines 767-774 if ($frameworkcode eq 'FA'){ Link Here
767
        'stickyduedate'      => $fa_stickyduedate,
767
        'stickyduedate'      => $fa_stickyduedate,
768
        'duedatespec'        => $fa_duedatespec,
768
        'duedatespec'        => $fa_duedatespec,
769
    );
769
    );
770
} elsif ( $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' && !$breedingid ) {
771
    # Only use the advanced editor for non-fast-cataloging.
772
    # breedingid is not handled because those would only come off a Z39.50
773
    # search initiated by the basic editor.
774
    print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( '#catalog:' . $biblionumber ) : '' ) );
770
}
775
}
771
776
777
772
# Getting the list of all frameworks
778
# Getting the list of all frameworks
773
# get framework list
779
# get framework list
774
my $frameworks = getframeworks;
780
my $frameworks = getframeworks;
(-)a/cataloguing/editor.pl (+53 lines)
Line 0 Link Here
1
#!/usr/bin/perl
2
#
3
# Copyright 2013 ByWater
4
#
5
# This file is part of Koha.
6
#
7
# Koha is free software; you can redistribute it and/or modify it under the
8
# terms of the GNU General Public License as published by the Free Software
9
# Foundation; either version 2 of the License, or (at your option) any later
10
# version.
11
#
12
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License along
17
# with Koha; if not, write to the Free Software Foundation, Inc.,
18
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
#
20
21
use Modern::Perl '2009';
22
23
use CGI;
24
use MARC::Record;
25
26
use C4::Auth;
27
use C4::Biblio;
28
use C4::Context;
29
use C4::Output;
30
31
my $input = CGI->new;
32
33
my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
34
    {
35
        template_name   => 'cataloguing/editor.tt',
36
        query           => $input,
37
        type            => 'intranet',
38
        authnotrequired => 0,
39
        flagsrequired   => { editcatalogue => 'edit_catalogue' },
40
    }
41
);
42
43
# Needed information for cataloging plugins
44
$template->{VARS}->{DefaultLanguageField008} = pack( 'A3', C4::Context->preference('DefaultLanguageField008') || 'eng' );
45
46
# Z39.50 servers
47
my $dbh = C4::Context->dbh;
48
$template->{VARS}->{z3950_targets} = $dbh->selectall_arrayref( q{
49
    SELECT * FROM z3950servers
50
    ORDER BY name
51
}, { Slice => {} } );
52
53
output_html_with_http_headers $input, $cookie, $template->output;
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/codemirror-compressed.js (+11 lines)
Line 0 Link Here
1
// CodeMirror 3.14
2
//
3
// Licensed under the MIT license.
4
// Copyright (C) 2014 by Marijn Haverbeke <marijnh@gmail.com> and others.
5
//
6
// Packaged along with the runmode addon, using the compression helper at codemirror.net.
7
//
8
window.CodeMirror=function(){"use strict";function w(a,c){if(!(this instanceof w))return new w(a,c);this.options=c=c||{};for(var d in Wc)!c.hasOwnProperty(d)&&Wc.hasOwnProperty(d)&&(c[d]=Wc[d]);I(c);var e="string"==typeof c.value?0:c.value.first,f=this.display=x(a,e);f.wrapper.CodeMirror=this,F(this),c.autofocus&&!o&&Kb(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,draggingText:!1,highlight:new Qe},D(this),c.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");var g=c.value;"string"==typeof g&&(g=new ae(c.value,c.mode)),Cb(this,ee)(this,g),b&&setTimeout($e(Jb,this,!0),20),Mb(this);var h;try{h=document.activeElement==f.input}catch(i){}h||c.autofocus&&!o?setTimeout($e(hc,this),20):ic(this),Cb(this,function(){for(var a in Vc)Vc.propertyIsEnumerable(a)&&Vc[a](this,c[a],Yc);for(var b=0;b<ad.length;++b)ad[b](this)})()}function x(a,b){var d={},f=d.input=df("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");return e?f.style.width="1000px":f.setAttribute("wrap","off"),n&&(f.style.border="1px solid black"),f.setAttribute("autocorrect","off"),f.setAttribute("autocapitalize","off"),f.setAttribute("spellcheck","false"),d.inputDiv=df("div",[f],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),d.scrollbarH=df("div",[df("div",null,null,"height: 1px")],"CodeMirror-hscrollbar"),d.scrollbarV=df("div",[df("div",null,null,"width: 1px")],"CodeMirror-vscrollbar"),d.scrollbarFiller=df("div",null,"CodeMirror-scrollbar-filler"),d.gutterFiller=df("div",null,"CodeMirror-gutter-filler"),d.lineDiv=df("div",null,"CodeMirror-code"),d.selectionDiv=df("div",null,null,"position: relative; z-index: 1"),d.cursor=df("div","\xa0","CodeMirror-cursor"),d.otherCursor=df("div","\xa0","CodeMirror-cursor CodeMirror-secondarycursor"),d.measure=df("div",null,"CodeMirror-measure"),d.lineSpace=df("div",[d.measure,d.selectionDiv,d.lineDiv,d.cursor,d.otherCursor],null,"position: relative; outline: none"),d.mover=df("div",[df("div",[d.lineSpace],"CodeMirror-lines")],null,"position: relative"),d.sizer=df("div",[d.mover],"CodeMirror-sizer"),d.heightForcer=df("div",null,null,"position: absolute; height: "+Oe+"px; width: 1px;"),d.gutters=df("div",null,"CodeMirror-gutters"),d.lineGutter=null,d.scroller=df("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll"),d.scroller.setAttribute("tabIndex","-1"),d.wrapper=df("div",[d.inputDiv,d.scrollbarH,d.scrollbarV,d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror"),c&&(d.gutters.style.zIndex=-1,d.scroller.style.paddingRight=0),a.appendChild?a.appendChild(d.wrapper):a(d.wrapper),n&&(f.style.width="0px"),e||(d.scroller.draggable=!0),j?(d.inputDiv.style.height="1px",d.inputDiv.style.position="absolute"):c&&(d.scrollbarH.style.minWidth=d.scrollbarV.style.minWidth="18px"),d.viewOffset=d.lastSizeC=0,d.showingFrom=d.showingTo=b,d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null,d.prevInput="",d.alignWidgets=!1,d.pollingFast=!1,d.poll=new Qe,d.cachedCharWidth=d.cachedTextHeight=null,d.measureLineCache=[],d.measureLineCachePos=0,d.inaccurateSelection=!1,d.maxLine=null,d.maxLineLength=0,d.maxLineChanged=!1,d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null,d}function y(a){a.doc.mode=w.getMode(a.options,a.doc.modeOption),a.doc.iter(function(a){a.stateAfter&&(a.stateAfter=null),a.styles&&(a.styles=null)}),a.doc.frontier=a.doc.first,_(a,100),a.state.modeGen++,a.curOp&&Fb(a)}function z(a){a.options.lineWrapping?(a.display.wrapper.className+=" CodeMirror-wrap",a.display.sizer.style.minWidth=""):(a.display.wrapper.className=a.display.wrapper.className.replace(" CodeMirror-wrap",""),H(a)),B(a),Fb(a),mb(a),setTimeout(function(){J(a)},100)}function A(a){var b=xb(a.display),c=a.options.lineWrapping,d=c&&Math.max(5,a.display.scroller.clientWidth/yb(a.display)-3);return function(e){return Ad(a.doc,e)?0:c?(Math.ceil(e.text.length/d)||1)*b:b}}function B(a){var b=a.doc,c=A(a);b.iter(function(a){var b=c(a);b!=a.height&&ie(a,b)})}function C(a){var b=ed[a.options.keyMap],c=b.style;a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(c?" cm-keymap-"+c:""),a.state.disableInput=b.disableInput}function D(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-"),mb(a)}function E(a){F(a),Fb(a),setTimeout(function(){L(a)},20)}function F(a){var b=a.display.gutters,c=a.options.gutters;ef(b);for(var d=0;d<c.length;++d){var e=c[d],f=b.appendChild(df("div",null,"CodeMirror-gutter "+e));"CodeMirror-linenumbers"==e&&(a.display.lineGutter=f,f.style.width=(a.display.lineNumWidth||1)+"px")}b.style.display=d?"":"none"}function G(a,b){if(0==b.height)return 0;for(var d,c=b.text.length,e=b;d=xd(e);){var f=d.find();e=fe(a,f.from.line),c+=f.from.ch-f.to.ch}for(e=b;d=yd(e);){var f=d.find();c-=e.text.length-f.from.ch,e=fe(a,f.to.line),c+=e.text.length-f.to.ch}return c}function H(a){var b=a.display,c=a.doc;b.maxLine=fe(c,c.first),b.maxLineLength=G(c,b.maxLine),b.maxLineChanged=!0,c.iter(function(a){var d=G(c,a);d>b.maxLineLength&&(b.maxLineLength=d,b.maxLine=a)})}function I(a){for(var b=!1,c=0;c<a.gutters.length;++c)"CodeMirror-linenumbers"==a.gutters[c]&&(a.lineNumbers?b=!0:a.gutters.splice(c--,1));!b&&a.lineNumbers&&a.gutters.push("CodeMirror-linenumbers")}function J(a){var b=a.display,c=a.doc.height,d=c+eb(b);b.sizer.style.minHeight=b.heightForcer.style.top=d+"px",b.gutters.style.height=Math.max(d,b.scroller.clientHeight-Oe)+"px";var e=Math.max(d,b.scroller.scrollHeight),f=b.scroller.scrollWidth>b.scroller.clientWidth+1,g=e>b.scroller.clientHeight+1;g?(b.scrollbarV.style.display="block",b.scrollbarV.style.bottom=f?mf(b.measure)+"px":"0",b.scrollbarV.firstChild.style.height=e-b.scroller.clientHeight+b.scrollbarV.clientHeight+"px"):b.scrollbarV.style.display="",f?(b.scrollbarH.style.display="block",b.scrollbarH.style.right=g?mf(b.measure)+"px":"0",b.scrollbarH.firstChild.style.width=b.scroller.scrollWidth-b.scroller.clientWidth+b.scrollbarH.clientWidth+"px"):b.scrollbarH.style.display="",f&&g?(b.scrollbarFiller.style.display="block",b.scrollbarFiller.style.height=b.scrollbarFiller.style.width=mf(b.measure)+"px"):b.scrollbarFiller.style.display="",f&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(b.gutterFiller.style.display="block",b.gutterFiller.style.height=mf(b.measure)+"px",b.gutterFiller.style.width=b.gutters.offsetWidth+"px"):b.gutterFiller.style.display="",k&&0===mf(b.measure)&&(b.scrollbarV.style.minWidth=b.scrollbarH.style.minHeight=l?"18px":"12px")}function K(a,b,c){var d=a.scroller.scrollTop,e=a.wrapper.clientHeight;"number"==typeof c?d=c:c&&(d=c.top,e=c.bottom-c.top),d=Math.floor(d-db(a));var f=Math.ceil(d+e);return{from:ke(b,d),to:ke(b,f)}}function L(a){var b=a.display;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var c=O(b)-b.scroller.scrollLeft+a.doc.scrollLeft,d=b.gutters.offsetWidth,e=c+"px",f=b.lineDiv.firstChild;f;f=f.nextSibling)if(f.alignable)for(var g=0,h=f.alignable;g<h.length;++g)h[g].style.left=e;a.options.fixedGutter&&(b.gutters.style.left=c+d+"px")}}function M(a){if(!a.options.lineNumbers)return!1;var b=a.doc,c=N(a.options,b.first+b.size-1),d=a.display;if(c.length!=d.lineNumChars){var e=d.measure.appendChild(df("div",[df("div",c)],"CodeMirror-linenumber CodeMirror-gutter-elt")),f=e.firstChild.offsetWidth,g=e.offsetWidth-f;return d.lineGutter.style.width="",d.lineNumInnerWidth=Math.max(f,d.lineGutter.offsetWidth-g),d.lineNumWidth=d.lineNumInnerWidth+g,d.lineNumChars=d.lineNumInnerWidth?c.length:-1,d.lineGutter.style.width=d.lineNumWidth+"px",!0}return!1}function N(a,b){return String(a.lineNumberFormatter(b+a.firstLineNumber))}function O(a){return hf(a.scroller).left-hf(a.sizer).left}function P(a,b,c){for(var f,d=a.display.showingFrom,e=a.display.showingTo,g=K(a.display,a.doc,c);Q(a,b,g)&&(f=!0,X(a),J(a),c&&(c=Math.min(a.display.scroller.scrollHeight-a.display.scroller.clientHeight,"number"==typeof c?c:c.top)),g=K(a.display,a.doc,c),!(g.from>=a.display.showingFrom&&g.to<=a.display.showingTo));)b=[];return f&&(Ke(a,"update",a),(a.display.showingFrom!=d||a.display.showingTo!=e)&&Ke(a,"viewportChange",a,a.display.showingFrom,a.display.showingTo)),f}function Q(a,b,d){var e=a.display,f=a.doc;if(!e.wrapper.clientWidth)return e.showingFrom=e.showingTo=f.first,e.viewOffset=0,void 0;if(!(0==b.length&&d.from>e.showingFrom&&d.to<e.showingTo)){M(a)&&(b=[{from:f.first,to:f.first+f.size}]);var g=e.sizer.style.marginLeft=e.gutters.offsetWidth+"px";e.scrollbarH.style.left=a.options.fixedGutter?g:"0";var h=1/0;if(a.options.lineNumbers)for(var i=0;i<b.length;++i)if(b[i].diff){h=b[i].from;break}var j=f.first+f.size,k=Math.max(d.from-a.options.viewportMargin,f.first),l=Math.min(j,d.to+a.options.viewportMargin);if(e.showingFrom<k&&k-e.showingFrom<20&&(k=Math.max(f.first,e.showingFrom)),e.showingTo>l&&e.showingTo-l<20&&(l=Math.min(j,e.showingTo)),v)for(k=je(zd(f,fe(f,k)));j>l&&Ad(f,fe(f,l));)++l;var m=[{from:Math.max(e.showingFrom,f.first),to:Math.min(e.showingTo,j)}];if(m=m[0].from>=m[0].to?[]:S(m,b),v)for(var i=0;i<m.length;++i)for(var o,n=m[i];o=yd(fe(f,n.to-1));){var p=o.find().from.line;if(!(p>n.from)){m.splice(i--,1);break}n.to=p}for(var q=0,i=0;i<m.length;++i){var n=m[i];n.from<k&&(n.from=k),n.to>l&&(n.to=l),n.from>=n.to?m.splice(i--,1):q+=n.to-n.from}if(q==l-k&&k==e.showingFrom&&l==e.showingTo)return R(a),void 0;m.sort(function(a,b){return a.from-b.from});try{var r=document.activeElement}catch(s){}.7*(l-k)>q&&(e.lineDiv.style.display="none"),U(a,k,l,m,h),e.lineDiv.style.display="",r&&document.activeElement!=r&&r.offsetHeight&&r.focus();var t=k!=e.showingFrom||l!=e.showingTo||e.lastSizeC!=e.wrapper.clientHeight;t&&(e.lastSizeC=e.wrapper.clientHeight,_(a,400)),e.showingFrom=k,e.showingTo=l;for(var x,u=e.lineDiv.offsetTop,w=e.lineDiv.firstChild;w;w=w.nextSibling)if(w.lineObj){if(c){var y=w.offsetTop+w.offsetHeight;x=y-u,u=y}else{var z=hf(w);x=z.bottom-z.top}var A=w.lineObj.height-x;if(2>x&&(x=xb(e)),A>.001||-.001>A){ie(w.lineObj,x);var B=w.lineObj.widgets;if(B)for(var i=0;i<B.length;++i)B[i].height=B[i].node.offsetHeight}}return R(a),!0}}function R(a){var b=a.display.viewOffset=le(a,fe(a.doc,a.display.showingFrom));a.display.mover.style.top=b+"px"}function S(a,b){for(var c=0,d=b.length||0;d>c;++c){for(var e=b[c],f=[],g=e.diff||0,h=0,i=a.length;i>h;++h){var j=a[h];e.to<=j.from&&e.diff?f.push({from:j.from+g,to:j.to+g}):e.to<=j.from||e.from>=j.to?f.push(j):(e.from>j.from&&f.push({from:j.from,to:e.from}),e.to<j.to&&f.push({from:e.to+g,to:j.to+g}))}a=f}return a}function T(a){for(var b=a.display,c={},d={},e=b.gutters.firstChild,f=0;e;e=e.nextSibling,++f)c[a.options.gutters[f]]=e.offsetLeft,d[a.options.gutters[f]]=e.offsetWidth;return{fixedPos:O(b),gutterTotalWidth:b.gutters.offsetWidth,gutterLeft:c,gutterWidth:d,wrapperWidth:b.wrapper.clientWidth}}function U(a,b,c,d,f){function l(b){var c=b.nextSibling;return e&&p&&a.display.currentWheelTarget==b?(b.style.display="none",b.lineObj=null):b.parentNode.removeChild(b),c}var g=T(a),h=a.display,i=a.options.lineNumbers;d.length||e&&a.display.currentWheelTarget||ef(h.lineDiv);var j=h.lineDiv,k=j.firstChild,m=d.shift(),n=b;for(a.doc.iter(b,c,function(b){if(m&&m.to==n&&(m=d.shift()),Ad(a.doc,b)){if(0!=b.height&&ie(b,0),b.widgets&&k.previousSibling)for(var c=0;c<b.widgets.length;++c){var e=b.widgets[c];if(e.showIfHidden){var h=k.previousSibling;if(/pre/i.test(h.nodeName)){var o=df("div",null,null,"position: relative");h.parentNode.replaceChild(o,h),o.appendChild(h),h=o}var p=h.appendChild(df("div",[e.node],"CodeMirror-linewidget"));e.handleMouseEvents||(p.ignoreEvents=!0),W(e,p,h,g)}}}else if(m&&m.from<=n&&m.to>n){for(;k.lineObj!=b;)k=l(k);i&&n>=f&&k.lineNumber&&gf(k.lineNumber,N(a.options,n)),k=k.nextSibling}else{if(b.widgets)for(var s,q=0,r=k;r&&20>q;++q,r=r.nextSibling)if(r.lineObj==b&&/div/i.test(r.nodeName)){s=r;break}var t=V(a,b,n,g,s);if(t!=s)j.insertBefore(t,k);else{for(;k!=s;)k=l(k);k=k.nextSibling}t.lineObj=b}++n});k;)k=l(k)}function V(a,b,d,e,f){var j,g=Rd(a,b),h=b.gutterMarkers,i=a.display;if(!(a.options.lineNumbers||h||b.bgClass||b.wrapClass||b.widgets))return g;if(f){f.alignable=null;for(var o,k=!0,l=0,m=null,n=f.firstChild;n;n=o)if(o=n.nextSibling,/\bCodeMirror-linewidget\b/.test(n.className)){for(var p=0,q=!0;p<b.widgets.length;++p){var r=b.widgets[p];if(r.above||(m=n,q=!1),r.node==n.firstChild){W(r,n,f,e),++l;break}}if(p==b.widgets.length){k=!1;break}}else f.removeChild(n);f.insertBefore(g,m),k&&l==b.widgets.length&&(j=f,f.className=b.wrapClass||"")}if(j||(j=df("div",null,b.wrapClass,"position: relative"),j.appendChild(g)),b.bgClass&&j.insertBefore(df("div",null,b.bgClass+" CodeMirror-linebackground"),j.firstChild),a.options.lineNumbers||h){var s=j.insertBefore(df("div",null,null,"position: absolute; left: "+(a.options.fixedGutter?e.fixedPos:-e.gutterTotalWidth)+"px"),j.firstChild);if(a.options.fixedGutter&&(j.alignable||(j.alignable=[])).push(s),!a.options.lineNumbers||h&&h["CodeMirror-linenumbers"]||(j.lineNumber=s.appendChild(df("div",N(a.options,d),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+e.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+i.lineNumInnerWidth+"px"))),h)for(var t=0;t<a.options.gutters.length;++t){var u=a.options.gutters[t],v=h.hasOwnProperty(u)&&h[u];v&&s.appendChild(df("div",[v],"CodeMirror-gutter-elt","left: "+e.gutterLeft[u]+"px; width: "+e.gutterWidth[u]+"px"))}}if(c&&(j.style.zIndex=2),b.widgets&&j!=f)for(var p=0,w=b.widgets;p<w.length;++p){var r=w[p],x=df("div",[r.node],"CodeMirror-linewidget");r.handleMouseEvents||(x.ignoreEvents=!0),W(r,x,j,e),r.above?j.insertBefore(x,a.options.lineNumbers&&0!=b.height?s:g):j.appendChild(x),Ke(r,"redraw")}return j}function W(a,b,c,d){if(a.noHScroll){(c.alignable||(c.alignable=[])).push(b);var e=d.wrapperWidth;b.style.left=d.fixedPos+"px",a.coverGutter||(e-=d.gutterTotalWidth,b.style.paddingLeft=d.gutterTotalWidth+"px"),b.style.width=e+"px"}a.coverGutter&&(b.style.zIndex=5,b.style.position="relative",a.noHScroll||(b.style.marginLeft=-d.gutterTotalWidth+"px"))}function X(a){var b=a.display,c=xc(a.doc.sel.from,a.doc.sel.to);if(c||a.options.showCursorWhenSelecting?Y(a):b.cursor.style.display=b.otherCursor.style.display="none",c?b.selectionDiv.style.display="none":Z(a),a.options.moveInputWithCursor){var d=sb(a,a.doc.sel.head,"div"),e=hf(b.wrapper),f=hf(b.lineDiv);b.inputDiv.style.top=Math.max(0,Math.min(b.wrapper.clientHeight-10,d.top+f.top-e.top))+"px",b.inputDiv.style.left=Math.max(0,Math.min(b.wrapper.clientWidth-10,d.left+f.left-e.left))+"px"}}function Y(a){var b=a.display,c=sb(a,a.doc.sel.head,"div");b.cursor.style.left=c.left+"px",b.cursor.style.top=c.top+"px",b.cursor.style.height=Math.max(0,c.bottom-c.top)*a.options.cursorHeight+"px",b.cursor.style.display="",c.other?(b.otherCursor.style.display="",b.otherCursor.style.left=c.other.left+"px",b.otherCursor.style.top=c.other.top+"px",b.otherCursor.style.height=.85*(c.other.bottom-c.other.top)+"px"):b.otherCursor.style.display="none"}function Z(a){function h(a,b,c,d){0>b&&(b=0),e.appendChild(df("div",null,"CodeMirror-selected","position: absolute; left: "+a+"px; top: "+b+"px; width: "+(null==c?f-a:c)+"px; height: "+(d-b)+"px"))}function i(b,d,e){function m(c,d){return rb(a,wc(b,c),"div",i,d)}var k,l,i=fe(c,b),j=i.text.length;return tf(me(i),d||0,null==e?j:e,function(a,b,c){var n,o,p,i=m(a,"left");if(a==b)n=i,o=p=i.left;else{if(n=m(b-1,"right"),"rtl"==c){var q=i;i=n,n=q}o=i.left,p=n.right}null==d&&0==a&&(o=g),n.top-i.top>3&&(h(o,i.top,null,i.bottom),o=g,i.bottom<n.top&&h(o,i.bottom,null,n.top)),null==e&&b==j&&(p=f),(!k||i.top<k.top||i.top==k.top&&i.left<k.left)&&(k=i),(!l||n.bottom>l.bottom||n.bottom==l.bottom&&n.right>l.right)&&(l=n),g+1>o&&(o=g),h(o,n.top,p-o,n.bottom)}),{start:k,end:l}}var b=a.display,c=a.doc,d=a.doc.sel,e=document.createDocumentFragment(),f=b.lineSpace.offsetWidth,g=fb(a.display);if(d.from.line==d.to.line)i(d.from.line,d.from.ch,d.to.ch);else{var j=fe(c,d.from.line),k=fe(c,d.to.line),l=zd(c,j)==zd(c,k),m=i(d.from.line,d.from.ch,l?j.text.length:null).end,n=i(d.to.line,l?0:null,d.to.ch).start;l&&(m.top<n.top-2?(h(m.right,m.top,null,m.bottom),h(g,n.top,n.left,n.bottom)):h(m.right,m.top,n.left-m.right,m.bottom)),m.bottom<n.top&&h(g,m.bottom,null,n.top)}ff(b.selectionDiv,e),b.selectionDiv.style.display=""}function $(a){if(a.state.focused){var b=a.display;clearInterval(b.blinker);var c=!0;b.cursor.style.visibility=b.otherCursor.style.visibility="",b.blinker=setInterval(function(){b.cursor.style.visibility=b.otherCursor.style.visibility=(c=!c)?"":"hidden"},a.options.cursorBlinkRate)}}function _(a,b){a.doc.mode.startState&&a.doc.frontier<a.display.showingTo&&a.state.highlight.set(b,$e(ab,a))}function ab(a){var b=a.doc;if(b.frontier<b.first&&(b.frontier=b.first),!(b.frontier>=a.display.showingTo)){var f,c=+new Date+a.options.workTime,d=bd(b.mode,cb(a,b.frontier)),e=[];b.iter(b.frontier,Math.min(b.first+b.size,a.display.showingTo+500),function(g){if(b.frontier>=a.display.showingFrom){var h=g.styles;g.styles=Md(a,g,d);for(var i=!h||h.length!=g.styles.length,j=0;!i&&j<h.length;++j)i=h[j]!=g.styles[j];i&&(f&&f.end==b.frontier?f.end++:e.push(f={start:b.frontier,end:b.frontier+1})),g.stateAfter=bd(b.mode,d)}else Od(a,g,d),g.stateAfter=0==b.frontier%5?bd(b.mode,d):null;return++b.frontier,+new Date>c?(_(a,a.options.workDelay),!0):void 0}),e.length&&Cb(a,function(){for(var a=0;a<e.length;++a)Fb(this,e[a].start,e[a].end)})()}}function bb(a,b,c){for(var d,e,f=a.doc,g=b,h=b-100;g>h;--g){if(g<=f.first)return f.first;var i=fe(f,g-1);if(i.stateAfter&&(!c||g<=f.frontier))return g;var j=Re(i.text,null,a.options.tabSize);(null==e||d>j)&&(e=g-1,d=j)}return e}function cb(a,b,c){var d=a.doc,e=a.display;if(!d.mode.startState)return!0;var f=bb(a,b,c),g=f>d.first&&fe(d,f-1).stateAfter;return g=g?bd(d.mode,g):cd(d.mode),d.iter(f,b,function(c){Od(a,c,g);var h=f==b-1||0==f%5||f>=e.showingFrom&&f<e.showingTo;c.stateAfter=h?bd(d.mode,g):null,++f}),g}function db(a){return a.lineSpace.offsetTop}function eb(a){return a.mover.offsetHeight-a.lineSpace.offsetHeight}function fb(a){var b=ff(a.measure,df("pre",null,null,"text-align: left")).appendChild(df("span","x"));return b.offsetLeft}function gb(a,b,c,d,e){var f=-1;d=d||jb(a,b);for(var g=c;;g+=f){var h=d[g];if(h)break;0>f&&0==g&&(f=1)}var i=(c>g||"right"==e)&&null!=h.topRight;return{left:c>g?h.right:h.left,right:g>c?h.left:h.right,top:i?h.topRight:h.top,bottom:i?h.bottomRight:h.bottom}}function hb(a,b){for(var c=a.display.measureLineCache,d=0;d<c.length;++d){var e=c[d];if(e.text==b.text&&e.markedSpans==b.markedSpans&&a.display.scroller.clientWidth==e.width&&e.classes==b.textClass+"|"+b.bgClass+"|"+b.wrapClass)return e}}function ib(a,b){var c=hb(a,b);c&&(c.text=c.measure=c.markedSpans=null)}function jb(a,b){var c=hb(a,b);if(c)return c.measure;var d=kb(a,b),e=a.display.measureLineCache,f={text:b.text,width:a.display.scroller.clientWidth,markedSpans:b.markedSpans,measure:d,classes:b.textClass+"|"+b.bgClass+"|"+b.wrapClass};return 16==e.length?e[++a.display.measureLineCachePos%16]=f:e.push(f),d}function kb(a,e){function t(a,b){b>s&&(b=s),0>a&&(a=0);for(var c=0;c<q.length;c+=2){var d=q[c],e=q[c+1];if(!(d>b||a>e)&&(a>=d&&e>=b||d>=a&&b>=e||Math.min(b,e)-Math.max(a,d)>=b-a>>1))return q[c]=Math.min(a,d),q[c+1]=Math.max(b,e),c}return q.push(a,b),c}var f=a.display,g=Ze(e.text.length),h=Rd(a,e,g);if(b&&!c&&!a.options.lineWrapping&&h.childNodes.length>100){for(var i=document.createDocumentFragment(),j=10,k=h.childNodes.length,l=0,m=Math.ceil(k/j);m>l;++l){for(var n=df("div",null,null,"display: inline-block"),o=0;j>o&&k;++o)n.appendChild(h.firstChild),--k;i.appendChild(n)}h.appendChild(i)}ff(f.measure,h);var p=hf(f.lineDiv),q=[],r=Ze(e.text.length),s=h.offsetHeight;d&&f.measure.first!=h&&ff(f.measure,h);for(var u,l=0;l<g.length;++l)if(u=g[l]){var v,w=u;if(/\bCodeMirror-widget\b/.test(u.className)&&u.getClientRects){1==u.firstChild.nodeType&&(w=u.firstChild);var x=w.getClientRects(),y=x[0],z=x[x.length-1];if(x.length>1){var A=t(y.top-p.top,y.bottom-p.top),B=t(z.top-p.top,z.bottom-p.top);r[l]={left:y.left-p.left,right:z.right-p.left,top:A,topRight:B};continue}}v=hf(w);var C=t(v.top-p.top,v.bottom-p.top),D=v.right;u.measureRight&&(D=hf(u.measureRight).left),r[l]={left:v.left-p.left,right:D-p.left,top:C}}for(var u,l=0;l<r.length;++l)if(u=r[l]){var E=u.top,F=u.topRight;u.top=q[E],u.bottom=q[E+1],null!=F&&(u.topRight=q[F],u.bottomRight=q[F+1])}return r}function lb(a,b){var c=!1;if(b.markedSpans)for(var d=0;d<b.markedSpans;++d){var e=b.markedSpans[d];!e.collapsed||null!=e.to&&e.to!=b.text.length||(c=!0)}var f=!c&&hb(a,b);if(f)return gb(a,b,b.text.length,f.measure,"right").right;var g=Rd(a,b),h=g.appendChild(of(a.display.measure));return ff(a.display.measure,g),hf(h).right-hf(a.display.lineDiv).left}function mb(a){a.display.measureLineCache.length=a.display.measureLineCachePos=0,a.display.cachedCharWidth=a.display.cachedTextHeight=null,a.options.lineWrapping||(a.display.maxLineChanged=!0),a.display.lineNumChars=null}function nb(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function ob(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function pb(a,b,c,d){if(b.widgets)for(var e=0;e<b.widgets.length;++e)if(b.widgets[e].above){var f=Gd(b.widgets[e]);c.top+=f,c.bottom+=f}if("line"==d)return c;d||(d="local");var g=le(a,b);if("local"==d?g+=db(a.display):g-=a.display.viewOffset,"page"==d||"window"==d){var h=hf(a.display.lineSpace);g+=h.top+("window"==d?0:ob());var i=h.left+("window"==d?0:nb());c.left+=i,c.right+=i}return c.top+=g,c.bottom+=g,c}function qb(a,b,c){if("div"==c)return b;var d=b.left,e=b.top;if("page"==c)d-=nb(),e-=ob();else if("local"==c||!c){var f=hf(a.display.sizer);d+=f.left,e+=f.top}var g=hf(a.display.lineSpace);return{left:d-g.left,top:e-g.top}}function rb(a,b,c,d,e){return d||(d=fe(a.doc,b.line)),pb(a,d,gb(a,d,b.ch,null,e),c)}function sb(a,b,c,d,e){function f(b,f){var g=gb(a,d,b,e,f?"right":"left");return f?g.left=g.right:g.right=g.left,pb(a,d,g,c)}function g(a,b){var c=h[b],d=c.level%2;return a==uf(c)&&b&&c.level<h[b-1].level?(c=h[--b],a=vf(c)-(c.level%2?0:1),d=!0):a==vf(c)&&b<h.length-1&&c.level<h[b+1].level&&(c=h[++b],a=uf(c)-c.level%2,d=!1),d&&a==c.to&&a>c.from?f(a-1):f(a,d)}d=d||fe(a.doc,b.line),e||(e=jb(a,d));var h=me(d),i=b.ch;if(!h)return f(i);var j=Cf(h,i),k=g(i,j);return null!=Bf&&(k.other=g(i,Bf)),k}function tb(a,b,c,d){var e=new wc(a,b);return e.xRel=d,c&&(e.outside=!0),e}function ub(a,b,c){var d=a.doc;if(c+=a.display.viewOffset,0>c)return tb(d.first,0,!0,-1);var e=ke(d,c),f=d.first+d.size-1;if(e>f)return tb(d.first+d.size-1,fe(d,f).text.length,!0,1);for(0>b&&(b=0);;){var g=fe(d,e),h=vb(a,g,e,b,c),i=yd(g),j=i&&i.find();if(!i||!(h.ch>j.from.ch||h.ch==j.from.ch&&h.xRel>0))return h;e=j.to.line}}function vb(a,b,c,d,e){function j(d){var e=sb(a,wc(c,d),"line",b,i);return g=!0,f>e.bottom?e.left-h:f<e.top?e.left+h:(g=!1,e.left)}var f=e-le(a,b),g=!1,h=2*a.display.wrapper.clientWidth,i=jb(a,b),k=me(b),l=b.text.length,m=wf(b),n=xf(b),o=j(m),p=g,q=j(n),r=g;if(d>q)return tb(c,n,r,1);for(;;){if(k?n==m||n==Ef(b,m,1):1>=n-m){for(var s=o>d||q-d>=d-o?m:n,t=d-(s==m?o:q);cf.test(b.text.charAt(s));)++s;var u=tb(c,s,s==m?p:r,0>t?-1:t?1:0);return u}var v=Math.ceil(l/2),w=m+v;if(k){w=m;for(var x=0;v>x;++x)w=Ef(b,w,1)}var y=j(w);y>d?(n=w,q=y,(r=g)&&(q+=1e3),l=v):(m=w,o=y,p=g,l-=v)}}function xb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==wb){wb=df("pre");for(var b=0;49>b;++b)wb.appendChild(document.createTextNode("x")),wb.appendChild(df("br"));wb.appendChild(document.createTextNode("x"))}ff(a.measure,wb);var c=wb.offsetHeight/50;return c>3&&(a.cachedTextHeight=c),ef(a.measure),c||1}function yb(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=df("span","x"),c=df("pre",[b]);ff(a.measure,c);var d=b.offsetWidth;return d>2&&(a.cachedCharWidth=d),d||10}function Ab(a){a.curOp={changes:[],updateInput:null,userSelChange:null,textChanged:null,selectionChanged:!1,cursorActivity:!1,updateMaxLine:!1,updateScrollPos:!1,id:++zb},Je++||(Ie=[])}function Bb(a){var b=a.curOp,c=a.doc,d=a.display;if(a.curOp=null,b.updateMaxLine&&H(a),d.maxLineChanged&&!a.options.lineWrapping&&d.maxLine){var e=lb(a,d.maxLine);d.sizer.style.minWidth=Math.max(0,e+3+Oe)+"px",d.maxLineChanged=!1;var f=Math.max(0,d.sizer.offsetLeft+d.sizer.offsetWidth-d.scroller.clientWidth);f<c.scrollLeft&&!b.updateScrollPos&&Xb(a,Math.min(d.scroller.scrollLeft,f),!0)}var g,h;if(b.updateScrollPos)g=b.updateScrollPos;else if(b.selectionChanged&&d.scroller.clientHeight){var i=sb(a,c.sel.head);g=Mc(a,i.left,i.top,i.left,i.bottom)}(b.changes.length||g&&null!=g.scrollTop)&&(h=P(a,b.changes,g&&g.scrollTop),a.display.scroller.offsetHeight&&(a.doc.scrollTop=a.display.scroller.scrollTop)),!h&&b.selectionChanged&&X(a),b.updateScrollPos?(d.scroller.scrollTop=d.scrollbarV.scrollTop=c.scrollTop=g.scrollTop,d.scroller.scrollLeft=d.scrollbarH.scrollLeft=c.scrollLeft=g.scrollLeft,L(a),b.scrollToPos&&Kc(a,Bc(a.doc,b.scrollToPos),b.scrollToPosMargin)):g&&Jc(a),b.selectionChanged&&$(a),a.state.focused&&b.updateInput&&Jb(a,b.userSelChange);var j=b.maybeHiddenMarkers,k=b.maybeUnhiddenMarkers;if(j)for(var l=0;l<j.length;++l)j[l].lines.length||He(j[l],"hide");if(k)for(var l=0;l<k.length;++l)k[l].lines.length&&He(k[l],"unhide");var m;if(--Je||(m=Ie,Ie=null),b.textChanged&&He(a,"change",a,b.textChanged),b.cursorActivity&&He(a,"cursorActivity",a),m)for(var l=0;l<m.length;++l)m[l]()}function Cb(a,b){return function(){var c=a||this,d=!c.curOp;d&&Ab(c);try{var e=b.apply(c,arguments)}finally{d&&Bb(c)}return e}}function Db(a){return function(){var c,b=this.cm&&!this.cm.curOp;b&&Ab(this.cm);try{c=a.apply(this,arguments)}finally{b&&Bb(this.cm)}return c}}function Eb(a,b){var d,c=!a.curOp;c&&Ab(a);try{d=b()}finally{c&&Bb(a)}return d}function Fb(a,b,c,d){null==b&&(b=a.doc.first),null==c&&(c=a.doc.first+a.doc.size),a.curOp.changes.push({from:b,to:c,diff:d})}function Gb(a){a.display.pollingFast||a.display.poll.set(a.options.pollInterval,function(){Ib(a),a.state.focused&&Gb(a)})}function Hb(a){function c(){var d=Ib(a);d||b?(a.display.pollingFast=!1,Gb(a)):(b=!0,a.display.poll.set(60,c))}var b=!1;a.display.pollingFast=!0,a.display.poll.set(20,c)}function Ib(a){var c=a.display.input,e=a.display.prevInput,f=a.doc,g=f.sel;if(!a.state.focused||qf(c)||Lb(a)||a.state.disableInput)return!1;var h=c.value;if(h==e&&xc(g.from,g.to))return!1;if(b&&!d&&a.display.inputHasSelection===h)return Jb(a,!0),!1;var i=!a.curOp;i&&Ab(a),g.shift=!1;for(var j=0,k=Math.min(e.length,h.length);k>j&&e.charCodeAt(j)==h.charCodeAt(j);)++j;var l=g.from,m=g.to;j<e.length?l=wc(l.line,l.ch-(e.length-j)):a.state.overwrite&&xc(l,m)&&!a.state.pasteIncoming&&(m=wc(m.line,Math.min(fe(f,m.line).text.length,m.ch+(h.length-j))));var n=a.curOp.updateInput,o={from:l,to:m,text:pf(h.slice(j)),origin:a.state.pasteIncoming?"paste":"+input"};return pc(a.doc,o,"end"),a.curOp.updateInput=n,Ke(a,"inputRead",a,o),h.length>1e3||h.indexOf("\n")>-1?c.value=a.display.prevInput="":a.display.prevInput=h,i&&Bb(a),a.state.pasteIncoming=!1,!0}function Jb(a,c){var e,f,g=a.doc;if(xc(g.sel.from,g.sel.to))c&&(a.display.prevInput=a.display.input.value="",b&&!d&&(a.display.inputHasSelection=null));else{a.display.prevInput="",e=rf&&(g.sel.to.line-g.sel.from.line>100||(f=a.getSelection()).length>1e3);var h=e?"-":f||a.getSelection();a.display.input.value=h,a.state.focused&&Ve(a.display.input),b&&!d&&(a.display.inputHasSelection=h)}a.display.inaccurateSelection=e}function Kb(a){"nocursor"==a.options.readOnly||o&&document.activeElement==a.display.input||a.display.input.focus()}function Lb(a){return a.options.readOnly||a.doc.cantEdit}function Mb(a){function d(){a.state.focused&&setTimeout($e(Kb,a),0)}function f(){null==e&&(e=setTimeout(function(){e=null,c.cachedCharWidth=c.cachedTextHeight=lf=null,mb(a),Eb(a,$e(Fb,a))},100))}function g(){for(var a=c.wrapper.parentNode;a&&a!=document.body;a=a.parentNode);a?setTimeout(g,5e3):Ge(window,"resize",f)}function h(b){Le(a,b)||a.options.onDragEvent&&a.options.onDragEvent(a,ye(b))||Ce(b)}function i(){c.inaccurateSelection&&(c.prevInput="",c.inaccurateSelection=!1,c.input.value=a.getSelection(),Ve(c.input))}var c=a.display;Fe(c.scroller,"mousedown",Cb(a,Rb)),b?Fe(c.scroller,"dblclick",Cb(a,function(b){if(!Le(a,b)){var c=Ob(a,b);if(c&&!Sb(a,b)&&!Nb(a.display,b)){ze(b);var d=Tc(fe(a.doc,c.line).text,c);Ec(a.doc,d.from,d.to)}}})):Fe(c.scroller,"dblclick",function(b){Le(a,b)||ze(b)}),Fe(c.lineSpace,"selectstart",function(a){Nb(c,a)||ze(a)}),t||Fe(c.scroller,"contextmenu",function(b){kc(a,b)}),Fe(c.scroller,"scroll",function(){c.scroller.clientHeight&&(Wb(a,c.scroller.scrollTop),Xb(a,c.scroller.scrollLeft,!0),He(a,"scroll",a))}),Fe(c.scrollbarV,"scroll",function(){c.scroller.clientHeight&&Wb(a,c.scrollbarV.scrollTop)}),Fe(c.scrollbarH,"scroll",function(){c.scroller.clientHeight&&Xb(a,c.scrollbarH.scrollLeft)}),Fe(c.scroller,"mousewheel",function(b){$b(a,b)}),Fe(c.scroller,"DOMMouseScroll",function(b){$b(a,b)}),Fe(c.scrollbarH,"mousedown",d),Fe(c.scrollbarV,"mousedown",d),Fe(c.wrapper,"scroll",function(){c.wrapper.scrollTop=c.wrapper.scrollLeft=0});var e;Fe(window,"resize",f),setTimeout(g,5e3),Fe(c.input,"keyup",Cb(a,function(b){Le(a,b)||a.options.onKeyEvent&&a.options.onKeyEvent(a,ye(b))||16==b.keyCode&&(a.doc.sel.shift=!1)})),Fe(c.input,"input",$e(Hb,a)),Fe(c.input,"keydown",Cb(a,fc)),Fe(c.input,"keypress",Cb(a,gc)),Fe(c.input,"focus",$e(hc,a)),Fe(c.input,"blur",$e(ic,a)),a.options.dragDrop&&(Fe(c.scroller,"dragstart",function(b){Vb(a,b)}),Fe(c.scroller,"dragenter",h),Fe(c.scroller,"dragover",h),Fe(c.scroller,"drop",Cb(a,Ub))),Fe(c.scroller,"paste",function(b){Nb(c,b)||(Kb(a),Hb(a))}),Fe(c.input,"paste",function(){a.state.pasteIncoming=!0,Hb(a)}),Fe(c.input,"cut",i),Fe(c.input,"copy",i),j&&Fe(c.sizer,"mouseup",function(){document.activeElement==c.input&&c.input.blur(),Kb(a)})}function Nb(a,b){for(var c=De(b);c!=a.wrapper;c=c.parentNode)if(!c||c.ignoreEvents||c.parentNode==a.sizer&&c!=a.mover)return!0}function Ob(a,b,c){var d=a.display;if(!c){var e=De(b);if(e==d.scrollbarH||e==d.scrollbarH.firstChild||e==d.scrollbarV||e==d.scrollbarV.firstChild||e==d.scrollbarFiller||e==d.gutterFiller)return null}var f,g,h=hf(d.lineSpace);try{f=b.clientX,g=b.clientY}catch(b){return null}return ub(a,f-h.left,g-h.top)}function Rb(a){function q(a){if(!xc(p,a)){if(p=a,"single"==j)return Ec(c.doc,Bc(f,h),a),void 0;if(n=Bc(f,n),o=Bc(f,o),"double"==j){var b=Tc(fe(f,a.line).text,a);yc(a,n)?Ec(c.doc,b.from,o):Ec(c.doc,n,b.to)}else"triple"==j&&(yc(a,n)?Ec(c.doc,o,Bc(f,wc(a.line,0))):Ec(c.doc,n,Bc(f,wc(a.line+1,0))))}}function u(a){var b=++s,e=Ob(c,a,!0);if(e)if(xc(e,l)){var h=a.clientY<r.top?-20:a.clientY>r.bottom?20:0;h&&setTimeout(Cb(c,function(){s==b&&(d.scroller.scrollTop+=h,u(a))}),50)}else{c.state.focused||hc(c),l=e,q(e);var g=K(d,f);(e.line>=g.to||e.line<g.from)&&setTimeout(Cb(c,function(){s==b&&u(a)}),150)}}function v(a){s=1/0,ze(a),Kb(c),Ge(document,"mousemove",w),Ge(document,"mouseup",x)}if(!Le(this,a)){var c=this,d=c.display,f=c.doc,g=f.sel;if(g.shift=a.shiftKey,Nb(d,a))return e||(d.scroller.draggable=!1,setTimeout(function(){d.scroller.draggable=!0},100)),void 0;if(!Sb(c,a)){var h=Ob(c,a);switch(Ee(a)){case 3:return t&&kc.call(c,c,a),void 0;case 2:return h&&Ec(c.doc,h),setTimeout($e(Kb,c),20),ze(a),void 0}if(!h)return De(a)==d.scroller&&ze(a),void 0;c.state.focused||hc(c);var i=+new Date,j="single";if(Qb&&Qb.time>i-400&&xc(Qb.pos,h))j="triple",ze(a),setTimeout($e(Kb,c),20),Uc(c,h.line);else if(Pb&&Pb.time>i-400&&xc(Pb.pos,h)){j="double",Qb={time:i,pos:h},ze(a);var k=Tc(fe(f,h.line).text,h);Ec(c.doc,k.from,k.to)}else Pb={time:i,pos:h};var l=h;if(c.options.dragDrop&&jf&&!Lb(c)&&!xc(g.from,g.to)&&!yc(h,g.from)&&!yc(g.to,h)&&"single"==j){var m=Cb(c,function(b){e&&(d.scroller.draggable=!1),c.state.draggingText=!1,Ge(document,"mouseup",m),Ge(d.scroller,"drop",m),Math.abs(a.clientX-b.clientX)+Math.abs(a.clientY-b.clientY)<10&&(ze(b),Ec(c.doc,h),Kb(c))
9
});return e&&(d.scroller.draggable=!0),c.state.draggingText=m,d.scroller.dragDrop&&d.scroller.dragDrop(),Fe(document,"mouseup",m),Fe(d.scroller,"drop",m),void 0}ze(a),"single"==j&&Ec(c.doc,Bc(f,h));var n=g.from,o=g.to,p=h,r=hf(d.wrapper),s=0,w=Cb(c,function(a){b||Ee(a)?u(a):v(a)}),x=Cb(c,v);Fe(document,"mousemove",w),Fe(document,"mouseup",x)}}}function Sb(a,b){var c=a.display;try{var d=b.clientX,e=b.clientY}catch(b){return!1}if(d>=Math.floor(hf(c.gutters).right))return!1;if(ze(b),!Ne(a,"gutterClick"))return!0;var f=hf(c.lineDiv);if(e>f.bottom)return!0;e-=f.top-c.viewOffset;for(var g=0;g<a.options.gutters.length;++g){var h=c.gutters.childNodes[g];if(h&&hf(h).right>=d){var i=ke(a.doc,e),j=a.options.gutters[g];Ke(a,"gutterClick",a,i,j,b);break}}return!0}function Ub(a){var c=this;if(!(Le(c,a)||Nb(c.display,a)||c.options.onDragEvent&&c.options.onDragEvent(c,ye(a)))){ze(a),b&&(Tb=+new Date);var d=Ob(c,a,!0),e=a.dataTransfer.files;if(d&&!Lb(c))if(e&&e.length&&window.FileReader&&window.File)for(var f=e.length,g=Array(f),h=0,i=function(a,b){var e=new FileReader;e.onload=function(){g[b]=e.result,++h==f&&(d=Bc(c.doc,d),pc(c.doc,{from:d,to:d,text:pf(g.join("\n")),origin:"paste"},"around"))},e.readAsText(a)},j=0;f>j;++j)i(e[j],j);else{if(c.state.draggingText&&!yc(d,c.doc.sel.from)&&!yc(c.doc.sel.to,d))return c.state.draggingText(a),setTimeout($e(Kb,c),20),void 0;try{var g=a.dataTransfer.getData("Text");if(g){var k=c.doc.sel.from,l=c.doc.sel.to;Gc(c.doc,d,d),c.state.draggingText&&vc(c.doc,"",k,l,"paste"),c.replaceSelection(g,null,"paste"),Kb(c),hc(c)}}catch(a){}}}}function Vb(a,c){if(b&&(!a.state.draggingText||+new Date-Tb<100))return Ce(c),void 0;if(!Le(a,c)&&!Nb(a.display,c)){var d=a.getSelection();if(c.dataTransfer.setData("Text",d),c.dataTransfer.setDragImage&&!i){var e=df("img",null,null,"position: fixed; left: 0; top: 0;");h&&(e.width=e.height=1,a.display.wrapper.appendChild(e),e._top=e.offsetTop),c.dataTransfer.setDragImage(e,0,0),h&&e.parentNode.removeChild(e)}}}function Wb(b,c){Math.abs(b.doc.scrollTop-c)<2||(b.doc.scrollTop=c,a||P(b,[],c),b.display.scroller.scrollTop!=c&&(b.display.scroller.scrollTop=c),b.display.scrollbarV.scrollTop!=c&&(b.display.scrollbarV.scrollTop=c),a&&P(b,[]),_(b,100))}function Xb(a,b,c){(c?b==a.doc.scrollLeft:Math.abs(a.doc.scrollLeft-b)<2)||(b=Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth),a.doc.scrollLeft=b,L(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbarH.scrollLeft!=b&&(a.display.scrollbarH.scrollLeft=b))}function $b(b,c){var d=c.wheelDeltaX,f=c.wheelDeltaY;null==d&&c.detail&&c.axis==c.HORIZONTAL_AXIS&&(d=c.detail),null==f&&c.detail&&c.axis==c.VERTICAL_AXIS?f=c.detail:null==f&&(f=c.wheelDelta);var g=b.display,i=g.scroller;if(d&&i.scrollWidth>i.clientWidth||f&&i.scrollHeight>i.clientHeight){if(f&&p&&e)for(var j=c.target;j!=i;j=j.parentNode)if(j.lineObj){b.display.currentWheelTarget=j;break}if(d&&!a&&!h&&null!=Zb)return f&&Wb(b,Math.max(0,Math.min(i.scrollTop+f*Zb,i.scrollHeight-i.clientHeight))),Xb(b,Math.max(0,Math.min(i.scrollLeft+d*Zb,i.scrollWidth-i.clientWidth))),ze(c),g.wheelStartX=null,void 0;if(f&&null!=Zb){var k=f*Zb,l=b.doc.scrollTop,m=l+g.wrapper.clientHeight;0>k?l=Math.max(0,l+k-50):m=Math.min(b.doc.height,m+k+50),P(b,[],{top:l,bottom:m})}20>Yb&&(null==g.wheelStartX?(g.wheelStartX=i.scrollLeft,g.wheelStartY=i.scrollTop,g.wheelDX=d,g.wheelDY=f,setTimeout(function(){if(null!=g.wheelStartX){var a=i.scrollLeft-g.wheelStartX,b=i.scrollTop-g.wheelStartY,c=b&&g.wheelDY&&b/g.wheelDY||a&&g.wheelDX&&a/g.wheelDX;g.wheelStartX=g.wheelStartY=null,c&&(Zb=(Zb*Yb+c)/(Yb+1),++Yb)}},200)):(g.wheelDX+=d,g.wheelDY+=f))}}function _b(a,b,c){if("string"==typeof b&&(b=dd[b],!b))return!1;a.display.pollingFast&&Ib(a)&&(a.display.pollingFast=!1);var d=a.doc,e=d.sel.shift,f=!1;try{Lb(a)&&(a.state.suppressEdits=!0),c&&(d.sel.shift=!1),f=b(a)!=Pe}finally{d.sel.shift=e,a.state.suppressEdits=!1}return f}function ac(a){var b=a.state.keyMaps.slice(0);return a.options.extraKeys&&b.push(a.options.extraKeys),b.push(a.options.keyMap),b}function cc(a,b){var c=fd(a.options.keyMap),e=c.auto;clearTimeout(bc),e&&!hd(b)&&(bc=setTimeout(function(){fd(a.options.keyMap)==c&&(a.options.keyMap=e.call?e.call(null,a):e,C(a))},50));var f=id(b,!0),g=!1;if(!f)return!1;var h=ac(a);return g=b.shiftKey?gd("Shift-"+f,h,function(b){return _b(a,b,!0)})||gd(f,h,function(b){return("string"==typeof b?/^go[A-Z]/.test(b):b.motion)?_b(a,b):void 0}):gd(f,h,function(b){return _b(a,b)}),g&&(ze(b),$(a),d&&(b.oldKeyCode=b.keyCode,b.keyCode=0),Ke(a,"keyHandled",a,f,b)),g}function dc(a,b,c){var d=gd("'"+c+"'",ac(a),function(b){return _b(a,b,!0)});return d&&(ze(b),$(a),Ke(a,"keyHandled",a,"'"+c+"'",b)),d}function fc(a){var c=this;if(c.state.focused||hc(c),b&&27==a.keyCode&&(a.returnValue=!1),!(Le(c,a)||c.options.onKeyEvent&&c.options.onKeyEvent(c,ye(a)))){var d=a.keyCode;c.doc.sel.shift=16==d||a.shiftKey;var e=cc(c,a);h&&(ec=e?d:null,!e&&88==d&&!rf&&(p?a.metaKey:a.ctrlKey)&&c.replaceSelection(""))}}function gc(a){var c=this;if(!(Le(c,a)||c.options.onKeyEvent&&c.options.onKeyEvent(c,ye(a)))){var e=a.keyCode,f=a.charCode;if(h&&e==ec)return ec=null,ze(a),void 0;if(!(h&&(!a.which||a.which<10)||j)||!cc(c,a)){var g=String.fromCharCode(null==f?e:f);this.options.electricChars&&this.doc.mode.electricChars&&this.options.smartIndent&&!Lb(this)&&this.doc.mode.electricChars.indexOf(g)>-1&&setTimeout(Cb(c,function(){Pc(c,c.doc.sel.to.line,"smart")}),75),dc(c,a,g)||(b&&!d&&(c.display.inputHasSelection=null),Hb(c))}}}function hc(a){"nocursor"!=a.options.readOnly&&(a.state.focused||(He(a,"focus",a),a.state.focused=!0,-1==a.display.wrapper.className.search(/\bCodeMirror-focused\b/)&&(a.display.wrapper.className+=" CodeMirror-focused"),Jb(a,!0)),Gb(a),$(a))}function ic(a){a.state.focused&&(He(a,"blur",a),a.state.focused=!1,a.display.wrapper.className=a.display.wrapper.className.replace(" CodeMirror-focused","")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused||(a.doc.sel.shift=!1)},150)}function kc(a,c){function k(){if(null!=e.input.selectionStart){var a=e.input.value=" "+(xc(f.from,f.to)?"":e.input.value);e.prevInput=" ",e.input.selectionStart=1,e.input.selectionEnd=a.length}}function l(){if(e.inputDiv.style.position="relative",e.input.style.cssText=j,d&&(e.scrollbarV.scrollTop=e.scroller.scrollTop=i),Gb(a),null!=e.input.selectionStart){(!b||d)&&k(),clearTimeout(jc);var c=0,f=function(){" "==e.prevInput&&0==e.input.selectionStart?Cb(a,dd.selectAll)(a):c++<10?jc=setTimeout(f,500):Jb(a)};jc=setTimeout(f,200)}}var e=a.display,f=a.doc.sel;if(!Nb(e,c)){var g=Ob(a,c),i=e.scroller.scrollTop;if(g&&!h){(xc(f.from,f.to)||yc(g,f.from)||!yc(g,f.to))&&Cb(a,Gc)(a.doc,g,g);var j=e.input.style.cssText;if(e.inputDiv.style.position="absolute",e.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(c.clientY-5)+"px; left: "+(c.clientX-5)+"px; z-index: 1000; background: white; outline: none;"+"border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);",Kb(a),Jb(a,!0),xc(f.from,f.to)&&(e.input.value=e.prevInput=" "),b&&!d&&k(),t){Ce(c);var m=function(){Ge(window,"mouseup",m),setTimeout(l,20)};Fe(window,"mouseup",m)}else setTimeout(l,50)}}}function mc(a,b,c){if(!yc(b.from,c))return Bc(a,c);var d=b.text.length-1-(b.to.line-b.from.line);if(c.line>b.to.line+d){var e=c.line-d,f=a.first+a.size-1;return e>f?wc(f,fe(a,f).text.length):Cc(c,fe(a,e).text.length)}if(c.line==b.to.line+d)return Cc(c,Ue(b.text).length+(1==b.text.length?b.from.ch:0)+fe(a,b.to.line).text.length-b.to.ch);var g=c.line-b.from.line;return Cc(c,b.text[g].length+(g?0:b.from.ch))}function nc(a,b,c){if(c&&"object"==typeof c)return{anchor:mc(a,b,c.anchor),head:mc(a,b,c.head)};if("start"==c)return{anchor:b.from,head:b.from};var d=lc(b);if("around"==c)return{anchor:b.from,head:d};if("end"==c)return{anchor:d,head:d};var e=function(a){if(yc(a,b.from))return a;if(!yc(b.to,a))return d;var c=a.line+b.text.length-(b.to.line-b.from.line)-1,e=a.ch;return a.line==b.to.line&&(e+=d.ch-b.to.ch),wc(c,e)};return{anchor:e(a.sel.anchor),head:e(a.sel.head)}}function oc(a,b,c){var d={canceled:!1,from:b.from,to:b.to,text:b.text,origin:b.origin,cancel:function(){this.canceled=!0}};return c&&(d.update=function(b,c,d,e){b&&(this.from=Bc(a,b)),c&&(this.to=Bc(a,c)),d&&(this.text=d),void 0!==e&&(this.origin=e)}),He(a,"beforeChange",a,d),a.cm&&He(a.cm,"beforeChange",a.cm,d),d.canceled?null:{from:d.from,to:d.to,text:d.text,origin:d.origin}}function pc(a,b,c,d){if(a.cm){if(!a.cm.curOp)return Cb(a.cm,pc)(a,b,c,d);if(a.cm.state.suppressEdits)return}if(!(Ne(a,"beforeChange")||a.cm&&Ne(a.cm,"beforeChange"))||(b=oc(a,b,!0))){var e=u&&!d&&vd(a,b.from,b.to);if(e){for(var f=e.length-1;f>=1;--f)qc(a,{from:e[f].from,to:e[f].to,text:[""]});e.length&&qc(a,{from:e[0].from,to:e[0].to,text:b.text},c)}else qc(a,b,c)}}function qc(a,b,c){var d=nc(a,b,c);qe(a,b,d,a.cm?a.cm.curOp.id:0/0),tc(a,b,d,td(a,b));var e=[];de(a,function(a,c){c||-1!=We(e,a.history)||(we(a.history,b),e.push(a.history)),tc(a,b,null,td(a,b))})}function rc(a,b){if(!a.cm||!a.cm.state.suppressEdits){var c=a.history,d=("undo"==b?c.done:c.undone).pop();if(d){var e={changes:[],anchorBefore:d.anchorAfter,headBefore:d.headAfter,anchorAfter:d.anchorBefore,headAfter:d.headBefore,generation:c.generation};("undo"==b?c.undone:c.done).push(e),c.generation=d.generation||++c.maxGeneration;for(var f=Ne(a,"beforeChange")||a.cm&&Ne(a.cm,"beforeChange"),g=d.changes.length-1;g>=0;--g){var h=d.changes[g];if(h.origin=b,f&&!oc(a,h,!1))return("undo"==b?c.done:c.undone).length=0,void 0;e.changes.push(pe(a,h));var i=g?nc(a,h,null):{anchor:d.anchorBefore,head:d.headBefore};tc(a,h,i,ud(a,h));var j=[];de(a,function(a,b){b||-1!=We(j,a.history)||(we(a.history,h),j.push(a.history)),tc(a,h,null,ud(a,h))})}}}}function sc(a,b){function c(a){return wc(a.line+b,a.ch)}a.first+=b,a.cm&&Fb(a.cm,a.first,a.first,b),a.sel.head=c(a.sel.head),a.sel.anchor=c(a.sel.anchor),a.sel.from=c(a.sel.from),a.sel.to=c(a.sel.to)}function tc(a,b,c,d){if(a.cm&&!a.cm.curOp)return Cb(a.cm,tc)(a,b,c,d);if(b.to.line<a.first)return sc(a,b.text.length-1-(b.to.line-b.from.line)),void 0;if(!(b.from.line>a.lastLine())){if(b.from.line<a.first){var e=b.text.length-1-(a.first-b.from.line);sc(a,e),b={from:wc(a.first,0),to:wc(b.to.line+e,b.to.ch),text:[Ue(b.text)],origin:b.origin}}var f=a.lastLine();b.to.line>f&&(b={from:b.from,to:wc(f,fe(a,f).text.length),text:[b.text[0]],origin:b.origin}),b.removed=ge(a,b.from,b.to),c||(c=nc(a,b,null)),a.cm?uc(a.cm,b,d,c):Yd(a,b,d,c)}}function uc(a,b,c,d){var e=a.doc,f=a.display,g=b.from,h=b.to,i=!1,j=g.line;a.options.lineWrapping||(j=je(zd(e,fe(e,g.line))),e.iter(j,h.line+1,function(a){return a==f.maxLine?(i=!0,!0):void 0})),yc(e.sel.head,b.from)||yc(b.to,e.sel.head)||(a.curOp.cursorActivity=!0),Yd(e,b,c,d,A(a)),a.options.lineWrapping||(e.iter(j,g.line+b.text.length,function(a){var b=G(e,a);b>f.maxLineLength&&(f.maxLine=a,f.maxLineLength=b,f.maxLineChanged=!0,i=!1)}),i&&(a.curOp.updateMaxLine=!0)),e.frontier=Math.min(e.frontier,g.line),_(a,400);var k=b.text.length-(h.line-g.line)-1;if(Fb(a,g.line,h.line+1,k),Ne(a,"change")){var l={from:g,to:h,text:b.text,removed:b.removed,origin:b.origin};if(a.curOp.textChanged){for(var m=a.curOp.textChanged;m.next;m=m.next);m.next=l}else a.curOp.textChanged=l}}function vc(a,b,c,d,e){if(d||(d=c),yc(d,c)){var f=d;d=c,c=f}"string"==typeof b&&(b=pf(b)),pc(a,{from:c,to:d,text:b,origin:e},null)}function wc(a,b){return this instanceof wc?(this.line=a,this.ch=b,void 0):new wc(a,b)}function xc(a,b){return a.line==b.line&&a.ch==b.ch}function yc(a,b){return a.line<b.line||a.line==b.line&&a.ch<b.ch}function zc(a){return wc(a.line,a.ch)}function Ac(a,b){return Math.max(a.first,Math.min(b,a.first+a.size-1))}function Bc(a,b){if(b.line<a.first)return wc(a.first,0);var c=a.first+a.size-1;return b.line>c?wc(c,fe(a,c).text.length):Cc(b,fe(a,b.line).text.length)}function Cc(a,b){var c=a.ch;return null==c||c>b?wc(a.line,b):0>c?wc(a.line,0):a}function Dc(a,b){return b>=a.first&&b<a.first+a.size}function Ec(a,b,c,d){if(a.sel.shift||a.sel.extend){var e=a.sel.anchor;if(c){var f=yc(b,e);f!=yc(c,e)?(e=b,b=c):f!=yc(b,c)&&(b=c)}Gc(a,e,b,d)}else Gc(a,b,c||b,d);a.cm&&(a.cm.curOp.userSelChange=!0)}function Fc(a,b,c){var d={anchor:b,head:c};return He(a,"beforeSelectionChange",a,d),a.cm&&He(a.cm,"beforeSelectionChange",a.cm,d),d.anchor=Bc(a,d.anchor),d.head=Bc(a,d.head),d}function Gc(a,b,c,d,e){if(!e&&Ne(a,"beforeSelectionChange")||a.cm&&Ne(a.cm,"beforeSelectionChange")){var f=Fc(a,b,c);c=f.head,b=f.anchor}var g=a.sel;if(g.goalColumn=null,(e||!xc(b,g.anchor))&&(b=Ic(a,b,d,"push"!=e)),(e||!xc(c,g.head))&&(c=Ic(a,c,d,"push"!=e)),!xc(g.anchor,b)||!xc(g.head,c)){g.anchor=b,g.head=c;var h=yc(c,b);g.from=h?c:b,g.to=h?b:c,a.cm&&(a.cm.curOp.updateInput=a.cm.curOp.selectionChanged=a.cm.curOp.cursorActivity=!0),Ke(a,"cursorActivity",a)}}function Hc(a){Gc(a.doc,a.doc.sel.from,a.doc.sel.to,null,"push")}function Ic(a,b,c,d){var e=!1,f=b,g=c||1;a.cantEdit=!1;a:for(;;){var h=fe(a,f.line);if(h.markedSpans)for(var i=0;i<h.markedSpans.length;++i){var j=h.markedSpans[i],k=j.marker;if((null==j.from||(k.inclusiveLeft?j.from<=f.ch:j.from<f.ch))&&(null==j.to||(k.inclusiveRight?j.to>=f.ch:j.to>f.ch))){if(d&&(He(k,"beforeCursorEnter"),k.explicitlyCleared)){if(h.markedSpans){--i;continue}break}if(!k.atomic)continue;var l=k.find()[0>g?"from":"to"];if(xc(l,f)&&(l.ch+=g,l.ch<0?l=l.line>a.first?Bc(a,wc(l.line-1)):null:l.ch>h.text.length&&(l=l.line<a.first+a.size-1?wc(l.line+1,0):null),!l)){if(e)return d?(a.cantEdit=!0,wc(a.first,0)):Ic(a,b,c,!0);e=!0,l=b,g=-g}f=l;continue a}}return f}}function Jc(a){var b=Kc(a,a.doc.sel.head,a.options.cursorScrollMargin);if(a.state.focused){var c=a.display,d=hf(c.sizer),e=null;if(b.top+d.top<0?e=!0:b.bottom+d.top>(window.innerHeight||document.documentElement.clientHeight)&&(e=!1),null!=e&&!m){var f="none"==c.cursor.style.display;f&&(c.cursor.style.display="",c.cursor.style.left=b.left+"px",c.cursor.style.top=b.top-c.viewOffset+"px"),c.cursor.scrollIntoView(e),f&&(c.cursor.style.display="none")}}}function Kc(a,b,c){for(null==c&&(c=0);;){var d=!1,e=sb(a,b),f=Mc(a,e.left,e.top-c,e.left,e.bottom+c),g=a.doc.scrollTop,h=a.doc.scrollLeft;if(null!=f.scrollTop&&(Wb(a,f.scrollTop),Math.abs(a.doc.scrollTop-g)>1&&(d=!0)),null!=f.scrollLeft&&(Xb(a,f.scrollLeft),Math.abs(a.doc.scrollLeft-h)>1&&(d=!0)),!d)return e}}function Lc(a,b,c,d,e){var f=Mc(a,b,c,d,e);null!=f.scrollTop&&Wb(a,f.scrollTop),null!=f.scrollLeft&&Xb(a,f.scrollLeft)}function Mc(a,b,c,d,e){var f=a.display,g=xb(a.display);0>c&&(c=0);var h=f.scroller.clientHeight-Oe,i=f.scroller.scrollTop,j={},k=a.doc.height+eb(f),l=g>c,m=e>k-g;if(i>c)j.scrollTop=l?0:c;else if(e>i+h){var n=Math.min(c,(m?k:e)-h);n!=i&&(j.scrollTop=n)}var o=f.scroller.clientWidth-Oe,p=f.scroller.scrollLeft;b+=f.gutters.offsetWidth,d+=f.gutters.offsetWidth;var q=f.gutters.offsetWidth,r=q+10>b;return p+q>b||r?(r&&(b=0),j.scrollLeft=Math.max(0,b-10-q)):d>o+p-3&&(j.scrollLeft=d+10-o),j}function Nc(a,b,c){a.curOp.updateScrollPos={scrollLeft:null==b?a.doc.scrollLeft:b,scrollTop:null==c?a.doc.scrollTop:c}}function Oc(a,b,c){var d=a.curOp.updateScrollPos||(a.curOp.updateScrollPos={scrollLeft:a.doc.scrollLeft,scrollTop:a.doc.scrollTop}),e=a.display.scroller;d.scrollTop=Math.max(0,Math.min(e.scrollHeight-e.clientHeight,d.scrollTop+c)),d.scrollLeft=Math.max(0,Math.min(e.scrollWidth-e.clientWidth,d.scrollLeft+b))}function Pc(a,b,c,d){var e=a.doc;if(null==c&&(c="add"),"smart"==c)if(a.doc.mode.indent)var f=cb(a,b);else c="prev";var k,g=a.options.tabSize,h=fe(e,b),i=Re(h.text,null,g),j=h.text.match(/^\s*/)[0];if("smart"==c&&(k=a.doc.mode.indent(f,h.text.slice(j.length),h.text),k==Pe)){if(!d)return;c="prev"}"prev"==c?k=b>e.first?Re(fe(e,b-1).text,null,g):0:"add"==c?k=i+a.options.indentUnit:"subtract"==c?k=i-a.options.indentUnit:"number"==typeof c&&(k=i+c),k=Math.max(0,k);var l="",m=0;if(a.options.indentWithTabs)for(var n=Math.floor(k/g);n;--n)m+=g,l+="	";k>m&&(l+=Te(k-m)),l!=j&&vc(a.doc,l,wc(b,0),wc(b,j.length),"+input"),h.stateAfter=null}function Qc(a,b,c){var d=b,e=b,f=a.doc;return"number"==typeof b?e=fe(f,Ac(f,b)):d=je(b),null==d?null:c(e,d)?(Fb(a,d,d+1),e):null}function Rc(a,b,c,d,e){function k(){var b=f+c;return b<a.first||b>=a.first+a.size?j=!1:(f=b,i=fe(a,b))}function l(a){var b=(e?Ef:Ff)(i,g,c,!0);if(null==b){if(a||!k())return j=!1;g=e?(0>c?xf:wf)(i):0>c?i.text.length:0}else g=b;return!0}var f=b.line,g=b.ch,h=c,i=fe(a,f),j=!0;if("char"==d)l();else if("column"==d)l(!0);else if("word"==d||"group"==d)for(var m=null,n="group"==d,o=!0;!(0>c)||l(!o);o=!1){var p=i.text.charAt(g)||"\n",q=af(p)?"w":n?/\s/.test(p)?null:"p":null;if(m&&m!=q){0>c&&(c=1,l());break}if(q&&(m=q),c>0&&!l(!o))break}var r=Ic(a,wc(f,g),h,!0);return j||(r.hitSide=!0),r}function Sc(a,b,c,d){var g,e=a.doc,f=b.left;if("page"==d){var h=Math.min(a.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);g=b.top+c*(h-(0>c?1.5:.5)*xb(a.display))}else"line"==d&&(g=c>0?b.bottom+3:b.top-3);for(;;){var i=ub(a,f,g);if(!i.outside)break;if(0>c?0>=g:g>=e.height){i.hitSide=!0;break}g+=5*c}return i}function Tc(a,b){var c=b.ch,d=b.ch;if(a){b.xRel<0||d==a.length?--c:++d;for(var e=a.charAt(c),f=af(e)?af:/\s/.test(e)?function(a){return/\s/.test(a)}:function(a){return!/\s/.test(a)&&!af(a)};c>0&&f(a.charAt(c-1));)--c;for(;d<a.length&&f(a.charAt(d));)++d}return{from:wc(b.line,c),to:wc(b.line,d)}}function Uc(a,b){Ec(a.doc,wc(b,0),Bc(a.doc,wc(b+1,0)))}function Xc(a,b,c,d){w.defaults[a]=b,c&&(Vc[a]=d?function(a,b,d){d!=Yc&&c(a,b,d)}:c)}function bd(a,b){if(b===!0)return b;if(a.copyState)return a.copyState(b);var c={};for(var d in b){var e=b[d];e instanceof Array&&(e=e.concat([])),c[d]=e}return c}function cd(a,b,c){return a.startState?a.startState(b,c):!0}function fd(a){return"string"==typeof a?ed[a]:a}function gd(a,b,c){function d(b){b=fd(b);var e=b[a];if(e===!1)return"stop";if(null!=e&&c(e))return!0;if(b.nofallthrough)return"stop";var f=b.fallthrough;if(null==f)return!1;if("[object Array]"!=Object.prototype.toString.call(f))return d(f);for(var g=0,h=f.length;h>g;++g){var i=d(f[g]);if(i)return i}return!1}for(var e=0;e<b.length;++e){var f=d(b[e]);if(f)return"stop"!=f}}function hd(a){var b=sf[a.keyCode];return"Ctrl"==b||"Alt"==b||"Shift"==b||"Mod"==b}function id(a,b){if(h&&34==a.keyCode&&a["char"])return!1;var c=sf[a.keyCode];return null==c||a.altGraphKey?!1:(a.altKey&&(c="Alt-"+c),(s?a.metaKey:a.ctrlKey)&&(c="Ctrl-"+c),(s?a.ctrlKey:a.metaKey)&&(c="Cmd-"+c),!b&&a.shiftKey&&(c="Shift-"+c),c)}function jd(a,b){this.pos=this.start=0,this.string=a,this.tabSize=b||8,this.lastColumnPos=this.lastColumnValue=0}function kd(a,b){this.lines=[],this.type=b,this.doc=a}function ld(a,b,c,d,e){if(d&&d.shared)return nd(a,b,c,d,e);if(a.cm&&!a.cm.curOp)return Cb(a.cm,ld)(a,b,c,d,e);var f=new kd(a,e);if("range"==e&&!yc(b,c))return f;d&&Ye(d,f),f.replacedWith&&(f.collapsed=!0,f.replacedWith=df("span",[f.replacedWith],"CodeMirror-widget"),d.handleMouseEvents||(f.replacedWith.ignoreEvents=!0)),f.collapsed&&(v=!0),f.addToHistory&&qe(a,{from:b,to:c,origin:"markText"},{head:a.sel.head,anchor:a.sel.anchor},0/0);var i,j,l,g=b.line,h=0,k=a.cm;if(a.iter(g,c.line+1,function(d){k&&f.collapsed&&!k.options.lineWrapping&&zd(a,d)==k.display.maxLine&&(l=!0);var e={from:null,to:null,marker:f};h+=d.text.length,g==b.line&&(e.from=b.ch,h-=b.ch),g==c.line&&(e.to=c.ch,h-=d.text.length-c.ch),f.collapsed&&(g==c.line&&(j=wd(d,c.ch)),g==b.line?i=wd(d,b.ch):ie(d,0)),qd(d,e),++g}),f.collapsed&&a.iter(b.line,c.line+1,function(b){Ad(a,b)&&ie(b,0)}),f.clearOnEnter&&Fe(f,"beforeCursorEnter",function(){f.clear()}),f.readOnly&&(u=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory()),f.collapsed){if(i!=j)throw new Error("Inserting collapsed marker overlapping an existing one");f.size=h,f.atomic=!0}return k&&(l&&(k.curOp.updateMaxLine=!0),(f.className||f.startStyle||f.endStyle||f.collapsed)&&Fb(k,b.line,c.line+1),f.atomic&&Hc(k)),f}function md(a,b){this.markers=a,this.primary=b;for(var c=0,d=this;c<a.length;++c)a[c].parent=this,Fe(a[c],"clear",function(){d.clear()})}function nd(a,b,c,d,e){d=Ye(d),d.shared=!1;var f=[ld(a,b,c,d,e)],g=f[0],h=d.replacedWith;return de(a,function(a){h&&(d.replacedWith=h.cloneNode(!0)),f.push(ld(a,Bc(a,b),Bc(a,c),d,e));for(var i=0;i<a.linked.length;++i)if(a.linked[i].isParent)return;g=Ue(f)}),new md(f,g)}function od(a,b){if(a)for(var c=0;c<a.length;++c){var d=a[c];if(d.marker==b)return d}}function pd(a,b){for(var c,d=0;d<a.length;++d)a[d]!=b&&(c||(c=[])).push(a[d]);return c}function qd(a,b){a.markedSpans=a.markedSpans?a.markedSpans.concat([b]):[b],b.marker.attachLine(a)}function rd(a,b,c){if(a)for(var e,d=0;d<a.length;++d){var f=a[d],g=f.marker,h=null==f.from||(g.inclusiveLeft?f.from<=b:f.from<b);if(h||"bookmark"==g.type&&f.from==b&&(!c||!f.marker.insertLeft)){var i=null==f.to||(g.inclusiveRight?f.to>=b:f.to>b);(e||(e=[])).push({from:f.from,to:i?null:f.to,marker:g})}}return e}function sd(a,b,c){if(a)for(var e,d=0;d<a.length;++d){var f=a[d],g=f.marker,h=null==f.to||(g.inclusiveRight?f.to>=b:f.to>b);if(h||"bookmark"==g.type&&f.from==b&&(!c||f.marker.insertLeft)){var i=null==f.from||(g.inclusiveLeft?f.from<=b:f.from<b);(e||(e=[])).push({from:i?null:f.from-b,to:null==f.to?null:f.to-b,marker:g})}}return e}function td(a,b){var c=Dc(a,b.from.line)&&fe(a,b.from.line).markedSpans,d=Dc(a,b.to.line)&&fe(a,b.to.line).markedSpans;if(!c&&!d)return null;var e=b.from.ch,f=b.to.ch,g=xc(b.from,b.to),h=rd(c,e,g),i=sd(d,f,g),j=1==b.text.length,k=Ue(b.text).length+(j?e:0);if(h)for(var l=0;l<h.length;++l){var m=h[l];if(null==m.to){var n=od(i,m.marker);n?j&&(m.to=null==n.to?null:n.to+k):m.to=e}}if(i)for(var l=0;l<i.length;++l){var m=i[l];if(null!=m.to&&(m.to+=k),null==m.from){var n=od(h,m.marker);n||(m.from=k,j&&(h||(h=[])).push(m))}else m.from+=k,j&&(h||(h=[])).push(m)}if(j&&h){for(var l=0;l<h.length;++l)null!=h[l].from&&h[l].from==h[l].to&&"bookmark"!=h[l].marker.type&&h.splice(l--,1);h.length||(h=null)}var o=[h];if(!j){var q,p=b.text.length-2;if(p>0&&h)for(var l=0;l<h.length;++l)null==h[l].to&&(q||(q=[])).push({from:null,to:null,marker:h[l].marker});for(var l=0;p>l;++l)o.push(q);o.push(i)}return o}function ud(a,b){var c=se(a,b),d=td(a,b);if(!c)return d;if(!d)return c;for(var e=0;e<c.length;++e){var f=c[e],g=d[e];if(f&&g)a:for(var h=0;h<g.length;++h){for(var i=g[h],j=0;j<f.length;++j)if(f[j].marker==i.marker)continue a;f.push(i)}else g&&(c[e]=g)}return c}function vd(a,b,c){var d=null;if(a.iter(b.line,c.line+1,function(a){if(a.markedSpans)for(var b=0;b<a.markedSpans.length;++b){var c=a.markedSpans[b].marker;!c.readOnly||d&&-1!=We(d,c)||(d||(d=[])).push(c)}}),!d)return null;for(var e=[{from:b,to:c}],f=0;f<d.length;++f)for(var g=d[f],h=g.find(),i=0;i<e.length;++i){var j=e[i];if(!yc(j.to,h.from)&&!yc(h.to,j.from)){var k=[i,1];(yc(j.from,h.from)||!g.inclusiveLeft&&xc(j.from,h.from))&&k.push({from:j.from,to:h.from}),(yc(h.to,j.to)||!g.inclusiveRight&&xc(j.to,h.to))&&k.push({from:h.to,to:j.to}),e.splice.apply(e,k),i+=k.length-1}}return e}function wd(a,b){var d,c=v&&a.markedSpans;if(c)for(var e,f=0;f<c.length;++f)e=c[f],e.marker.collapsed&&(null==e.from||e.from<b)&&(null==e.to||e.to>b)&&(!d||d.width<e.marker.width)&&(d=e.marker);return d}function xd(a){return wd(a,-1)}function yd(a){return wd(a,a.text.length+1)}function zd(a,b){for(var c;c=xd(b);)b=fe(a,c.find().from.line);return b}function Ad(a,b){var c=v&&b.markedSpans;if(c)for(var d,e=0;e<c.length;++e)if(d=c[e],d.marker.collapsed){if(null==d.from)return!0;if(!d.marker.replacedWith&&0==d.from&&d.marker.inclusiveLeft&&Bd(a,b,d))return!0}}function Bd(a,b,c){if(null==c.to){var d=c.marker.find().to,e=fe(a,d.line);return Bd(a,e,od(e.markedSpans,c.marker))}if(c.marker.inclusiveRight&&c.to==b.text.length)return!0;for(var f,g=0;g<b.markedSpans.length;++g)if(f=b.markedSpans[g],f.marker.collapsed&&!f.marker.replacedWith&&f.from==c.to&&(f.marker.inclusiveLeft||c.marker.inclusiveRight)&&Bd(a,b,f))return!0}function Cd(a){var b=a.markedSpans;if(b){for(var c=0;c<b.length;++c)b[c].marker.detachLine(a);a.markedSpans=null}}function Dd(a,b){if(b){for(var c=0;c<b.length;++c)b[c].marker.attachLine(a);a.markedSpans=b}}function Fd(a){return function(){var b=!this.cm.curOp;b&&Ab(this.cm);try{var c=a.apply(this,arguments)}finally{b&&Bb(this.cm)}return c}}function Gd(a){return null!=a.height?a.height:(a.node.parentNode&&1==a.node.parentNode.nodeType||ff(a.cm.display.measure,df("div",[a.node],null,"position: relative")),a.height=a.node.offsetHeight)}function Hd(a,b,c,d){var e=new Ed(a,c,d);return e.noHScroll&&(a.display.alignWidgets=!0),Qc(a,b,function(b){if((b.widgets||(b.widgets=[])).push(e),e.line=b,!Ad(a.doc,b)||e.showIfHidden){var c=le(a,b)<a.display.scroller.scrollTop;ie(b,b.height+Gd(e)),c&&Oc(a,0,e.height)}return!0}),e}function Id(a,b,c){var d={text:a};return Dd(d,b),d.height=c?c(d):1,d}function Jd(a,b,c,d){a.text=b,a.stateAfter&&(a.stateAfter=null),a.styles&&(a.styles=null),null!=a.order&&(a.order=null),Cd(a),Dd(a,c);var e=d?d(a):1;e!=a.height&&ie(a,e)}function Kd(a){a.parent=null,Cd(a)}function Ld(a,b,c,d,e){var f=c.flattenSpans;null==f&&(f=a.options.flattenSpans);var j,g=0,h=null,i=new jd(b,a.options.tabSize);for(""==b&&c.blankLine&&c.blankLine(d);!i.eol();)i.pos>a.options.maxHighlightLength?(f=!1,i.pos=Math.min(b.length,i.start+5e4),j=null):j=c.token(i,d),f&&h==j||(g<i.start&&e(i.start,h),g=i.start,h=j),i.start=i.pos;g<i.pos&&e(i.pos,h)}function Md(a,b,c){var d=[a.state.modeGen];Ld(a,b.text,a.doc.mode,c,function(a,b){d.push(a,b)});for(var e=0;e<a.state.overlays.length;++e){var f=a.state.overlays[e],g=1,h=0;Ld(a,b.text,f.mode,!0,function(a,b){for(var c=g;a>h;){var e=d[g];e>a&&d.splice(g,1,a,d[g+1],e),g+=2,h=Math.min(a,e)}if(b)if(f.opaque)d.splice(c,g-c,a,b),g=c+2;else for(;g>c;c+=2){var i=d[c+1];d[c+1]=i?i+" "+b:b}})}return d}function Nd(a,b){return b.styles&&b.styles[0]==a.state.modeGen||(b.styles=Md(a,b,b.stateAfter=cb(a,je(b)))),b.styles}function Od(a,b,c){var d=a.doc.mode,e=new jd(b.text,a.options.tabSize);for(""==b.text&&d.blankLine&&d.blankLine(c);!e.eol()&&e.pos<=a.options.maxHighlightLength;)d.token(e,c),e.start=e.pos}function Qd(a){return a?Pd[a]||(Pd[a]="cm-"+a.replace(/ +/g," cm-")):null}function Rd(a,c,d){for(var f,g=c,h=!0;f=xd(g);)g=fe(a.doc,f.find().from.line);var i={pre:df("pre"),col:0,pos:0,display:!d,measure:null,measuredSomething:!1,cm:a};g.textClass&&(i.pre.className=g.textClass);do{g.text&&(h=!1),i.measure=g==c&&d,i.pos=0,i.addToken=i.measure?Ud:Td,(b||e)&&a.getOption("lineWrapping")&&(i.addToken=Vd(i.addToken));var j=Xd(g,i,Nd(a,g));d&&g==c&&!i.measuredSomething&&(d[0]=i.pre.appendChild(of(a.display.measure)),i.measuredSomething=!0),j&&(g=fe(a.doc,j.to.line))}while(j);!d||i.measuredSomething||d[0]||(d[0]=i.pre.appendChild(h?df("span","\xa0"):of(a.display.measure))),i.pre.firstChild||Ad(a.doc,c)||i.pre.appendChild(document.createTextNode("\xa0"));var k;if(d&&b&&(k=me(g))){var l=k.length-1;k[l].from==k[l].to&&--l;var m=k[l],n=k[l-1];if(m.from+1==m.to&&n&&m.level<n.level){var o=d[i.pos-1];o&&o.parentNode.insertBefore(o.measureRight=of(a.display.measure),o.nextSibling)}}return He(a,"renderLine",a,c,i.pre),i.pre}function Td(a,b,c,d,e){if(b){if(Sd.test(b))for(var f=document.createDocumentFragment(),g=0;;){Sd.lastIndex=g;var h=Sd.exec(b),i=h?h.index-g:b.length-g;if(i&&(f.appendChild(document.createTextNode(b.slice(g,g+i))),a.col+=i),!h)break;if(g+=i+1,"	"==h[0]){var j=a.cm.options.tabSize,k=j-a.col%j;f.appendChild(df("span",Te(k),"cm-tab")),a.col+=k}else{var l=df("span","\u2022","cm-invalidchar");l.title="\\u"+h[0].charCodeAt(0).toString(16),f.appendChild(l),a.col+=1}}else{a.col+=b.length;var f=document.createTextNode(b)}if(c||d||e||a.measure){var m=c||"";return d&&(m+=d),e&&(m+=e),a.pre.appendChild(df("span",[f],m))}a.pre.appendChild(f)}}function Ud(a,c,d,e,f){for(var g=a.cm.options.lineWrapping,h=0;h<c.length;++h){var i=c.charAt(h),j=0==h;i>="\ud800"&&"\udbff">i&&h<c.length-1?(i=c.slice(h,h+2),++h):h&&g&&kf(c,h)&&a.pre.appendChild(df("wbr"));var k=a.measure[a.pos]=Td(a,i,d,j&&e,h==c.length-1&&f);b&&g&&" "==i&&h&&!/\s/.test(c.charAt(h-1))&&h<c.length-1&&!/\s/.test(c.charAt(h+1))&&(k.style.whiteSpace="normal"),a.pos+=i.length}c.length&&(a.measuredSomething=!0)}function Vd(a){function b(a){for(var b=" ",c=0;c<a.length-2;++c)b+=c%2?" ":"\xa0";return b+=" "}return function(c,d,e,f,g){return a(c,d.replace(/ {3,}/,b),e,f,g)}}function Wd(a,b,c){c&&(a.display||(c=c.cloneNode(!0)),a.measure&&(a.measure[a.pos]=b?c:a.pre.appendChild(of(a.cm.display.measure)),a.measuredSomething=!0),a.pre.appendChild(c)),a.pos+=b}function Xd(a,b,c){var d=a.markedSpans,e=a.text,f=0;if(d)for(var k,m,n,o,p,h=e.length,i=0,g=1,j="",l=0;;){if(l==i){m=n=o="",p=null,l=1/0;for(var q=null,r=0;r<d.length;++r){var s=d[r],t=s.marker;s.from<=i&&(null==s.to||s.to>i)?(null!=s.to&&l>s.to&&(l=s.to,n=""),t.className&&(m+=" "+t.className),t.startStyle&&s.from==i&&(o+=" "+t.startStyle),t.endStyle&&s.to==l&&(n+=" "+t.endStyle),t.collapsed&&(!p||p.marker.size<t.size)&&(p=s)):s.from>i&&l>s.from&&(l=s.from),"bookmark"==t.type&&s.from==i&&t.replacedWith&&(q=t.replacedWith)}if(p&&(p.from||0)==i&&(Wd(b,(null==p.to?h:p.to)-i,null!=p.from&&p.marker.replacedWith),null==p.to))return p.marker.find();q&&!p&&Wd(b,0,q)}if(i>=h)break;for(var u=Math.min(h,l);;){if(j){var v=i+j.length;if(!p){var w=v>u?j.slice(0,u-i):j;b.addToken(b,w,k?k+m:m,o,i+w.length==l?n:"")}if(v>=u){j=j.slice(u-i),i=u;break}i=v,o=""}j=e.slice(f,f=c[g++]),k=Qd(c[g++])}}else for(var g=1;g<c.length;g+=2)b.addToken(b,e.slice(f,f=c[g]),Qd(c[g+1]))}function Yd(a,b,c,d,e){function f(a){return c?c[a]:null}function g(a,c,d){Jd(a,c,d,e),Ke(a,"change",a,b)}var h=b.from,i=b.to,j=b.text,k=fe(a,h.line),l=fe(a,i.line),m=Ue(j),n=f(j.length-1),o=i.line-h.line;if(0==h.ch&&0==i.ch&&""==m){for(var p=0,q=j.length-1,r=[];q>p;++p)r.push(Id(j[p],f(p),e));g(l,l.text,n),o&&a.remove(h.line,o),r.length&&a.insert(h.line,r)}else if(k==l)if(1==j.length)g(k,k.text.slice(0,h.ch)+m+k.text.slice(i.ch),n);else{for(var r=[],p=1,q=j.length-1;q>p;++p)r.push(Id(j[p],f(p),e));r.push(Id(m+k.text.slice(i.ch),n,e)),g(k,k.text.slice(0,h.ch)+j[0],f(0)),a.insert(h.line+1,r)}else if(1==j.length)g(k,k.text.slice(0,h.ch)+j[0]+l.text.slice(i.ch),f(0)),a.remove(h.line+1,o);else{g(k,k.text.slice(0,h.ch)+j[0],f(0)),g(l,m+l.text.slice(i.ch),n);for(var p=1,q=j.length-1,r=[];q>p;++p)r.push(Id(j[p],f(p),e));o>1&&a.remove(h.line+1,o-1),a.insert(h.line+1,r)}Ke(a,"change",a,b),Gc(a,d.anchor,d.head,null,!0)}function Zd(a){this.lines=a,this.parent=null;for(var b=0,c=a.length,d=0;c>b;++b)a[b].parent=this,d+=a[b].height;this.height=d}function $d(a){this.children=a;for(var b=0,c=0,d=0,e=a.length;e>d;++d){var f=a[d];b+=f.chunkSize(),c+=f.height,f.parent=this}this.size=b,this.height=c,this.parent=null}function de(a,b,c){function d(a,e,f){if(a.linked)for(var g=0;g<a.linked.length;++g){var h=a.linked[g];if(h.doc!=e){var i=f&&h.sharedHist;(!c||i)&&(b(h.doc,i),d(h.doc,a,i))}}}d(a,null,!0)}function ee(a,b){if(b.cm)throw new Error("This document is already in use.");a.doc=b,b.cm=a,B(a),y(a),a.options.lineWrapping||H(a),a.options.mode=b.modeOption,Fb(a)}function fe(a,b){for(b-=a.first;!a.lines;)for(var c=0;;++c){var d=a.children[c],e=d.chunkSize();if(e>b){a=d;break}b-=e}return a.lines[b]}function ge(a,b,c){var d=[],e=b.line;return a.iter(b.line,c.line+1,function(a){var f=a.text;e==c.line&&(f=f.slice(0,c.ch)),e==b.line&&(f=f.slice(b.ch)),d.push(f),++e}),d}function he(a,b,c){var d=[];return a.iter(b,c,function(a){d.push(a.text)}),d}function ie(a,b){for(var c=b-a.height,d=a;d;d=d.parent)d.height+=c}function je(a){if(null==a.parent)return null;for(var b=a.parent,c=We(b.lines,a),d=b.parent;d;b=d,d=d.parent)for(var e=0;d.children[e]!=b;++e)c+=d.children[e].chunkSize();return c+b.first}function ke(a,b){var c=a.first;a:do{for(var d=0,e=a.children.length;e>d;++d){var f=a.children[d],g=f.height;if(g>b){a=f;continue a}b-=g,c+=f.chunkSize()}return c}while(!a.lines);for(var d=0,e=a.lines.length;e>d;++d){var h=a.lines[d],i=h.height;if(i>b)break;b-=i}return c+d
10
}function le(a,b){b=zd(a.doc,b);for(var c=0,d=b.parent,e=0;e<d.lines.length;++e){var f=d.lines[e];if(f==b)break;c+=f.height}for(var g=d.parent;g;d=g,g=d.parent)for(var e=0;e<g.children.length;++e){var h=g.children[e];if(h==d)break;c+=h.height}return c}function me(a){var b=a.order;return null==b&&(b=a.order=Gf(a.text)),b}function ne(a){return{done:[],undone:[],undoDepth:1/0,lastTime:0,lastOp:null,lastOrigin:null,generation:a||1,maxGeneration:a||1}}function oe(a,b,c,d){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,c),Math.min(a.first+a.size,d),function(c){c.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=c.markedSpans),++f})}function pe(a,b){var c={from:b.from,to:lc(b),text:ge(a,b.from,b.to)};return oe(a,c,b.from.line,b.to.line+1),de(a,function(a){oe(a,c,b.from.line,b.to.line+1)},!0),c}function qe(a,b,c,d){var e=a.history;e.undone.length=0;var f=+new Date,g=Ue(e.done);if(g&&(e.lastOp==d||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&a.cm&&e.lastTime>f-a.cm.options.historyEventDelay||"*"==b.origin.charAt(0)))){var h=Ue(g.changes);xc(b.from,b.to)&&xc(b.from,h.to)?h.to=lc(b):g.changes.push(pe(a,b)),g.anchorAfter=c.anchor,g.headAfter=c.head}else for(g={changes:[pe(a,b)],generation:e.generation,anchorBefore:a.sel.anchor,headBefore:a.sel.head,anchorAfter:c.anchor,headAfter:c.head},e.done.push(g),e.generation=++e.maxGeneration;e.done.length>e.undoDepth;)e.done.shift();e.lastTime=f,e.lastOp=d,e.lastOrigin=b.origin}function re(a){if(!a)return null;for(var c,b=0;b<a.length;++b)a[b].marker.explicitlyCleared?c||(c=a.slice(0,b)):c&&c.push(a[b]);return c?c.length?c:null:a}function se(a,b){var c=b["spans_"+a.id];if(!c)return null;for(var d=0,e=[];d<b.text.length;++d)e.push(re(c[d]));return e}function te(a,b){for(var c=0,d=[];c<a.length;++c){var e=a[c],f=e.changes,g=[];d.push({changes:g,anchorBefore:e.anchorBefore,headBefore:e.headBefore,anchorAfter:e.anchorAfter,headAfter:e.headAfter});for(var h=0;h<f.length;++h){var j,i=f[h];if(g.push({from:i.from,to:i.to,text:i.text}),b)for(var k in i)(j=k.match(/^spans_(\d+)$/))&&We(b,Number(j[1]))>-1&&(Ue(g)[k]=i[k],delete i[k])}}return d}function ue(a,b,c,d){c<a.line?a.line+=d:b<a.line&&(a.line=b,a.ch=0)}function ve(a,b,c,d){for(var e=0;e<a.length;++e){for(var f=a[e],g=!0,h=0;h<f.changes.length;++h){var i=f.changes[h];if(f.copied||(i.from=zc(i.from),i.to=zc(i.to)),c<i.from.line)i.from.line+=d,i.to.line+=d;else if(b<=i.to.line){g=!1;break}}f.copied||(f.anchorBefore=zc(f.anchorBefore),f.headBefore=zc(f.headBefore),f.anchorAfter=zc(f.anchorAfter),f.readAfter=zc(f.headAfter),f.copied=!0),g?(ue(f.anchorBefore),ue(f.headBefore),ue(f.anchorAfter),ue(f.headAfter)):(a.splice(0,e+1),e=0)}}function we(a,b){var c=b.from.line,d=b.to.line,e=b.text.length-(d-c)-1;ve(a.done,c,d,e),ve(a.undone,c,d,e)}function xe(){Ce(this)}function ye(a){return a.stop||(a.stop=xe),a}function ze(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function Ae(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0}function Be(a){return null!=a.defaultPrevented?a.defaultPrevented:0==a.returnValue}function Ce(a){ze(a),Ae(a)}function De(a){return a.target||a.srcElement}function Ee(a){var b=a.which;return null==b&&(1&a.button?b=1:2&a.button?b=3:4&a.button&&(b=2)),p&&a.ctrlKey&&1==b&&(b=3),b}function Fe(a,b,c){if(a.addEventListener)a.addEventListener(b,c,!1);else if(a.attachEvent)a.attachEvent("on"+b,c);else{var d=a._handlers||(a._handlers={}),e=d[b]||(d[b]=[]);e.push(c)}}function Ge(a,b,c){if(a.removeEventListener)a.removeEventListener(b,c,!1);else if(a.detachEvent)a.detachEvent("on"+b,c);else{var d=a._handlers&&a._handlers[b];if(!d)return;for(var e=0;e<d.length;++e)if(d[e]==c){d.splice(e,1);break}}}function He(a,b){var c=a._handlers&&a._handlers[b];if(c)for(var d=Array.prototype.slice.call(arguments,2),e=0;e<c.length;++e)c[e].apply(null,d)}function Ke(a,b){function e(a){return function(){a.apply(null,d)}}var c=a._handlers&&a._handlers[b];if(c){var d=Array.prototype.slice.call(arguments,2);Ie||(++Je,Ie=[],setTimeout(Me,0));for(var f=0;f<c.length;++f)Ie.push(e(c[f]))}}function Le(a,b){return He(a,b.type,a,b),Be(b)}function Me(){--Je;var a=Ie;Ie=null;for(var b=0;b<a.length;++b)a[b]()}function Ne(a,b){var c=a._handlers&&a._handlers[b];return c&&c.length>0}function Qe(){this.id=null}function Re(a,b,c,d,e){null==b&&(b=a.search(/[^\s\u00a0]/),-1==b&&(b=a.length));for(var f=d||0,g=e||0;b>f;++f)"	"==a.charAt(f)?g+=c-g%c:++g;return g}function Te(a){for(;Se.length<=a;)Se.push(Ue(Se)+" ");return Se[a]}function Ue(a){return a[a.length-1]}function Ve(a){if(n)a.selectionStart=0,a.selectionEnd=a.value.length;else try{a.select()}catch(b){}}function We(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0,d=a.length;d>c;++c)if(a[c]==b)return c;return-1}function Xe(a,b){function c(){}c.prototype=a;var d=new c;return b&&Ye(b,d),d}function Ye(a,b){b||(b={});for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function Ze(a){for(var b=[],c=0;a>c;++c)b.push(void 0);return b}function $e(a){var b=Array.prototype.slice.call(arguments,1);return function(){return a.apply(null,b)}}function af(a){return/\w/.test(a)||a>"\x80"&&(a.toUpperCase()!=a.toLowerCase()||_e.test(a))}function bf(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function df(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)gf(e,b);else if(b)for(var f=0;f<b.length;++f)e.appendChild(b[f]);return e}function ef(a){for(var b=a.childNodes.length;b>0;--b)a.removeChild(a.firstChild);return a}function ff(a,b){return ef(a).appendChild(b)}function gf(a,b){d?(a.innerHTML="",a.appendChild(document.createTextNode(b))):a.textContent=b}function hf(a){return a.getBoundingClientRect()}function kf(){return!1}function mf(a){if(null!=lf)return lf;var b=df("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return ff(a,b),b.offsetWidth&&(lf=b.offsetHeight-b.clientHeight),lf||0}function of(a){if(null==nf){var b=df("span","\u200b");ff(a,df("span",[b,document.createTextNode("x")])),0!=a.firstChild.offsetHeight&&(nf=b.offsetWidth<=1&&b.offsetHeight>2&&!c)}return nf?df("span","\u200b"):df("span","\xa0",null,"display: inline-block; width: 1px; margin-right: -1px")}function tf(a,b,c,d){if(!a)return d(b,c,"ltr");for(var e=0;e<a.length;++e){var f=a[e];(f.from<c&&f.to>b||b==c&&f.to==b)&&d(Math.max(f.from,b),Math.min(f.to,c),1==f.level?"rtl":"ltr")}}function uf(a){return a.level%2?a.to:a.from}function vf(a){return a.level%2?a.from:a.to}function wf(a){var b=me(a);return b?uf(b[0]):0}function xf(a){var b=me(a);return b?vf(Ue(b)):a.text.length}function yf(a,b){var c=fe(a.doc,b),d=zd(a.doc,c);d!=c&&(b=je(d));var e=me(d),f=e?e[0].level%2?xf(d):wf(d):0;return wc(b,f)}function zf(a,b){for(var c,d;c=yd(d=fe(a.doc,b));)b=c.find().to.line;var e=me(d),f=e?e[0].level%2?wf(d):xf(d):d.text.length;return wc(b,f)}function Af(a,b,c){var d=a[0].level;return b==d?!0:c==d?!1:c>b}function Cf(a,b){for(var d,c=0;c<a.length;++c){var e=a[c];if(e.from<b&&e.to>b)return Bf=null,c;if(e.from==b||e.to==b){if(null!=d)return Af(a,e.level,a[d].level)?(Bf=d,c):(Bf=c,d);d=c}}return Bf=null,d}function Df(a,b,c,d){if(!d)return b+c;do b+=c;while(b>0&&cf.test(a.text.charAt(b)));return b}function Ef(a,b,c,d){var e=me(a);if(!e)return Ff(a,b,c,d);for(var f=Cf(e,b),g=e[f],h=Df(a,b,g.level%2?-c:c,d);;){if(h>g.from&&h<g.to)return h;if(h==g.from||h==g.to)return Cf(e,h)==f?h:(g=e[f+=c],c>0==g.level%2?g.to:g.from);if(g=e[f+=c],!g)return null;h=c>0==g.level%2?Df(a,g.to,-1,d):Df(a,g.from,1,d)}}function Ff(a,b,c,d){var e=b+c;if(d)for(;e>0&&cf.test(a.text.charAt(e));)e+=c;return 0>e||e>a.text.length?null:e}var a=/gecko\/\d/i.test(navigator.userAgent),b=/MSIE \d/.test(navigator.userAgent),c=b&&(null==document.documentMode||document.documentMode<8),d=b&&(null==document.documentMode||document.documentMode<9),e=/WebKit\//.test(navigator.userAgent),f=e&&/Qt\/\d+\.\d+/.test(navigator.userAgent),g=/Chrome\//.test(navigator.userAgent),h=/Opera\//.test(navigator.userAgent),i=/Apple Computer/.test(navigator.vendor),j=/KHTML\//.test(navigator.userAgent),k=/Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent),l=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),m=/PhantomJS/.test(navigator.userAgent),n=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),o=n||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),p=n||/Mac/.test(navigator.platform),q=/windows/i.test(navigator.platform),r=h&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);r&&(r=Number(r[1]));var wb,Pb,Qb,s=p&&(f||h&&(null==r||12.11>r)),t=a||b&&!d,u=!1,v=!1,zb=0,Tb=0,Yb=0,Zb=null;b?Zb=-.53:a?Zb=15:g?Zb=-.7:i&&(Zb=-1/3);var bc,jc,ec=null,lc=w.changeEnd=function(a){return a.text?wc(a.from.line+a.text.length-1,Ue(a.text).length+(1==a.text.length?a.from.ch:0)):a.to};w.Pos=wc,w.prototype={constructor:w,focus:function(){window.focus(),Kb(this),hc(this),Hb(this)},setOption:function(a,b){var c=this.options,d=c[a];(c[a]!=b||"mode"==a)&&(c[a]=b,Vc.hasOwnProperty(a)&&Cb(this,Vc[a])(this,b,d))},getOption:function(a){return this.options[a]},getDoc:function(){return this.doc},addKeyMap:function(a,b){this.state.keyMaps[b?"push":"unshift"](a)},removeKeyMap:function(a){for(var b=this.state.keyMaps,c=0;c<b.length;++c)if(("string"==typeof a?b[c].name:b[c])==a)return b.splice(c,1),!0},addOverlay:Cb(null,function(a,b){var c=a.token?a:w.getMode(this.options,a);if(c.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:c,modeSpec:a,opaque:b&&b.opaque}),this.state.modeGen++,Fb(this)}),removeOverlay:Cb(null,function(a){for(var b=this.state.overlays,c=0;c<b.length;++c){var d=b[c].modeSpec;if(d==a||"string"==typeof a&&d.name==a)return b.splice(c,1),this.state.modeGen++,Fb(this),void 0}}),indentLine:Cb(null,function(a,b,c){"string"!=typeof b&&"number"!=typeof b&&(b=null==b?this.options.smartIndent?"smart":"prev":b?"add":"subtract"),Dc(this.doc,a)&&Pc(this,a,b,c)}),indentSelection:Cb(null,function(a){var b=this.doc.sel;if(xc(b.from,b.to))return Pc(this,b.from.line,a);for(var c=b.to.line-(b.to.ch?0:1),d=b.from.line;c>=d;++d)Pc(this,d,a)}),getTokenAt:function(a,b){var c=this.doc;a=Bc(c,a);for(var d=cb(this,a.line,b),e=this.doc.mode,f=fe(c,a.line),g=new jd(f.text,this.options.tabSize);g.pos<a.ch&&!g.eol();){g.start=g.pos;var h=e.token(g,d)}return{start:g.start,end:g.pos,string:g.current(),className:h||null,type:h||null,state:d}},getTokenTypeAt:function(a){a=Bc(this.doc,a);for(var b=Nd(this,fe(this.doc,a.line)),c=0,d=(b.length-1)/2,e=a.ch;;){var f=c+d>>1;if((f?b[2*f-1]:0)>=e)d=f;else{if(!(b[2*f+1]<e))return b[2*f+2];c=f+1}}},getStateAfter:function(a,b){var c=this.doc;return a=Ac(c,null==a?c.first+c.size-1:a),cb(this,a+1,b)},cursorCoords:function(a,b){var c,d=this.doc.sel;return c=null==a?d.head:"object"==typeof a?Bc(this.doc,a):a?d.from:d.to,sb(this,c,b||"page")},charCoords:function(a,b){return rb(this,Bc(this.doc,a),b||"page")},coordsChar:function(a,b){return a=qb(this,a,b||"page"),ub(this,a.left,a.top)},lineAtHeight:function(a,b){return a=qb(this,{top:a,left:0},b||"page").top,ke(this.doc,a+this.display.viewOffset)},heightAtLine:function(a,b){var c=!1,d=this.doc.first+this.doc.size-1;a<this.doc.first?a=this.doc.first:a>d&&(a=d,c=!0);var e=fe(this.doc,a);return pb(this,fe(this.doc,a),{top:0,left:0},b||"page").top+(c?e.height:0)},defaultTextHeight:function(){return xb(this.display)},defaultCharWidth:function(){return yb(this.display)},setGutterMarker:Cb(null,function(a,b,c){return Qc(this,a,function(a){var d=a.gutterMarkers||(a.gutterMarkers={});return d[b]=c,!c&&bf(d)&&(a.gutterMarkers=null),!0})}),clearGutter:Cb(null,function(a){var b=this,c=b.doc,d=c.first;c.iter(function(c){c.gutterMarkers&&c.gutterMarkers[a]&&(c.gutterMarkers[a]=null,Fb(b,d,d+1),bf(c.gutterMarkers)&&(c.gutterMarkers=null)),++d})}),addLineClass:Cb(null,function(a,b,c){return Qc(this,a,function(a){var d="text"==b?"textClass":"background"==b?"bgClass":"wrapClass";if(a[d]){if(new RegExp("(?:^|\\s)"+c+"(?:$|\\s)").test(a[d]))return!1;a[d]+=" "+c}else a[d]=c;return!0})}),removeLineClass:Cb(null,function(a,b,c){return Qc(this,a,function(a){var d="text"==b?"textClass":"background"==b?"bgClass":"wrapClass",e=a[d];if(!e)return!1;if(null==c)a[d]=null;else{var f=e.match(new RegExp("(?:^|\\s+)"+c+"(?:$|\\s+)"));if(!f)return!1;var g=f.index+f[0].length;a[d]=e.slice(0,f.index)+(f.index&&g!=e.length?" ":"")+e.slice(g)||null}return!0})}),addLineWidget:Cb(null,function(a,b,c){return Hd(this,a,b,c)}),removeLineWidget:function(a){a.clear()},lineInfo:function(a){if("number"==typeof a){if(!Dc(this.doc,a))return null;var b=a;if(a=fe(this.doc,a),!a)return null}else{var b=je(a);if(null==b)return null}return{line:b,handle:a,text:a.text,gutterMarkers:a.gutterMarkers,textClass:a.textClass,bgClass:a.bgClass,wrapClass:a.wrapClass,widgets:a.widgets}},getViewport:function(){return{from:this.display.showingFrom,to:this.display.showingTo}},addWidget:function(a,b,c,d,e){var f=this.display;a=sb(this,Bc(this.doc,a));var g=a.bottom,h=a.left;if(b.style.position="absolute",f.sizer.appendChild(b),"over"==d)g=a.top;else if("above"==d||"near"==d){var i=Math.max(f.wrapper.clientHeight,this.doc.height),j=Math.max(f.sizer.clientWidth,f.lineSpace.clientWidth);("above"==d||a.bottom+b.offsetHeight>i)&&a.top>b.offsetHeight?g=a.top-b.offsetHeight:a.bottom+b.offsetHeight<=i&&(g=a.bottom),h+b.offsetWidth>j&&(h=j-b.offsetWidth)}b.style.top=g+"px",b.style.left=b.style.right="","right"==e?(h=f.sizer.clientWidth-b.offsetWidth,b.style.right="0px"):("left"==e?h=0:"middle"==e&&(h=(f.sizer.clientWidth-b.offsetWidth)/2),b.style.left=h+"px"),c&&Lc(this,h,g,h+b.offsetWidth,g+b.offsetHeight)},triggerOnKeyDown:Cb(null,fc),execCommand:function(a){return dd[a](this)},findPosH:function(a,b,c,d){var e=1;0>b&&(e=-1,b=-b);for(var f=0,g=Bc(this.doc,a);b>f&&(g=Rc(this.doc,g,e,c,d),!g.hitSide);++f);return g},moveH:Cb(null,function(a,b){var d,c=this.doc.sel;d=c.shift||c.extend||xc(c.from,c.to)?Rc(this.doc,c.head,a,b,this.options.rtlMoveVisually):0>a?c.from:c.to,Ec(this.doc,d,d,a)}),deleteH:Cb(null,function(a,b){var c=this.doc.sel;xc(c.from,c.to)?vc(this.doc,"",c.from,Rc(this.doc,c.head,a,b,!1),"+delete"):vc(this.doc,"",c.from,c.to,"+delete"),this.curOp.userSelChange=!0}),findPosV:function(a,b,c,d){var e=1,f=d;0>b&&(e=-1,b=-b);for(var g=0,h=Bc(this.doc,a);b>g;++g){var i=sb(this,h,"div");if(null==f?f=i.left:i.left=f,h=Sc(this,i,e,c),h.hitSide)break}return h},moveV:Cb(null,function(a,b){var c=this.doc.sel,d=sb(this,c.head,"div");null!=c.goalColumn&&(d.left=c.goalColumn);var e=Sc(this,d,a,b);"page"==b&&Oc(this,0,rb(this,e,"div").top-d.top),Ec(this.doc,e,e,a),c.goalColumn=d.left}),toggleOverwrite:function(a){(null==a||a!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?this.display.cursor.className+=" CodeMirror-overwrite":this.display.cursor.className=this.display.cursor.className.replace(" CodeMirror-overwrite",""))},hasFocus:function(){return this.state.focused},scrollTo:Cb(null,function(a,b){Nc(this,a,b)}),getScrollInfo:function(){var a=this.display.scroller,b=Oe;return{left:a.scrollLeft,top:a.scrollTop,height:a.scrollHeight-b,width:a.scrollWidth-b,clientHeight:a.clientHeight-b,clientWidth:a.clientWidth-b}},scrollIntoView:Cb(null,function(a,b){"number"==typeof a&&(a=wc(a,0)),b||(b=0);var c=a;a&&null==a.line||(this.curOp.scrollToPos=a?Bc(this.doc,a):this.doc.sel.head,this.curOp.scrollToPosMargin=b,c=sb(this,this.curOp.scrollToPos));var d=Mc(this,c.left,c.top-b,c.right,c.bottom+b);Nc(this,d.scrollLeft,d.scrollTop)}),setSize:function(a,b){function c(a){return"number"==typeof a||/^\d+$/.test(String(a))?a+"px":a}null!=a&&(this.display.wrapper.style.width=c(a)),null!=b&&(this.display.wrapper.style.height=c(b)),this.refresh()},on:function(a,b){Fe(this,a,b)},off:function(a,b){Ge(this,a,b)},operation:function(a){return Eb(this,a)},refresh:Cb(null,function(){mb(this),Nc(this,this.doc.scrollLeft,this.doc.scrollTop),Fb(this)}),swapDoc:Cb(null,function(a){var b=this.doc;return b.cm=null,ee(this,a),mb(this),Jb(this,!0),Nc(this,a.scrollLeft,a.scrollTop),b}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};var Vc=w.optionHandlers={},Wc=w.defaults={},Yc=w.Init={toString:function(){return"CodeMirror.Init"}};Xc("value","",function(a,b){a.setValue(b)},!0),Xc("mode",null,function(a,b){a.doc.modeOption=b,y(a)},!0),Xc("indentUnit",2,y,!0),Xc("indentWithTabs",!1),Xc("smartIndent",!0),Xc("tabSize",4,function(a){y(a),mb(a),Fb(a)},!0),Xc("electricChars",!0),Xc("rtlMoveVisually",!q),Xc("theme","default",function(a){D(a),E(a)},!0),Xc("keyMap","default",C),Xc("extraKeys",null),Xc("onKeyEvent",null),Xc("onDragEvent",null),Xc("lineWrapping",!1,z,!0),Xc("gutters",[],function(a){I(a.options),E(a)},!0),Xc("fixedGutter",!0,function(a,b){a.display.gutters.style.left=b?O(a.display)+"px":"0",a.refresh()},!0),Xc("coverGutterNextToScrollbar",!1,J,!0),Xc("lineNumbers",!1,function(a){I(a.options),E(a)},!0),Xc("firstLineNumber",1,E,!0),Xc("lineNumberFormatter",function(a){return a},E,!0),Xc("showCursorWhenSelecting",!1,X,!0),Xc("readOnly",!1,function(a,b){"nocursor"==b?(ic(a),a.display.input.blur()):b||Jb(a,!0)}),Xc("dragDrop",!0),Xc("cursorBlinkRate",530),Xc("cursorScrollMargin",0),Xc("cursorHeight",1),Xc("workTime",100),Xc("workDelay",100),Xc("flattenSpans",!0),Xc("pollInterval",100),Xc("undoDepth",40,function(a,b){a.doc.history.undoDepth=b}),Xc("historyEventDelay",500),Xc("viewportMargin",10,function(a){a.refresh()},!0),Xc("maxHighlightLength",1e4,function(a){y(a),a.refresh()},!0),Xc("moveInputWithCursor",!0,function(a,b){b||(a.display.inputDiv.style.top=a.display.inputDiv.style.left=0)}),Xc("tabindex",null,function(a,b){a.display.input.tabIndex=b||""}),Xc("autofocus",null);var Zc=w.modes={},$c=w.mimeModes={};w.defineMode=function(a,b){if(w.defaults.mode||"null"==a||(w.defaults.mode=a),arguments.length>2){b.dependencies=[];for(var c=2;c<arguments.length;++c)b.dependencies.push(arguments[c])}Zc[a]=b},w.defineMIME=function(a,b){$c[a]=b},w.resolveMode=function(a){if("string"==typeof a&&$c.hasOwnProperty(a))a=$c[a];else if(a&&"string"==typeof a.name&&$c.hasOwnProperty(a.name)){var b=$c[a.name];a=Xe(b,a),a.name=b.name}else if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return w.resolveMode("application/xml");return"string"==typeof a?{name:a}:a||{name:"null"}},w.getMode=function(a,b){b=w.resolveMode(b);var c=Zc[b.name];if(!c)return w.getMode(a,"text/plain");var d=c(a,b);if(_c.hasOwnProperty(b.name)){var e=_c[b.name];for(var f in e)e.hasOwnProperty(f)&&(d.hasOwnProperty(f)&&(d["_"+f]=d[f]),d[f]=e[f])}return d.name=b.name,d},w.defineMode("null",function(){return{token:function(a){a.skipToEnd()}}}),w.defineMIME("text/plain","null");var _c=w.modeExtensions={};w.extendMode=function(a,b){var c=_c.hasOwnProperty(a)?_c[a]:_c[a]={};Ye(b,c)},w.defineExtension=function(a,b){w.prototype[a]=b},w.defineDocExtension=function(a,b){ae.prototype[a]=b},w.defineOption=Xc;var ad=[];w.defineInitHook=function(a){ad.push(a)},w.copyState=bd,w.startState=cd,w.innerMode=function(a,b){for(;a.innerMode;){var c=a.innerMode(b);b=c.state,a=c.mode}return c||{mode:a,state:b}};var dd=w.commands={selectAll:function(a){a.setSelection(wc(a.firstLine(),0),wc(a.lastLine()))},killLine:function(a){var b=a.getCursor(!0),c=a.getCursor(!1),d=!xc(b,c);d||a.getLine(b.line).length!=b.ch?a.replaceRange("",b,d?c:wc(b.line),"+delete"):a.replaceRange("",b,wc(b.line+1,0),"+delete")},deleteLine:function(a){var b=a.getCursor().line;a.replaceRange("",wc(b,0),wc(b),"+delete")},delLineLeft:function(a){var b=a.getCursor();a.replaceRange("",wc(b.line,0),b,"+delete")},undo:function(a){a.undo()},redo:function(a){a.redo()},goDocStart:function(a){a.extendSelection(wc(a.firstLine(),0))},goDocEnd:function(a){a.extendSelection(wc(a.lastLine()))},goLineStart:function(a){a.extendSelection(yf(a,a.getCursor().line))},goLineStartSmart:function(a){var b=a.getCursor(),c=yf(a,b.line),d=a.getLineHandle(c.line),e=me(d);if(e&&0!=e[0].level)a.extendSelection(c);else{var f=Math.max(0,d.text.search(/\S/)),g=b.line==c.line&&b.ch<=f&&b.ch;a.extendSelection(wc(c.line,g?0:f))}},goLineEnd:function(a){a.extendSelection(zf(a,a.getCursor().line))},goLineRight:function(a){var b=a.charCoords(a.getCursor(),"div").top+5;a.extendSelection(a.coordsChar({left:a.display.lineDiv.offsetWidth+100,top:b},"div"))},goLineLeft:function(a){var b=a.charCoords(a.getCursor(),"div").top+5;a.extendSelection(a.coordsChar({left:0,top:b},"div"))},goLineUp:function(a){a.moveV(-1,"line")},goLineDown:function(a){a.moveV(1,"line")},goPageUp:function(a){a.moveV(-1,"page")},goPageDown:function(a){a.moveV(1,"page")},goCharLeft:function(a){a.moveH(-1,"char")},goCharRight:function(a){a.moveH(1,"char")},goColumnLeft:function(a){a.moveH(-1,"column")},goColumnRight:function(a){a.moveH(1,"column")},goWordLeft:function(a){a.moveH(-1,"word")},goGroupRight:function(a){a.moveH(1,"group")},goGroupLeft:function(a){a.moveH(-1,"group")},goWordRight:function(a){a.moveH(1,"word")},delCharBefore:function(a){a.deleteH(-1,"char")},delCharAfter:function(a){a.deleteH(1,"char")},delWordBefore:function(a){a.deleteH(-1,"word")},delWordAfter:function(a){a.deleteH(1,"word")},delGroupBefore:function(a){a.deleteH(-1,"group")},delGroupAfter:function(a){a.deleteH(1,"group")},indentAuto:function(a){a.indentSelection("smart")},indentMore:function(a){a.indentSelection("add")},indentLess:function(a){a.indentSelection("subtract")},insertTab:function(a){a.replaceSelection("	","end","+input")},defaultTab:function(a){a.somethingSelected()?a.indentSelection("add"):a.replaceSelection("	","end","+input")},transposeChars:function(a){var b=a.getCursor(),c=a.getLine(b.line);b.ch>0&&b.ch<c.length-1&&a.replaceRange(c.charAt(b.ch)+c.charAt(b.ch-1),wc(b.line,b.ch-1),wc(b.line,b.ch+1))},newlineAndIndent:function(a){Cb(a,function(){a.replaceSelection("\n","end","+input"),a.indentLine(a.getCursor().line,null,!0)})()},toggleOverwrite:function(a){a.toggleOverwrite()}},ed=w.keyMap={};ed.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite"},ed.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Alt-Up":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Down":"goDocEnd","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore",fallthrough:"basic"},ed.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineStart","Cmd-Right":"goLineEnd","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delLineLeft",fallthrough:["basic","emacsy"]},ed["default"]=p?ed.macDefault:ed.pcDefault,ed.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},w.lookupKey=gd,w.isModifierKey=hd,w.keyName=id,w.fromTextArea=function(a,b){function e(){a.value=i.getValue()}if(b||(b={}),b.value=a.value,!b.tabindex&&a.tabindex&&(b.tabindex=a.tabindex),!b.placeholder&&a.placeholder&&(b.placeholder=a.placeholder),null==b.autofocus){var c=document.body;try{c=document.activeElement}catch(d){}b.autofocus=c==a||null!=a.getAttribute("autofocus")&&c==document.body}if(a.form&&(Fe(a.form,"submit",e),!b.leaveSubmitMethodAlone)){var f=a.form,g=f.submit;try{var h=f.submit=function(){e(),f.submit=g,f.submit(),f.submit=h}}catch(d){}}a.style.display="none";var i=w(function(b){a.parentNode.insertBefore(b,a.nextSibling)},b);return i.save=e,i.getTextArea=function(){return a},i.toTextArea=function(){e(),a.parentNode.removeChild(i.getWrapperElement()),a.style.display="",a.form&&(Ge(a.form,"submit",e),"function"==typeof a.form.submit&&(a.form.submit=g))},i},jd.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return 0==this.pos},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(a){var b=this.string.charAt(this.pos);if("string"==typeof a)var c=b==a;else var c=b&&(a.test?a.test(b):a(b));return c?(++this.pos,b):void 0},eatWhile:function(a){for(var b=this.pos;this.eat(a););return this.pos>b},eatSpace:function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a},skipToEnd:function(){this.pos=this.string.length},skipTo:function(a){var b=this.string.indexOf(a,this.pos);return b>-1?(this.pos=b,!0):void 0},backUp:function(a){this.pos-=a},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=Re(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue},indentation:function(){return Re(this.string,null,this.tabSize)},match:function(a,b,c){if("string"!=typeof a){var f=this.string.slice(this.pos).match(a);return f&&f.index>0?null:(f&&b!==!1&&(this.pos+=f[0].length),f)}var d=function(a){return c?a.toLowerCase():a},e=this.string.substr(this.pos,a.length);return d(e)==d(a)?(b!==!1&&(this.pos+=a.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)}},w.StringStream=jd,w.TextMarker=kd,kd.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;b&&Ab(a);for(var c=null,d=null,e=0;e<this.lines.length;++e){var f=this.lines[e],g=od(f.markedSpans,this);null!=g.to&&(d=je(f)),f.markedSpans=pd(f.markedSpans,g),null!=g.from?c=je(f):this.collapsed&&!Ad(this.doc,f)&&a&&ie(f,xb(a.display))}if(a&&this.collapsed&&!a.options.lineWrapping)for(var e=0;e<this.lines.length;++e){var h=zd(a.doc,this.lines[e]),i=G(a.doc,h);i>a.display.maxLineLength&&(a.display.maxLine=h,a.display.maxLineLength=i,a.display.maxLineChanged=!0)}null!=c&&a&&Fb(a,c,d+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Hc(a)),b&&Bb(a),Ke(this,"clear")}},kd.prototype.find=function(){for(var a,b,c=0;c<this.lines.length;++c){var d=this.lines[c],e=od(d.markedSpans,this);if(null!=e.from||null!=e.to){var f=je(d);null!=e.from&&(a=wc(f,e.from)),null!=e.to&&(b=wc(f,e.to))}}return"bookmark"==this.type?a:a&&{from:a,to:b}},kd.prototype.changed=function(){var a=this.find(),b=this.doc.cm;if(a&&b){var c=fe(this.doc,a.from.line);if(ib(b,c),a.from.line>=b.display.showingFrom&&a.from.line<b.display.showingTo){for(var d=b.display.lineDiv.firstChild;d;d=d.nextSibling)if(d.lineObj==c){d.offsetHeight!=c.height&&ie(c,d.offsetHeight);break}Eb(b,function(){b.curOp.selectionChanged=!0})}}},kd.prototype.attachLine=function(a){if(!this.lines.length&&this.doc.cm){var b=this.doc.cm.curOp;b.maybeHiddenMarkers&&-1!=We(b.maybeHiddenMarkers,this)||(b.maybeUnhiddenMarkers||(b.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(a)},kd.prototype.detachLine=function(a){if(this.lines.splice(We(this.lines,a),1),!this.lines.length&&this.doc.cm){var b=this.doc.cm.curOp;(b.maybeHiddenMarkers||(b.maybeHiddenMarkers=[])).push(this)}},w.SharedTextMarker=md,md.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var a=0;a<this.markers.length;++a)this.markers[a].clear();Ke(this,"clear")}},md.prototype.find=function(){return this.primary.find()};var Ed=w.LineWidget=function(a,b,c){for(var d in c)c.hasOwnProperty(d)&&(this[d]=c[d]);this.cm=a,this.node=b};Ed.prototype.clear=Fd(function(){var a=this.line.widgets,b=je(this.line);if(null!=b&&a){for(var c=0;c<a.length;++c)a[c]==this&&a.splice(c--,1);a.length||(this.line.widgets=null),ie(this.line,Math.max(0,this.line.height-Gd(this))),Fb(this.cm,b,b+1)}}),Ed.prototype.changed=Fd(function(){var a=this.height;this.height=null;var b=Gd(this)-a;if(b){ie(this.line,this.line.height+b);var c=je(this.line);Fb(this.cm,c,c+1)}});var Pd={},Sd=/[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;Zd.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var c=a,d=a+b;d>c;++c){var e=this.lines[c];this.height-=e.height,Kd(e),Ke(e,"delete")}this.lines.splice(a,b)},collapse:function(a){a.splice.apply(a,[a.length,0].concat(this.lines))},insertInner:function(a,b,c){this.height+=c,this.lines=this.lines.slice(0,a).concat(b).concat(this.lines.slice(a));for(var d=0,e=b.length;e>d;++d)b[d].parent=this},iterN:function(a,b,c){for(var d=a+b;d>a;++a)if(c(this.lines[a]))return!0}},$d.prototype={chunkSize:function(){return this.size},removeInner:function(a,b){this.size-=b;for(var c=0;c<this.children.length;++c){var d=this.children[c],e=d.chunkSize();if(e>a){var f=Math.min(b,e-a),g=d.height;if(d.removeInner(a,f),this.height-=g-d.height,e==f&&(this.children.splice(c--,1),d.parent=null),0==(b-=f))break;a=0}else a-=e}if(this.size-b<25){var h=[];this.collapse(h),this.children=[new Zd(h)],this.children[0].parent=this}},collapse:function(a){for(var b=0,c=this.children.length;c>b;++b)this.children[b].collapse(a)},insertInner:function(a,b,c){this.size+=b.length,this.height+=c;for(var d=0,e=this.children.length;e>d;++d){var f=this.children[d],g=f.chunkSize();if(g>=a){if(f.insertInner(a,b,c),f.lines&&f.lines.length>50){for(;f.lines.length>50;){var h=f.lines.splice(f.lines.length-25,25),i=new Zd(h);f.height-=i.height,this.children.splice(d+1,0,i),i.parent=this}this.maybeSpill()}break}a-=g}},maybeSpill:function(){if(!(this.children.length<=10)){var a=this;do{var b=a.children.splice(a.children.length-5,5),c=new $d(b);if(a.parent){a.size-=c.size,a.height-=c.height;var e=We(a.parent.children,a);a.parent.children.splice(e+1,0,c)}else{var d=new $d(a.children);d.parent=a,a.children=[d,c],a=d}c.parent=a.parent}while(a.children.length>10);a.parent.maybeSpill()}},iterN:function(a,b,c){for(var d=0,e=this.children.length;e>d;++d){var f=this.children[d],g=f.chunkSize();if(g>a){var h=Math.min(b,g-a);if(f.iterN(a,h,c))return!0;if(0==(b-=h))break;a=0}else a-=g}}};var _d=0,ae=w.Doc=function(a,b,c){if(!(this instanceof ae))return new ae(a,b,c);null==c&&(c=0),$d.call(this,[new Zd([Id("",null)])]),this.first=c,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.history=ne(),this.cleanGeneration=1,this.frontier=c;var d=wc(c,0);this.sel={from:d,to:d,head:d,anchor:d,shift:!1,extend:!1,goalColumn:null},this.id=++_d,this.modeOption=b,"string"==typeof a&&(a=pf(a)),Yd(this,{from:d,to:d,text:a},null,{head:d,anchor:d})};ae.prototype=Xe($d.prototype,{constructor:ae,iter:function(a,b,c){c?this.iterN(a-this.first,b-a,c):this.iterN(this.first,this.first+this.size,a)},insert:function(a,b){for(var c=0,d=0,e=b.length;e>d;++d)c+=b[d].height;this.insertInner(a-this.first,b,c)},remove:function(a,b){this.removeInner(a-this.first,b)},getValue:function(a){var b=he(this,this.first,this.first+this.size);return a===!1?b:b.join(a||"\n")},setValue:function(a){var b=wc(this.first,0),c=this.first+this.size-1;pc(this,{from:b,to:wc(c,fe(this,c).text.length),text:pf(a),origin:"setValue"},{head:b,anchor:b},!0)},replaceRange:function(a,b,c,d){b=Bc(this,b),c=c?Bc(this,c):b,vc(this,a,b,c,d)
11
},getRange:function(a,b,c){var d=ge(this,Bc(this,a),Bc(this,b));return c===!1?d:d.join(c||"\n")},getLine:function(a){var b=this.getLineHandle(a);return b&&b.text},setLine:function(a,b){Dc(this,a)&&vc(this,b,wc(a,0),Bc(this,wc(a)))},removeLine:function(a){a?vc(this,"",Bc(this,wc(a-1)),Bc(this,wc(a))):vc(this,"",wc(0,0),Bc(this,wc(1,0)))},getLineHandle:function(a){return Dc(this,a)?fe(this,a):void 0},getLineNumber:function(a){return je(a)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(a){return Bc(this,a)},getCursor:function(a){var c,b=this.sel;return c=null==a||"head"==a?b.head:"anchor"==a?b.anchor:"end"==a||a===!1?b.to:b.from,zc(c)},somethingSelected:function(){return!xc(this.sel.head,this.sel.anchor)},setCursor:Db(function(a,b,c){var d=Bc(this,"number"==typeof a?wc(a,b||0):a);c?Ec(this,d):Gc(this,d,d)}),setSelection:Db(function(a,b){Gc(this,Bc(this,a),Bc(this,b||a))}),extendSelection:Db(function(a,b){Ec(this,Bc(this,a),b&&Bc(this,b))}),getSelection:function(a){return this.getRange(this.sel.from,this.sel.to,a)},replaceSelection:function(a,b,c){pc(this,{from:this.sel.from,to:this.sel.to,text:pf(a),origin:c},b||"around")},undo:Db(function(){rc(this,"undo")}),redo:Db(function(){rc(this,"redo")}),setExtending:function(a){this.sel.extend=a},historySize:function(){var a=this.history;return{undo:a.done.length,redo:a.undone.length}},clearHistory:function(){this.history=ne(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration()},changeGeneration:function(){return this.history.lastOp=this.history.lastOrigin=null,this.history.generation},isClean:function(a){return this.history.generation==(a||this.cleanGeneration)},getHistory:function(){return{done:te(this.history.done),undone:te(this.history.undone)}},setHistory:function(a){var b=this.history=ne(this.history.maxGeneration);b.done=a.done.slice(0),b.undone=a.undone.slice(0)},markText:function(a,b,c){return ld(this,Bc(this,a),Bc(this,b),c,"range")},setBookmark:function(a,b){var c={replacedWith:b&&(null==b.nodeType?b.widget:b),insertLeft:b&&b.insertLeft};return a=Bc(this,a),ld(this,a,a,c,"bookmark")},findMarksAt:function(a){a=Bc(this,a);var b=[],c=fe(this,a.line).markedSpans;if(c)for(var d=0;d<c.length;++d){var e=c[d];(null==e.from||e.from<=a.ch)&&(null==e.to||e.to>=a.ch)&&b.push(e.marker.parent||e.marker)}return b},getAllMarks:function(){var a=[];return this.iter(function(b){var c=b.markedSpans;if(c)for(var d=0;d<c.length;++d)null!=c[d].from&&a.push(c[d].marker)}),a},posFromIndex:function(a){var b,c=this.first;return this.iter(function(d){var e=d.text.length+1;return e>a?(b=a,!0):(a-=e,++c,void 0)}),Bc(this,wc(c,b))},indexFromPos:function(a){a=Bc(this,a);var b=a.ch;return a.line<this.first||a.ch<0?0:(this.iter(this.first,a.line,function(a){b+=a.text.length+1}),b)},copy:function(a){var b=new ae(he(this,this.first,this.first+this.size),this.modeOption,this.first);return b.scrollTop=this.scrollTop,b.scrollLeft=this.scrollLeft,b.sel={from:this.sel.from,to:this.sel.to,head:this.sel.head,anchor:this.sel.anchor,shift:this.sel.shift,extend:!1,goalColumn:this.sel.goalColumn},a&&(b.history.undoDepth=this.history.undoDepth,b.setHistory(this.getHistory())),b},linkedDoc:function(a){a||(a={});var b=this.first,c=this.first+this.size;null!=a.from&&a.from>b&&(b=a.from),null!=a.to&&a.to<c&&(c=a.to);var d=new ae(he(this,b,c),a.mode||this.modeOption,b);return a.sharedHist&&(d.history=this.history),(this.linked||(this.linked=[])).push({doc:d,sharedHist:a.sharedHist}),d.linked=[{doc:this,isParent:!0,sharedHist:a.sharedHist}],d},unlinkDoc:function(a){if(a instanceof w&&(a=a.doc),this.linked)for(var b=0;b<this.linked.length;++b){var c=this.linked[b];if(c.doc==a){this.linked.splice(b,1),a.unlinkDoc(this);break}}if(a.history==this.history){var d=[a.id];de(a,function(a){d.push(a.id)},!0),a.history=ne(),a.history.done=te(this.history.done,d),a.history.undone=te(this.history.undone,d)}},iterLinkedDocs:function(a){de(this,a)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),ae.prototype.eachLine=ae.prototype.iter;var be="iter insert remove copy getEditor".split(" ");for(var ce in ae.prototype)ae.prototype.hasOwnProperty(ce)&&We(be,ce)<0&&(w.prototype[ce]=function(a){return function(){return a.apply(this.doc,arguments)}}(ae.prototype[ce]));w.e_stop=Ce,w.e_preventDefault=ze,w.e_stopPropagation=Ae;var Ie,Je=0;w.on=Fe,w.off=Ge,w.signal=He;var Oe=30,Pe=w.Pass={toString:function(){return"CodeMirror.Pass"}};Qe.prototype={set:function(a,b){clearTimeout(this.id),this.id=setTimeout(b,a)}},w.countColumn=Re;var Se=[""],_e=/[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,cf=/[\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]/;w.replaceGetRect=function(a){hf=a};var jf=function(){if(d)return!1;var a=df("div");return"draggable"in a||"dragDrop"in a}();a?kf=function(a,b){return 36==a.charCodeAt(b-1)&&39==a.charCodeAt(b)}:i&&!/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)?kf=function(a,b){return/\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(a.slice(b-1,b+1))}:e&&(kf=function(a,b){return b>1&&45==a.charCodeAt(b-1)&&/\w/.test(a.charAt(b-2))&&/[^\-?\.]/.test(a.charAt(b))?!0:/[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|\u2026[\w~`@#$%\^&*(_=+{[><]/.test(a.slice(b-1,b+1))});var lf,nf,pf=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,c=[],d=a.length;d>=b;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r");-1!=g?(c.push(f.slice(0,g)),b+=g+1):(c.push(f),b=e+1)}return c}:function(a){return a.split(/\r\n?|\n/)};w.splitLines=pf;var qf=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(c){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},rf=function(){var a=df("div");return"oncopy"in a?!0:(a.setAttribute("oncopy","return;"),"function"==typeof a.oncopy)}(),sf={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",91:"Mod",92:"Mod",93:"Mod",109:"-",107:"=",127:"Delete",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63276:"PageUp",63277:"PageDown",63275:"End",63273:"Home",63234:"Left",63232:"Up",63235:"Right",63233:"Down",63302:"Insert",63272:"Delete"};w.keyNames=sf,function(){for(var a=0;10>a;a++)sf[a+48]=String(a);for(var a=65;90>=a;a++)sf[a]=String.fromCharCode(a);for(var a=1;12>=a;a++)sf[a+111]=sf[a+63235]="F"+a}();var Bf,Gf=function(){function c(c){return 255>=c?a.charAt(c):c>=1424&&1524>=c?"R":c>=1536&&1791>=c?b.charAt(c-1536):c>=1792&&2220>=c?"r":"L"}var a="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL",b="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr",d=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,e=/[stwN]/,f=/[LRr]/,g=/[Lb1n]/,h=/[1n]/,i="L";return function(a){if(!d.test(a))return!1;for(var l,b=a.length,j=[],k=0;b>k;++k)j.push(l=c(a.charCodeAt(k)));for(var k=0,m=i;b>k;++k){var l=j[k];"m"==l?j[k]=m:m=l}for(var k=0,n=i;b>k;++k){var l=j[k];"1"==l&&"r"==n?j[k]="n":f.test(l)&&(n=l,"r"==l&&(j[k]="R"))}for(var k=1,m=j[0];b-1>k;++k){var l=j[k];"+"==l&&"1"==m&&"1"==j[k+1]?j[k]="1":","!=l||m!=j[k+1]||"1"!=m&&"n"!=m||(j[k]=m),m=l}for(var k=0;b>k;++k){var l=j[k];if(","==l)j[k]="N";else if("%"==l){for(var o=k+1;b>o&&"%"==j[o];++o);for(var p=k&&"!"==j[k-1]||b-1>o&&"1"==j[o]?"1":"N",q=k;o>q;++q)j[q]=p;k=o-1}}for(var k=0,n=i;b>k;++k){var l=j[k];"L"==n&&"1"==l?j[k]="L":f.test(l)&&(n=l)}for(var k=0;b>k;++k)if(e.test(j[k])){for(var o=k+1;b>o&&e.test(j[o]);++o);for(var r="L"==(k?j[k-1]:i),s="L"==(b-1>o?j[o]:i),p=r||s?"L":"R",q=k;o>q;++q)j[q]=p;k=o-1}for(var u,t=[],k=0;b>k;)if(g.test(j[k])){var v=k;for(++k;b>k&&g.test(j[k]);++k);t.push({from:v,to:k,level:0})}else{var w=k,x=t.length;for(++k;b>k&&"L"!=j[k];++k);for(var q=w;k>q;)if(h.test(j[q])){q>w&&t.splice(x,0,{from:w,to:q,level:1});var y=q;for(++q;k>q&&h.test(j[q]);++q);t.splice(x,0,{from:y,to:q,level:2}),w=q}else++q;k>w&&t.splice(x,0,{from:w,to:k,level:1})}return 1==t[0].level&&(u=a.match(/^\s+/))&&(t[0].from=u[0].length,t.unshift({from:0,to:u[0].length,level:0})),1==Ue(t).level&&(u=a.match(/\s+$/))&&(Ue(t).to-=u[0].length,t.push({from:b-u[0].length,to:b,level:0})),t[0].level!=Ue(t).level&&t.push({from:b,to:b,level:t[0].level}),t}}();return w.version="3.14.0",w}(),CodeMirror.runMode=function(a,b,c,d){var e=CodeMirror.getMode(CodeMirror.defaults,b),f=/MSIE \d/.test(navigator.userAgent),g=f&&(null==document.documentMode||document.documentMode<9);if(1==c.nodeType){var h=d&&d.tabSize||CodeMirror.defaults.tabSize,i=c,j=0;i.innerHTML="",c=function(a,b){if("\n"==a)return i.appendChild(document.createTextNode(g?"\r":a)),j=0,void 0;for(var c="",d=0;;){var e=a.indexOf("	",d);if(-1==e){c+=a.slice(d),j+=a.length-d;break}j+=e-d,c+=a.slice(d,e);var f=h-j%h;j+=f;for(var k=0;f>k;++k)c+=" ";d=e+1}if(b){var l=i.appendChild(document.createElement("span"));l.className="cm-"+b.replace(/ +/g," cm-"),l.appendChild(document.createTextNode(c))}else i.appendChild(document.createTextNode(c))}}for(var k=CodeMirror.splitLines(a),l=CodeMirror.startState(e),m=0,n=k.length;n>m;++m){m&&c("\n");for(var o=new CodeMirror.StringStream(k[m]);!o.eol();){var p=e.token(o,l);c(o.current(),p,m,o.start),o.start=o.pos}}};
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/codemirror.js (-5715 lines)
Lines 1-5715 Link Here
1
// CodeMirror version 3.14
2
//
3
// CodeMirror is the only global var we claim
4
window.CodeMirror = (function() {
5
  "use strict";
6
7
  // BROWSER SNIFFING
8
9
  // Crude, but necessary to handle a number of hard-to-feature-detect
10
  // bugs and behavior differences.
11
  var gecko = /gecko\/\d/i.test(navigator.userAgent);
12
  var ie = /MSIE \d/.test(navigator.userAgent);
13
  var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
14
  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
15
  var webkit = /WebKit\//.test(navigator.userAgent);
16
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
17
  var chrome = /Chrome\//.test(navigator.userAgent);
18
  var opera = /Opera\//.test(navigator.userAgent);
19
  var safari = /Apple Computer/.test(navigator.vendor);
20
  var khtml = /KHTML\//.test(navigator.userAgent);
21
  var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
22
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
23
  var phantom = /PhantomJS/.test(navigator.userAgent);
24
25
  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
26
  // This is woefully incomplete. Suggestions for alternative methods welcome.
27
  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
28
  var mac = ios || /Mac/.test(navigator.platform);
29
  var windows = /windows/i.test(navigator.platform);
30
31
  var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
32
  if (opera_version) opera_version = Number(opera_version[1]);
33
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
34
  var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
35
  var captureMiddleClick = gecko || (ie && !ie_lt9);
36
37
  // Optimize some code when these features are not used
38
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
39
40
  // CONSTRUCTOR
41
42
  function CodeMirror(place, options) {
43
    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
44
45
    this.options = options = options || {};
46
    // Determine effective options based on given values and defaults.
47
    for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
48
      options[opt] = defaults[opt];
49
    setGuttersForLineNumbers(options);
50
51
    var docStart = typeof options.value == "string" ? 0 : options.value.first;
52
    var display = this.display = makeDisplay(place, docStart);
53
    display.wrapper.CodeMirror = this;
54
    updateGutters(this);
55
    if (options.autofocus && !mobile) focusInput(this);
56
57
    this.state = {keyMaps: [],
58
                  overlays: [],
59
                  modeGen: 0,
60
                  overwrite: false, focused: false,
61
                  suppressEdits: false, pasteIncoming: false,
62
                  draggingText: false,
63
                  highlight: new Delayed()};
64
65
    themeChanged(this);
66
    if (options.lineWrapping)
67
      this.display.wrapper.className += " CodeMirror-wrap";
68
69
    var doc = options.value;
70
    if (typeof doc == "string") doc = new Doc(options.value, options.mode);
71
    operation(this, attachDoc)(this, doc);
72
73
    // Override magic textarea content restore that IE sometimes does
74
    // on our hidden textarea on reload
75
    if (ie) setTimeout(bind(resetInput, this, true), 20);
76
77
    registerEventHandlers(this);
78
    // IE throws unspecified error in certain cases, when
79
    // trying to access activeElement before onload
80
    var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
81
    if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
82
    else onBlur(this);
83
84
    operation(this, function() {
85
      for (var opt in optionHandlers)
86
        if (optionHandlers.propertyIsEnumerable(opt))
87
          optionHandlers[opt](this, options[opt], Init);
88
      for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
89
    })();
90
  }
91
92
  // DISPLAY CONSTRUCTOR
93
94
  function makeDisplay(place, docStart) {
95
    var d = {};
96
97
    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
98
    if (webkit) input.style.width = "1000px";
99
    else input.setAttribute("wrap", "off");
100
    // if border: 0; -- iOS fails to open keyboard (issue #1287)
101
    if (ios) input.style.border = "1px solid black";
102
    input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
103
104
    // Wraps and hides input textarea
105
    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
106
    // The actual fake scrollbars.
107
    d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
108
    d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
109
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
110
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
111
    // DIVs containing the selection and the actual code
112
    d.lineDiv = elt("div", null, "CodeMirror-code");
113
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
114
    // Blinky cursor, and element used to ensure cursor fits at the end of a line
115
    d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
116
    // Secondary cursor, shown when on a 'jump' in bi-directional text
117
    d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
118
    // Used to measure text size
119
    d.measure = elt("div", null, "CodeMirror-measure");
120
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
121
    d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
122
                         null, "position: relative; outline: none");
123
    // Moved around its parent to cover visible view
124
    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
125
    // Set to the height of the text, causes scrolling
126
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
127
    // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
128
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
129
    // Will contain the gutters, if any
130
    d.gutters = elt("div", null, "CodeMirror-gutters");
131
    d.lineGutter = null;
132
    // Provides scrolling
133
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
134
    d.scroller.setAttribute("tabIndex", "-1");
135
    // The element in which the editor lives.
136
    d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
137
                            d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
138
    // Work around IE7 z-index bug
139
    if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
140
    if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
141
142
    // Needed to hide big blue blinking cursor on Mobile Safari
143
    if (ios) input.style.width = "0px";
144
    if (!webkit) d.scroller.draggable = true;
145
    // Needed to handle Tab key in KHTML
146
    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
147
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
148
    else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
149
150
    // Current visible range (may be bigger than the view window).
151
    d.viewOffset = d.lastSizeC = 0;
152
    d.showingFrom = d.showingTo = docStart;
153
154
    // Used to only resize the line number gutter when necessary (when
155
    // the amount of lines crosses a boundary that makes its width change)
156
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
157
    // See readInput and resetInput
158
    d.prevInput = "";
159
    // Set to true when a non-horizontal-scrolling widget is added. As
160
    // an optimization, widget aligning is skipped when d is false.
161
    d.alignWidgets = false;
162
    // Flag that indicates whether we currently expect input to appear
163
    // (after some event like 'keypress' or 'input') and are polling
164
    // intensively.
165
    d.pollingFast = false;
166
    // Self-resetting timeout for the poller
167
    d.poll = new Delayed();
168
169
    d.cachedCharWidth = d.cachedTextHeight = null;
170
    d.measureLineCache = [];
171
    d.measureLineCachePos = 0;
172
173
    // Tracks when resetInput has punted to just putting a short
174
    // string instead of the (large) selection.
175
    d.inaccurateSelection = false;
176
177
    // Tracks the maximum line length so that the horizontal scrollbar
178
    // can be kept static when scrolling.
179
    d.maxLine = null;
180
    d.maxLineLength = 0;
181
    d.maxLineChanged = false;
182
183
    // Used for measuring wheel scrolling granularity
184
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
185
186
    return d;
187
  }
188
189
  // STATE UPDATES
190
191
  // Used to get the editor into a consistent state again when options change.
192
193
  function loadMode(cm) {
194
    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
195
    cm.doc.iter(function(line) {
196
      if (line.stateAfter) line.stateAfter = null;
197
      if (line.styles) line.styles = null;
198
    });
199
    cm.doc.frontier = cm.doc.first;
200
    startWorker(cm, 100);
201
    cm.state.modeGen++;
202
    if (cm.curOp) regChange(cm);
203
  }
204
205
  function wrappingChanged(cm) {
206
    if (cm.options.lineWrapping) {
207
      cm.display.wrapper.className += " CodeMirror-wrap";
208
      cm.display.sizer.style.minWidth = "";
209
    } else {
210
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
211
      computeMaxLength(cm);
212
    }
213
    estimateLineHeights(cm);
214
    regChange(cm);
215
    clearCaches(cm);
216
    setTimeout(function(){updateScrollbars(cm);}, 100);
217
  }
218
219
  function estimateHeight(cm) {
220
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
221
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
222
    return function(line) {
223
      if (lineIsHidden(cm.doc, line))
224
        return 0;
225
      else if (wrapping)
226
        return (Math.ceil(line.text.length / perLine) || 1) * th;
227
      else
228
        return th;
229
    };
230
  }
231
232
  function estimateLineHeights(cm) {
233
    var doc = cm.doc, est = estimateHeight(cm);
234
    doc.iter(function(line) {
235
      var estHeight = est(line);
236
      if (estHeight != line.height) updateLineHeight(line, estHeight);
237
    });
238
  }
239
240
  function keyMapChanged(cm) {
241
    var map = keyMap[cm.options.keyMap], style = map.style;
242
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
243
      (style ? " cm-keymap-" + style : "");
244
    cm.state.disableInput = map.disableInput;
245
  }
246
247
  function themeChanged(cm) {
248
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
249
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
250
    clearCaches(cm);
251
  }
252
253
  function guttersChanged(cm) {
254
    updateGutters(cm);
255
    regChange(cm);
256
    setTimeout(function(){alignHorizontally(cm);}, 20);
257
  }
258
259
  function updateGutters(cm) {
260
    var gutters = cm.display.gutters, specs = cm.options.gutters;
261
    removeChildren(gutters);
262
    for (var i = 0; i < specs.length; ++i) {
263
      var gutterClass = specs[i];
264
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
265
      if (gutterClass == "CodeMirror-linenumbers") {
266
        cm.display.lineGutter = gElt;
267
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
268
      }
269
    }
270
    gutters.style.display = i ? "" : "none";
271
  }
272
273
  function lineLength(doc, line) {
274
    if (line.height == 0) return 0;
275
    var len = line.text.length, merged, cur = line;
276
    while (merged = collapsedSpanAtStart(cur)) {
277
      var found = merged.find();
278
      cur = getLine(doc, found.from.line);
279
      len += found.from.ch - found.to.ch;
280
    }
281
    cur = line;
282
    while (merged = collapsedSpanAtEnd(cur)) {
283
      var found = merged.find();
284
      len -= cur.text.length - found.from.ch;
285
      cur = getLine(doc, found.to.line);
286
      len += cur.text.length - found.to.ch;
287
    }
288
    return len;
289
  }
290
291
  function computeMaxLength(cm) {
292
    var d = cm.display, doc = cm.doc;
293
    d.maxLine = getLine(doc, doc.first);
294
    d.maxLineLength = lineLength(doc, d.maxLine);
295
    d.maxLineChanged = true;
296
    doc.iter(function(line) {
297
      var len = lineLength(doc, line);
298
      if (len > d.maxLineLength) {
299
        d.maxLineLength = len;
300
        d.maxLine = line;
301
      }
302
    });
303
  }
304
305
  // Make sure the gutters options contains the element
306
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
307
  function setGuttersForLineNumbers(options) {
308
    var found = false;
309
    for (var i = 0; i < options.gutters.length; ++i) {
310
      if (options.gutters[i] == "CodeMirror-linenumbers") {
311
        if (options.lineNumbers) found = true;
312
        else options.gutters.splice(i--, 1);
313
      }
314
    }
315
    if (!found && options.lineNumbers)
316
      options.gutters.push("CodeMirror-linenumbers");
317
  }
318
319
  // SCROLLBARS
320
321
  // Re-synchronize the fake scrollbars with the actual size of the
322
  // content. Optionally force a scrollTop.
323
  function updateScrollbars(cm) {
324
    var d = cm.display, docHeight = cm.doc.height;
325
    var totalHeight = docHeight + paddingVert(d);
326
    d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
327
    d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
328
    var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
329
    var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
330
    var needsV = scrollHeight > (d.scroller.clientHeight + 1);
331
    if (needsV) {
332
      d.scrollbarV.style.display = "block";
333
      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
334
      d.scrollbarV.firstChild.style.height =
335
        (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
336
    } else d.scrollbarV.style.display = "";
337
    if (needsH) {
338
      d.scrollbarH.style.display = "block";
339
      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
340
      d.scrollbarH.firstChild.style.width =
341
        (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
342
    } else d.scrollbarH.style.display = "";
343
    if (needsH && needsV) {
344
      d.scrollbarFiller.style.display = "block";
345
      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
346
    } else d.scrollbarFiller.style.display = "";
347
    if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
348
      d.gutterFiller.style.display = "block";
349
      d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
350
      d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
351
    } else d.gutterFiller.style.display = "";
352
353
    if (mac_geLion && scrollbarWidth(d.measure) === 0)
354
      d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
355
  }
356
357
  function visibleLines(display, doc, viewPort) {
358
    var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
359
    if (typeof viewPort == "number") top = viewPort;
360
    else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
361
    top = Math.floor(top - paddingTop(display));
362
    var bottom = Math.ceil(top + height);
363
    return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
364
  }
365
366
  // LINE NUMBERS
367
368
  function alignHorizontally(cm) {
369
    var display = cm.display;
370
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
371
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
372
    var gutterW = display.gutters.offsetWidth, l = comp + "px";
373
    for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
374
      for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
375
    }
376
    if (cm.options.fixedGutter)
377
      display.gutters.style.left = (comp + gutterW) + "px";
378
  }
379
380
  function maybeUpdateLineNumberWidth(cm) {
381
    if (!cm.options.lineNumbers) return false;
382
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
383
    if (last.length != display.lineNumChars) {
384
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
385
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
386
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
387
      display.lineGutter.style.width = "";
388
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
389
      display.lineNumWidth = display.lineNumInnerWidth + padding;
390
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
391
      display.lineGutter.style.width = display.lineNumWidth + "px";
392
      return true;
393
    }
394
    return false;
395
  }
396
397
  function lineNumberFor(options, i) {
398
    return String(options.lineNumberFormatter(i + options.firstLineNumber));
399
  }
400
  function compensateForHScroll(display) {
401
    return getRect(display.scroller).left - getRect(display.sizer).left;
402
  }
403
404
  // DISPLAY DRAWING
405
406
  function updateDisplay(cm, changes, viewPort) {
407
    var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
408
    var visible = visibleLines(cm.display, cm.doc, viewPort);
409
    for (;;) {
410
      if (!updateDisplayInner(cm, changes, visible)) break;
411
      updated = true;
412
      updateSelection(cm);
413
      updateScrollbars(cm);
414
415
      // Clip forced viewport to actual scrollable area
416
      if (viewPort)
417
        viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
418
                            typeof viewPort == "number" ? viewPort : viewPort.top);
419
      visible = visibleLines(cm.display, cm.doc, viewPort);
420
      if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
421
        break;
422
      changes = [];
423
    }
424
425
    if (updated) {
426
      signalLater(cm, "update", cm);
427
      if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
428
        signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
429
    }
430
    return updated;
431
  }
432
433
  // Uses a set of changes plus the current scroll position to
434
  // determine which DOM updates have to be made, and makes the
435
  // updates.
436
  function updateDisplayInner(cm, changes, visible) {
437
    var display = cm.display, doc = cm.doc;
438
    if (!display.wrapper.clientWidth) {
439
      display.showingFrom = display.showingTo = doc.first;
440
      display.viewOffset = 0;
441
      return;
442
    }
443
444
    // Bail out if the visible area is already rendered and nothing changed.
445
    if (changes.length == 0 &&
446
        visible.from > display.showingFrom && visible.to < display.showingTo)
447
      return;
448
449
    if (maybeUpdateLineNumberWidth(cm))
450
      changes = [{from: doc.first, to: doc.first + doc.size}];
451
    var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
452
    display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
453
454
    // Used to determine which lines need their line numbers updated
455
    var positionsChangedFrom = Infinity;
456
    if (cm.options.lineNumbers)
457
      for (var i = 0; i < changes.length; ++i)
458
        if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
459
460
    var end = doc.first + doc.size;
461
    var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
462
    var to = Math.min(end, visible.to + cm.options.viewportMargin);
463
    if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
464
    if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
465
    if (sawCollapsedSpans) {
466
      from = lineNo(visualLine(doc, getLine(doc, from)));
467
      while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
468
    }
469
470
    // Create a range of theoretically intact lines, and punch holes
471
    // in that using the change info.
472
    var intact = [{from: Math.max(display.showingFrom, doc.first),
473
                   to: Math.min(display.showingTo, end)}];
474
    if (intact[0].from >= intact[0].to) intact = [];
475
    else intact = computeIntact(intact, changes);
476
    // When merged lines are present, we might have to reduce the
477
    // intact ranges because changes in continued fragments of the
478
    // intact lines do require the lines to be redrawn.
479
    if (sawCollapsedSpans)
480
      for (var i = 0; i < intact.length; ++i) {
481
        var range = intact[i], merged;
482
        while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
483
          var newTo = merged.find().from.line;
484
          if (newTo > range.from) range.to = newTo;
485
          else { intact.splice(i--, 1); break; }
486
        }
487
      }
488
489
    // Clip off the parts that won't be visible
490
    var intactLines = 0;
491
    for (var i = 0; i < intact.length; ++i) {
492
      var range = intact[i];
493
      if (range.from < from) range.from = from;
494
      if (range.to > to) range.to = to;
495
      if (range.from >= range.to) intact.splice(i--, 1);
496
      else intactLines += range.to - range.from;
497
    }
498
    if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
499
      updateViewOffset(cm);
500
      return;
501
    }
502
    intact.sort(function(a, b) {return a.from - b.from;});
503
504
    // Avoid crashing on IE's "unspecified error" when in iframes
505
    try {
506
      var focused = document.activeElement;
507
    } catch(e) {}
508
    if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
509
    patchDisplay(cm, from, to, intact, positionsChangedFrom);
510
    display.lineDiv.style.display = "";
511
    if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
512
513
    var different = from != display.showingFrom || to != display.showingTo ||
514
      display.lastSizeC != display.wrapper.clientHeight;
515
    // This is just a bogus formula that detects when the editor is
516
    // resized or the font size changes.
517
    if (different) {
518
      display.lastSizeC = display.wrapper.clientHeight;
519
      startWorker(cm, 400);
520
    }
521
    display.showingFrom = from; display.showingTo = to;
522
523
    var prevBottom = display.lineDiv.offsetTop;
524
    for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
525
      if (ie_lt8) {
526
        var bot = node.offsetTop + node.offsetHeight;
527
        height = bot - prevBottom;
528
        prevBottom = bot;
529
      } else {
530
        var box = getRect(node);
531
        height = box.bottom - box.top;
532
      }
533
      var diff = node.lineObj.height - height;
534
      if (height < 2) height = textHeight(display);
535
      if (diff > .001 || diff < -.001) {
536
        updateLineHeight(node.lineObj, height);
537
        var widgets = node.lineObj.widgets;
538
        if (widgets) for (var i = 0; i < widgets.length; ++i)
539
          widgets[i].height = widgets[i].node.offsetHeight;
540
      }
541
    }
542
    updateViewOffset(cm);
543
544
    return true;
545
  }
546
547
  function updateViewOffset(cm) {
548
    var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
549
    // Position the mover div to align with the current virtual scroll position
550
    cm.display.mover.style.top = off + "px";
551
  }
552
553
  function computeIntact(intact, changes) {
554
    for (var i = 0, l = changes.length || 0; i < l; ++i) {
555
      var change = changes[i], intact2 = [], diff = change.diff || 0;
556
      for (var j = 0, l2 = intact.length; j < l2; ++j) {
557
        var range = intact[j];
558
        if (change.to <= range.from && change.diff) {
559
          intact2.push({from: range.from + diff, to: range.to + diff});
560
        } else if (change.to <= range.from || change.from >= range.to) {
561
          intact2.push(range);
562
        } else {
563
          if (change.from > range.from)
564
            intact2.push({from: range.from, to: change.from});
565
          if (change.to < range.to)
566
            intact2.push({from: change.to + diff, to: range.to + diff});
567
        }
568
      }
569
      intact = intact2;
570
    }
571
    return intact;
572
  }
573
574
  function getDimensions(cm) {
575
    var d = cm.display, left = {}, width = {};
576
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
577
      left[cm.options.gutters[i]] = n.offsetLeft;
578
      width[cm.options.gutters[i]] = n.offsetWidth;
579
    }
580
    return {fixedPos: compensateForHScroll(d),
581
            gutterTotalWidth: d.gutters.offsetWidth,
582
            gutterLeft: left,
583
            gutterWidth: width,
584
            wrapperWidth: d.wrapper.clientWidth};
585
  }
586
587
  function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
588
    var dims = getDimensions(cm);
589
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
590
    if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
591
      removeChildren(display.lineDiv);
592
    var container = display.lineDiv, cur = container.firstChild;
593
594
    function rm(node) {
595
      var next = node.nextSibling;
596
      if (webkit && mac && cm.display.currentWheelTarget == node) {
597
        node.style.display = "none";
598
        node.lineObj = null;
599
      } else {
600
        node.parentNode.removeChild(node);
601
      }
602
      return next;
603
    }
604
605
    var nextIntact = intact.shift(), lineN = from;
606
    cm.doc.iter(from, to, function(line) {
607
      if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
608
      if (lineIsHidden(cm.doc, line)) {
609
        if (line.height != 0) updateLineHeight(line, 0);
610
        if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
611
          var w = line.widgets[i];
612
          if (w.showIfHidden) {
613
            var prev = cur.previousSibling;
614
            if (/pre/i.test(prev.nodeName)) {
615
              var wrap = elt("div", null, null, "position: relative");
616
              prev.parentNode.replaceChild(wrap, prev);
617
              wrap.appendChild(prev);
618
              prev = wrap;
619
            }
620
            var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
621
            if (!w.handleMouseEvents) wnode.ignoreEvents = true;
622
            positionLineWidget(w, wnode, prev, dims);
623
          }
624
        }
625
      } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
626
        // This line is intact. Skip to the actual node. Update its
627
        // line number if needed.
628
        while (cur.lineObj != line) cur = rm(cur);
629
        if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
630
          setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
631
        cur = cur.nextSibling;
632
      } else {
633
        // For lines with widgets, make an attempt to find and reuse
634
        // the existing element, so that widgets aren't needlessly
635
        // removed and re-inserted into the dom
636
        if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
637
          if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
638
        // This line needs to be generated.
639
        var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
640
        if (lineNode != reuse) {
641
          container.insertBefore(lineNode, cur);
642
        } else {
643
          while (cur != reuse) cur = rm(cur);
644
          cur = cur.nextSibling;
645
        }
646
647
        lineNode.lineObj = line;
648
      }
649
      ++lineN;
650
    });
651
    while (cur) cur = rm(cur);
652
  }
653
654
  function buildLineElement(cm, line, lineNo, dims, reuse) {
655
    var lineElement = lineContent(cm, line);
656
    var markers = line.gutterMarkers, display = cm.display, wrap;
657
658
    if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets)
659
      return lineElement;
660
661
    // Lines with gutter elements, widgets or a background class need
662
    // to be wrapped again, and have the extra elements added to the
663
    // wrapper div
664
665
    if (reuse) {
666
      reuse.alignable = null;
667
      var isOk = true, widgetsSeen = 0, insertBefore = null;
668
      for (var n = reuse.firstChild, next; n; n = next) {
669
        next = n.nextSibling;
670
        if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
671
          reuse.removeChild(n);
672
        } else {
673
          for (var i = 0, first = true; i < line.widgets.length; ++i) {
674
            var widget = line.widgets[i];
675
            if (!widget.above) { insertBefore = n; first = false; }
676
            if (widget.node == n.firstChild) {
677
              positionLineWidget(widget, n, reuse, dims);
678
              ++widgetsSeen;
679
              break;
680
            }
681
          }
682
          if (i == line.widgets.length) { isOk = false; break; }
683
        }
684
      }
685
      reuse.insertBefore(lineElement, insertBefore);
686
      if (isOk && widgetsSeen == line.widgets.length) {
687
        wrap = reuse;
688
        reuse.className = line.wrapClass || "";
689
      }
690
    }
691
    if (!wrap) {
692
      wrap = elt("div", null, line.wrapClass, "position: relative");
693
      wrap.appendChild(lineElement);
694
    }
695
    // Kludge to make sure the styled element lies behind the selection (by z-index)
696
    if (line.bgClass)
697
      wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild);
698
    if (cm.options.lineNumbers || markers) {
699
      var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
700
                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
701
                                         wrap.firstChild);
702
      if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
703
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
704
        wrap.lineNumber = gutterWrap.appendChild(
705
          elt("div", lineNumberFor(cm.options, lineNo),
706
              "CodeMirror-linenumber CodeMirror-gutter-elt",
707
              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
708
              + display.lineNumInnerWidth + "px"));
709
      if (markers)
710
        for (var k = 0; k < cm.options.gutters.length; ++k) {
711
          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
712
          if (found)
713
            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
714
                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
715
        }
716
    }
717
    if (ie_lt8) wrap.style.zIndex = 2;
718
    if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
719
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
720
      if (!widget.handleMouseEvents) node.ignoreEvents = true;
721
      positionLineWidget(widget, node, wrap, dims);
722
      if (widget.above)
723
        wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
724
      else
725
        wrap.appendChild(node);
726
      signalLater(widget, "redraw");
727
    }
728
    return wrap;
729
  }
730
731
  function positionLineWidget(widget, node, wrap, dims) {
732
    if (widget.noHScroll) {
733
      (wrap.alignable || (wrap.alignable = [])).push(node);
734
      var width = dims.wrapperWidth;
735
      node.style.left = dims.fixedPos + "px";
736
      if (!widget.coverGutter) {
737
        width -= dims.gutterTotalWidth;
738
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
739
      }
740
      node.style.width = width + "px";
741
    }
742
    if (widget.coverGutter) {
743
      node.style.zIndex = 5;
744
      node.style.position = "relative";
745
      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
746
    }
747
  }
748
749
  // SELECTION / CURSOR
750
751
  function updateSelection(cm) {
752
    var display = cm.display;
753
    var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
754
    if (collapsed || cm.options.showCursorWhenSelecting)
755
      updateSelectionCursor(cm);
756
    else
757
      display.cursor.style.display = display.otherCursor.style.display = "none";
758
    if (!collapsed)
759
      updateSelectionRange(cm);
760
    else
761
      display.selectionDiv.style.display = "none";
762
763
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
764
    if (cm.options.moveInputWithCursor) {
765
      var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
766
      var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
767
      display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
768
                                                        headPos.top + lineOff.top - wrapOff.top)) + "px";
769
      display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
770
                                                         headPos.left + lineOff.left - wrapOff.left)) + "px";
771
    }
772
  }
773
774
  // No selection, plain cursor
775
  function updateSelectionCursor(cm) {
776
    var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
777
    display.cursor.style.left = pos.left + "px";
778
    display.cursor.style.top = pos.top + "px";
779
    display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
780
    display.cursor.style.display = "";
781
782
    if (pos.other) {
783
      display.otherCursor.style.display = "";
784
      display.otherCursor.style.left = pos.other.left + "px";
785
      display.otherCursor.style.top = pos.other.top + "px";
786
      display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
787
    } else { display.otherCursor.style.display = "none"; }
788
  }
789
790
  // Highlight selection
791
  function updateSelectionRange(cm) {
792
    var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
793
    var fragment = document.createDocumentFragment();
794
    var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
795
796
    function add(left, top, width, bottom) {
797
      if (top < 0) top = 0;
798
      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
799
                               "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
800
                               "px; height: " + (bottom - top) + "px"));
801
    }
802
803
    function drawForLine(line, fromArg, toArg) {
804
      var lineObj = getLine(doc, line);
805
      var lineLen = lineObj.text.length;
806
      var start, end;
807
      function coords(ch, bias) {
808
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
809
      }
810
811
      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
812
        var leftPos = coords(from, "left"), rightPos, left, right;
813
        if (from == to) {
814
          rightPos = leftPos;
815
          left = right = leftPos.left;
816
        } else {
817
          rightPos = coords(to - 1, "right");
818
          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
819
          left = leftPos.left;
820
          right = rightPos.right;
821
        }
822
        if (fromArg == null && from == 0) left = pl;
823
        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
824
          add(left, leftPos.top, null, leftPos.bottom);
825
          left = pl;
826
          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
827
        }
828
        if (toArg == null && to == lineLen) right = clientWidth;
829
        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
830
          start = leftPos;
831
        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
832
          end = rightPos;
833
        if (left < pl + 1) left = pl;
834
        add(left, rightPos.top, right - left, rightPos.bottom);
835
      });
836
      return {start: start, end: end};
837
    }
838
839
    if (sel.from.line == sel.to.line) {
840
      drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
841
    } else {
842
      var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
843
      var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
844
      var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
845
      var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
846
      if (singleVLine) {
847
        if (leftEnd.top < rightStart.top - 2) {
848
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
849
          add(pl, rightStart.top, rightStart.left, rightStart.bottom);
850
        } else {
851
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
852
        }
853
      }
854
      if (leftEnd.bottom < rightStart.top)
855
        add(pl, leftEnd.bottom, null, rightStart.top);
856
    }
857
858
    removeChildrenAndAdd(display.selectionDiv, fragment);
859
    display.selectionDiv.style.display = "";
860
  }
861
862
  // Cursor-blinking
863
  function restartBlink(cm) {
864
    if (!cm.state.focused) return;
865
    var display = cm.display;
866
    clearInterval(display.blinker);
867
    var on = true;
868
    display.cursor.style.visibility = display.otherCursor.style.visibility = "";
869
    display.blinker = setInterval(function() {
870
      display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
871
    }, cm.options.cursorBlinkRate);
872
  }
873
874
  // HIGHLIGHT WORKER
875
876
  function startWorker(cm, time) {
877
    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
878
      cm.state.highlight.set(time, bind(highlightWorker, cm));
879
  }
880
881
  function highlightWorker(cm) {
882
    var doc = cm.doc;
883
    if (doc.frontier < doc.first) doc.frontier = doc.first;
884
    if (doc.frontier >= cm.display.showingTo) return;
885
    var end = +new Date + cm.options.workTime;
886
    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
887
    var changed = [], prevChange;
888
    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
889
      if (doc.frontier >= cm.display.showingFrom) { // Visible
890
        var oldStyles = line.styles;
891
        line.styles = highlightLine(cm, line, state);
892
        var ischange = !oldStyles || oldStyles.length != line.styles.length;
893
        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
894
        if (ischange) {
895
          if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
896
          else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
897
        }
898
        line.stateAfter = copyState(doc.mode, state);
899
      } else {
900
        processLine(cm, line, state);
901
        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
902
      }
903
      ++doc.frontier;
904
      if (+new Date > end) {
905
        startWorker(cm, cm.options.workDelay);
906
        return true;
907
      }
908
    });
909
    if (changed.length)
910
      operation(cm, function() {
911
        for (var i = 0; i < changed.length; ++i)
912
          regChange(this, changed[i].start, changed[i].end);
913
      })();
914
  }
915
916
  // Finds the line to start with when starting a parse. Tries to
917
  // find a line with a stateAfter, so that it can start with a
918
  // valid state. If that fails, it returns the line with the
919
  // smallest indentation, which tends to need the least context to
920
  // parse correctly.
921
  function findStartLine(cm, n, precise) {
922
    var minindent, minline, doc = cm.doc;
923
    for (var search = n, lim = n - 100; search > lim; --search) {
924
      if (search <= doc.first) return doc.first;
925
      var line = getLine(doc, search - 1);
926
      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
927
      var indented = countColumn(line.text, null, cm.options.tabSize);
928
      if (minline == null || minindent > indented) {
929
        minline = search - 1;
930
        minindent = indented;
931
      }
932
    }
933
    return minline;
934
  }
935
936
  function getStateBefore(cm, n, precise) {
937
    var doc = cm.doc, display = cm.display;
938
      if (!doc.mode.startState) return true;
939
    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
940
    if (!state) state = startState(doc.mode);
941
    else state = copyState(doc.mode, state);
942
    doc.iter(pos, n, function(line) {
943
      processLine(cm, line, state);
944
      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
945
      line.stateAfter = save ? copyState(doc.mode, state) : null;
946
      ++pos;
947
    });
948
    return state;
949
  }
950
951
  // POSITION MEASUREMENT
952
953
  function paddingTop(display) {return display.lineSpace.offsetTop;}
954
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
955
  function paddingLeft(display) {
956
    var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
957
    return e.offsetLeft;
958
  }
959
960
  function measureChar(cm, line, ch, data, bias) {
961
    var dir = -1;
962
    data = data || measureLine(cm, line);
963
964
    for (var pos = ch;; pos += dir) {
965
      var r = data[pos];
966
      if (r) break;
967
      if (dir < 0 && pos == 0) dir = 1;
968
    }
969
    var rightV = (pos < ch || bias == "right") && r.topRight != null;
970
    return {left: pos < ch ? r.right : r.left,
971
            right: pos > ch ? r.left : r.right,
972
            top: rightV ? r.topRight : r.top,
973
            bottom: rightV ? r.bottomRight : r.bottom};
974
  }
975
976
  function findCachedMeasurement(cm, line) {
977
    var cache = cm.display.measureLineCache;
978
    for (var i = 0; i < cache.length; ++i) {
979
      var memo = cache[i];
980
      if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
981
          cm.display.scroller.clientWidth == memo.width &&
982
          memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass)
983
        return memo;
984
    }
985
  }
986
987
  function clearCachedMeasurement(cm, line) {
988
    var exists = findCachedMeasurement(cm, line);
989
    if (exists) exists.text = exists.measure = exists.markedSpans = null;
990
  }
991
992
  function measureLine(cm, line) {
993
    // First look in the cache
994
    var cached = findCachedMeasurement(cm, line);
995
    if (cached) return cached.measure;
996
997
    // Failing that, recompute and store result in cache
998
    var measure = measureLineInner(cm, line);
999
    var cache = cm.display.measureLineCache;
1000
    var memo = {text: line.text, width: cm.display.scroller.clientWidth,
1001
                markedSpans: line.markedSpans, measure: measure,
1002
                classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass};
1003
    if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
1004
    else cache.push(memo);
1005
    return measure;
1006
  }
1007
1008
  function measureLineInner(cm, line) {
1009
    var display = cm.display, measure = emptyArray(line.text.length);
1010
    var pre = lineContent(cm, line, measure);
1011
1012
    // IE does not cache element positions of inline elements between
1013
    // calls to getBoundingClientRect. This makes the loop below,
1014
    // which gathers the positions of all the characters on the line,
1015
    // do an amount of layout work quadratic to the number of
1016
    // characters. When line wrapping is off, we try to improve things
1017
    // by first subdividing the line into a bunch of inline blocks, so
1018
    // that IE can reuse most of the layout information from caches
1019
    // for those blocks. This does interfere with line wrapping, so it
1020
    // doesn't work when wrapping is on, but in that case the
1021
    // situation is slightly better, since IE does cache line-wrapping
1022
    // information and only recomputes per-line.
1023
    if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
1024
      var fragment = document.createDocumentFragment();
1025
      var chunk = 10, n = pre.childNodes.length;
1026
      for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
1027
        var wrap = elt("div", null, null, "display: inline-block");
1028
        for (var j = 0; j < chunk && n; ++j) {
1029
          wrap.appendChild(pre.firstChild);
1030
          --n;
1031
        }
1032
        fragment.appendChild(wrap);
1033
      }
1034
      pre.appendChild(fragment);
1035
    }
1036
1037
    removeChildrenAndAdd(display.measure, pre);
1038
1039
    var outer = getRect(display.lineDiv);
1040
    var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
1041
    // Work around an IE7/8 bug where it will sometimes have randomly
1042
    // replaced our pre with a clone at this point.
1043
    if (ie_lt9 && display.measure.first != pre)
1044
      removeChildrenAndAdd(display.measure, pre);
1045
1046
    function categorizeVSpan(top, bot) {
1047
      if (bot > maxBot) bot = maxBot;
1048
      if (top < 0) top = 0;
1049
      for (var j = 0; j < vranges.length; j += 2) {
1050
        var rtop = vranges[j], rbot = vranges[j+1];
1051
        if (rtop > bot || rbot < top) continue;
1052
        if (rtop <= top && rbot >= bot ||
1053
            top <= rtop && bot >= rbot ||
1054
            Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
1055
          vranges[j] = Math.min(top, rtop);
1056
          vranges[j+1] = Math.max(bot, rbot);
1057
          return j;
1058
        }
1059
      }
1060
      vranges.push(top, bot);
1061
      return j;
1062
    }
1063
1064
    for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
1065
      var size, node = cur;
1066
      // A widget might wrap, needs special care
1067
      if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
1068
        if (cur.firstChild.nodeType == 1) node = cur.firstChild;
1069
        var rects = node.getClientRects(), rLeft = rects[0], rRight = rects[rects.length - 1];
1070
        if (rects.length > 1) {
1071
          var vCatLeft = categorizeVSpan(rLeft.top - outer.top, rLeft.bottom - outer.top);
1072
          var vCatRight = categorizeVSpan(rRight.top - outer.top, rRight.bottom - outer.top);
1073
          data[i] = {left: rLeft.left - outer.left, right: rRight.right - outer.left,
1074
                     top: vCatLeft, topRight: vCatRight};
1075
          continue;
1076
        }
1077
      }
1078
      size = getRect(node);
1079
      var vCat = categorizeVSpan(size.top - outer.top, size.bottom - outer.top);
1080
      var right = size.right;
1081
      if (cur.measureRight) right = getRect(cur.measureRight).left;
1082
      data[i] = {left: size.left - outer.left, right: right - outer.left, top: vCat};
1083
    }
1084
    for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
1085
      var vr = cur.top, vrRight = cur.topRight;
1086
      cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
1087
      if (vrRight != null) { cur.topRight = vranges[vrRight]; cur.bottomRight = vranges[vrRight+1]; }
1088
    }
1089
    return data;
1090
  }
1091
1092
  function measureLineWidth(cm, line) {
1093
    var hasBadSpan = false;
1094
    if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
1095
      var sp = line.markedSpans[i];
1096
      if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
1097
    }
1098
    var cached = !hasBadSpan && findCachedMeasurement(cm, line);
1099
    if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right;
1100
1101
    var pre = lineContent(cm, line);
1102
    var end = pre.appendChild(zeroWidthElement(cm.display.measure));
1103
    removeChildrenAndAdd(cm.display.measure, pre);
1104
    return getRect(end).right - getRect(cm.display.lineDiv).left;
1105
  }
1106
1107
  function clearCaches(cm) {
1108
    cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
1109
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
1110
    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1111
    cm.display.lineNumChars = null;
1112
  }
1113
1114
  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1115
  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1116
1117
  // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
1118
  function intoCoordSystem(cm, lineObj, rect, context) {
1119
    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1120
      var size = widgetHeight(lineObj.widgets[i]);
1121
      rect.top += size; rect.bottom += size;
1122
    }
1123
    if (context == "line") return rect;
1124
    if (!context) context = "local";
1125
    var yOff = heightAtLine(cm, lineObj);
1126
    if (context == "local") yOff += paddingTop(cm.display);
1127
    else yOff -= cm.display.viewOffset;
1128
    if (context == "page" || context == "window") {
1129
      var lOff = getRect(cm.display.lineSpace);
1130
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1131
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1132
      rect.left += xOff; rect.right += xOff;
1133
    }
1134
    rect.top += yOff; rect.bottom += yOff;
1135
    return rect;
1136
  }
1137
1138
  // Context may be "window", "page", "div", or "local"/null
1139
  // Result is in "div" coords
1140
  function fromCoordSystem(cm, coords, context) {
1141
    if (context == "div") return coords;
1142
    var left = coords.left, top = coords.top;
1143
    // First move into "page" coordinate system
1144
    if (context == "page") {
1145
      left -= pageScrollX();
1146
      top -= pageScrollY();
1147
    } else if (context == "local" || !context) {
1148
      var localBox = getRect(cm.display.sizer);
1149
      left += localBox.left;
1150
      top += localBox.top;
1151
    }
1152
1153
    var lineSpaceBox = getRect(cm.display.lineSpace);
1154
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1155
  }
1156
1157
  function charCoords(cm, pos, context, lineObj, bias) {
1158
    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1159
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
1160
  }
1161
1162
  function cursorCoords(cm, pos, context, lineObj, measurement) {
1163
    lineObj = lineObj || getLine(cm.doc, pos.line);
1164
    if (!measurement) measurement = measureLine(cm, lineObj);
1165
    function get(ch, right) {
1166
      var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
1167
      if (right) m.left = m.right; else m.right = m.left;
1168
      return intoCoordSystem(cm, lineObj, m, context);
1169
    }
1170
    function getBidi(ch, partPos) {
1171
      var part = order[partPos], right = part.level % 2;
1172
      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1173
        part = order[--partPos];
1174
        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1175
        right = true;
1176
      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1177
        part = order[++partPos];
1178
        ch = bidiLeft(part) - part.level % 2;
1179
        right = false;
1180
      }
1181
      if (right && ch == part.to && ch > part.from) return get(ch - 1);
1182
      return get(ch, right);
1183
    }
1184
    var order = getOrder(lineObj), ch = pos.ch;
1185
    if (!order) return get(ch);
1186
    var partPos = getBidiPartAt(order, ch);
1187
    var val = getBidi(ch, partPos);
1188
    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1189
    return val;
1190
  }
1191
1192
  function PosWithInfo(line, ch, outside, xRel) {
1193
    var pos = new Pos(line, ch);
1194
    pos.xRel = xRel;
1195
    if (outside) pos.outside = true;
1196
    return pos;
1197
  }
1198
1199
  // Coords must be lineSpace-local
1200
  function coordsChar(cm, x, y) {
1201
    var doc = cm.doc;
1202
    y += cm.display.viewOffset;
1203
    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1204
    var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1205
    if (lineNo > last)
1206
      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1207
    if (x < 0) x = 0;
1208
1209
    for (;;) {
1210
      var lineObj = getLine(doc, lineNo);
1211
      var found = coordsCharInner(cm, lineObj, lineNo, x, y);
1212
      var merged = collapsedSpanAtEnd(lineObj);
1213
      var mergedPos = merged && merged.find();
1214
      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1215
        lineNo = mergedPos.to.line;
1216
      else
1217
        return found;
1218
    }
1219
  }
1220
1221
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
1222
    var innerOff = y - heightAtLine(cm, lineObj);
1223
    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1224
    var measurement = measureLine(cm, lineObj);
1225
1226
    function getX(ch) {
1227
      var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
1228
                            lineObj, measurement);
1229
      wrongLine = true;
1230
      if (innerOff > sp.bottom) return sp.left - adjust;
1231
      else if (innerOff < sp.top) return sp.left + adjust;
1232
      else wrongLine = false;
1233
      return sp.left;
1234
    }
1235
1236
    var bidi = getOrder(lineObj), dist = lineObj.text.length;
1237
    var from = lineLeft(lineObj), to = lineRight(lineObj);
1238
    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1239
1240
    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1241
    // Do a binary search between these bounds.
1242
    for (;;) {
1243
      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1244
        var ch = x < fromX || x - fromX <= toX - x ? from : to;
1245
        var xDiff = x - (ch == from ? fromX : toX);
1246
        while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
1247
        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1248
                              xDiff < 0 ? -1 : xDiff ? 1 : 0);
1249
        return pos;
1250
      }
1251
      var step = Math.ceil(dist / 2), middle = from + step;
1252
      if (bidi) {
1253
        middle = from;
1254
        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1255
      }
1256
      var middleX = getX(middle);
1257
      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1258
      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1259
    }
1260
  }
1261
1262
  var measureText;
1263
  function textHeight(display) {
1264
    if (display.cachedTextHeight != null) return display.cachedTextHeight;
1265
    if (measureText == null) {
1266
      measureText = elt("pre");
1267
      // Measure a bunch of lines, for browsers that compute
1268
      // fractional heights.
1269
      for (var i = 0; i < 49; ++i) {
1270
        measureText.appendChild(document.createTextNode("x"));
1271
        measureText.appendChild(elt("br"));
1272
      }
1273
      measureText.appendChild(document.createTextNode("x"));
1274
    }
1275
    removeChildrenAndAdd(display.measure, measureText);
1276
    var height = measureText.offsetHeight / 50;
1277
    if (height > 3) display.cachedTextHeight = height;
1278
    removeChildren(display.measure);
1279
    return height || 1;
1280
  }
1281
1282
  function charWidth(display) {
1283
    if (display.cachedCharWidth != null) return display.cachedCharWidth;
1284
    var anchor = elt("span", "x");
1285
    var pre = elt("pre", [anchor]);
1286
    removeChildrenAndAdd(display.measure, pre);
1287
    var width = anchor.offsetWidth;
1288
    if (width > 2) display.cachedCharWidth = width;
1289
    return width || 10;
1290
  }
1291
1292
  // OPERATIONS
1293
1294
  // Operations are used to wrap changes in such a way that each
1295
  // change won't have to update the cursor and display (which would
1296
  // be awkward, slow, and error-prone), but instead updates are
1297
  // batched and then all combined and executed at once.
1298
1299
  var nextOpId = 0;
1300
  function startOperation(cm) {
1301
    cm.curOp = {
1302
      // An array of ranges of lines that have to be updated. See
1303
      // updateDisplay.
1304
      changes: [],
1305
      updateInput: null,
1306
      userSelChange: null,
1307
      textChanged: null,
1308
      selectionChanged: false,
1309
      cursorActivity: false,
1310
      updateMaxLine: false,
1311
      updateScrollPos: false,
1312
      id: ++nextOpId
1313
    };
1314
    if (!delayedCallbackDepth++) delayedCallbacks = [];
1315
  }
1316
1317
  function endOperation(cm) {
1318
    var op = cm.curOp, doc = cm.doc, display = cm.display;
1319
    cm.curOp = null;
1320
1321
    if (op.updateMaxLine) computeMaxLength(cm);
1322
    if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
1323
      var width = measureLineWidth(cm, display.maxLine);
1324
      display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
1325
      display.maxLineChanged = false;
1326
      var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
1327
      if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
1328
        setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
1329
    }
1330
    var newScrollPos, updated;
1331
    if (op.updateScrollPos) {
1332
      newScrollPos = op.updateScrollPos;
1333
    } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
1334
      var coords = cursorCoords(cm, doc.sel.head);
1335
      newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
1336
    }
1337
    if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) {
1338
      updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
1339
      if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1340
    }
1341
    if (!updated && op.selectionChanged) updateSelection(cm);
1342
    if (op.updateScrollPos) {
1343
      display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
1344
      display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
1345
      alignHorizontally(cm);
1346
      if (op.scrollToPos)
1347
        scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
1348
    } else if (newScrollPos) {
1349
      scrollCursorIntoView(cm);
1350
    }
1351
    if (op.selectionChanged) restartBlink(cm);
1352
1353
    if (cm.state.focused && op.updateInput)
1354
      resetInput(cm, op.userSelChange);
1355
1356
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1357
    if (hidden) for (var i = 0; i < hidden.length; ++i)
1358
      if (!hidden[i].lines.length) signal(hidden[i], "hide");
1359
    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1360
      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1361
1362
    var delayed;
1363
    if (!--delayedCallbackDepth) {
1364
      delayed = delayedCallbacks;
1365
      delayedCallbacks = null;
1366
    }
1367
    if (op.textChanged)
1368
      signal(cm, "change", cm, op.textChanged);
1369
    if (op.cursorActivity) signal(cm, "cursorActivity", cm);
1370
    if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1371
  }
1372
1373
  // Wraps a function in an operation. Returns the wrapped function.
1374
  function operation(cm1, f) {
1375
    return function() {
1376
      var cm = cm1 || this, withOp = !cm.curOp;
1377
      if (withOp) startOperation(cm);
1378
      try { var result = f.apply(cm, arguments); }
1379
      finally { if (withOp) endOperation(cm); }
1380
      return result;
1381
    };
1382
  }
1383
  function docOperation(f) {
1384
    return function() {
1385
      var withOp = this.cm && !this.cm.curOp, result;
1386
      if (withOp) startOperation(this.cm);
1387
      try { result = f.apply(this, arguments); }
1388
      finally { if (withOp) endOperation(this.cm); }
1389
      return result;
1390
    };
1391
  }
1392
  function runInOp(cm, f) {
1393
    var withOp = !cm.curOp, result;
1394
    if (withOp) startOperation(cm);
1395
    try { result = f(); }
1396
    finally { if (withOp) endOperation(cm); }
1397
    return result;
1398
  }
1399
1400
  function regChange(cm, from, to, lendiff) {
1401
    if (from == null) from = cm.doc.first;
1402
    if (to == null) to = cm.doc.first + cm.doc.size;
1403
    cm.curOp.changes.push({from: from, to: to, diff: lendiff});
1404
  }
1405
1406
  // INPUT HANDLING
1407
1408
  function slowPoll(cm) {
1409
    if (cm.display.pollingFast) return;
1410
    cm.display.poll.set(cm.options.pollInterval, function() {
1411
      readInput(cm);
1412
      if (cm.state.focused) slowPoll(cm);
1413
    });
1414
  }
1415
1416
  function fastPoll(cm) {
1417
    var missed = false;
1418
    cm.display.pollingFast = true;
1419
    function p() {
1420
      var changed = readInput(cm);
1421
      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
1422
      else {cm.display.pollingFast = false; slowPoll(cm);}
1423
    }
1424
    cm.display.poll.set(20, p);
1425
  }
1426
1427
  // prevInput is a hack to work with IME. If we reset the textarea
1428
  // on every change, that breaks IME. So we look for changes
1429
  // compared to the previous content instead. (Modern browsers have
1430
  // events that indicate IME taking place, but these are not widely
1431
  // supported or compatible enough yet to rely on.)
1432
  function readInput(cm) {
1433
    var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
1434
    if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
1435
    var text = input.value;
1436
    if (text == prevInput && posEq(sel.from, sel.to)) return false;
1437
    if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
1438
      resetInput(cm, true);
1439
      return false;
1440
    }
1441
1442
    var withOp = !cm.curOp;
1443
    if (withOp) startOperation(cm);
1444
    sel.shift = false;
1445
    var same = 0, l = Math.min(prevInput.length, text.length);
1446
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1447
    var from = sel.from, to = sel.to;
1448
    if (same < prevInput.length)
1449
      from = Pos(from.line, from.ch - (prevInput.length - same));
1450
    else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
1451
      to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
1452
1453
    var updateInput = cm.curOp.updateInput;
1454
    var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
1455
                       origin: cm.state.pasteIncoming ? "paste" : "+input"};
1456
    makeChange(cm.doc, changeEvent, "end");
1457
    cm.curOp.updateInput = updateInput;
1458
    signalLater(cm, "inputRead", cm, changeEvent);
1459
1460
    if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
1461
    else cm.display.prevInput = text;
1462
    if (withOp) endOperation(cm);
1463
    cm.state.pasteIncoming = false;
1464
    return true;
1465
  }
1466
1467
  function resetInput(cm, user) {
1468
    var minimal, selected, doc = cm.doc;
1469
    if (!posEq(doc.sel.from, doc.sel.to)) {
1470
      cm.display.prevInput = "";
1471
      minimal = hasCopyEvent &&
1472
        (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
1473
      var content = minimal ? "-" : selected || cm.getSelection();
1474
      cm.display.input.value = content;
1475
      if (cm.state.focused) selectInput(cm.display.input);
1476
      if (ie && !ie_lt9) cm.display.inputHasSelection = content;
1477
    } else if (user) {
1478
      cm.display.prevInput = cm.display.input.value = "";
1479
      if (ie && !ie_lt9) cm.display.inputHasSelection = null;
1480
    }
1481
    cm.display.inaccurateSelection = minimal;
1482
  }
1483
1484
  function focusInput(cm) {
1485
    if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
1486
      cm.display.input.focus();
1487
  }
1488
1489
  function isReadOnly(cm) {
1490
    return cm.options.readOnly || cm.doc.cantEdit;
1491
  }
1492
1493
  // EVENT HANDLERS
1494
1495
  function registerEventHandlers(cm) {
1496
    var d = cm.display;
1497
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
1498
    if (ie)
1499
      on(d.scroller, "dblclick", operation(cm, function(e) {
1500
        if (signalDOMEvent(cm, e)) return;
1501
        var pos = posFromMouse(cm, e);
1502
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
1503
        e_preventDefault(e);
1504
        var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
1505
        extendSelection(cm.doc, word.from, word.to);
1506
      }));
1507
    else
1508
      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
1509
    on(d.lineSpace, "selectstart", function(e) {
1510
      if (!eventInWidget(d, e)) e_preventDefault(e);
1511
    });
1512
    // Gecko browsers fire contextmenu *after* opening the menu, at
1513
    // which point we can't mess with it anymore. Context menu is
1514
    // handled in onMouseDown for Gecko.
1515
    if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
1516
1517
    on(d.scroller, "scroll", function() {
1518
      if (d.scroller.clientHeight) {
1519
        setScrollTop(cm, d.scroller.scrollTop);
1520
        setScrollLeft(cm, d.scroller.scrollLeft, true);
1521
        signal(cm, "scroll", cm);
1522
      }
1523
    });
1524
    on(d.scrollbarV, "scroll", function() {
1525
      if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
1526
    });
1527
    on(d.scrollbarH, "scroll", function() {
1528
      if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
1529
    });
1530
1531
    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
1532
    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
1533
1534
    function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
1535
    on(d.scrollbarH, "mousedown", reFocus);
1536
    on(d.scrollbarV, "mousedown", reFocus);
1537
    // Prevent wrapper from ever scrolling
1538
    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
1539
1540
    var resizeTimer;
1541
    function onResize() {
1542
      if (resizeTimer == null) resizeTimer = setTimeout(function() {
1543
        resizeTimer = null;
1544
        // Might be a text scaling operation, clear size caches.
1545
        d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
1546
        clearCaches(cm);
1547
        runInOp(cm, bind(regChange, cm));
1548
      }, 100);
1549
    }
1550
    on(window, "resize", onResize);
1551
    // Above handler holds on to the editor and its data structures.
1552
    // Here we poll to unregister it when the editor is no longer in
1553
    // the document, so that it can be garbage-collected.
1554
    function unregister() {
1555
      for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
1556
      if (p) setTimeout(unregister, 5000);
1557
      else off(window, "resize", onResize);
1558
    }
1559
    setTimeout(unregister, 5000);
1560
1561
    on(d.input, "keyup", operation(cm, function(e) {
1562
      if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
1563
      if (e.keyCode == 16) cm.doc.sel.shift = false;
1564
    }));
1565
    on(d.input, "input", bind(fastPoll, cm));
1566
    on(d.input, "keydown", operation(cm, onKeyDown));
1567
    on(d.input, "keypress", operation(cm, onKeyPress));
1568
    on(d.input, "focus", bind(onFocus, cm));
1569
    on(d.input, "blur", bind(onBlur, cm));
1570
1571
    function drag_(e) {
1572
      if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
1573
      e_stop(e);
1574
    }
1575
    if (cm.options.dragDrop) {
1576
      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
1577
      on(d.scroller, "dragenter", drag_);
1578
      on(d.scroller, "dragover", drag_);
1579
      on(d.scroller, "drop", operation(cm, onDrop));
1580
    }
1581
    on(d.scroller, "paste", function(e){
1582
      if (eventInWidget(d, e)) return;
1583
      focusInput(cm);
1584
      fastPoll(cm);
1585
    });
1586
    on(d.input, "paste", function() {
1587
      cm.state.pasteIncoming = true;
1588
      fastPoll(cm);
1589
    });
1590
1591
    function prepareCopy() {
1592
      if (d.inaccurateSelection) {
1593
        d.prevInput = "";
1594
        d.inaccurateSelection = false;
1595
        d.input.value = cm.getSelection();
1596
        selectInput(d.input);
1597
      }
1598
    }
1599
    on(d.input, "cut", prepareCopy);
1600
    on(d.input, "copy", prepareCopy);
1601
1602
    // Needed to handle Tab key in KHTML
1603
    if (khtml) on(d.sizer, "mouseup", function() {
1604
        if (document.activeElement == d.input) d.input.blur();
1605
        focusInput(cm);
1606
    });
1607
  }
1608
1609
  function eventInWidget(display, e) {
1610
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
1611
      if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
1612
    }
1613
  }
1614
1615
  function posFromMouse(cm, e, liberal) {
1616
    var display = cm.display;
1617
    if (!liberal) {
1618
      var target = e_target(e);
1619
      if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
1620
          target == display.scrollbarV || target == display.scrollbarV.firstChild ||
1621
          target == display.scrollbarFiller || target == display.gutterFiller) return null;
1622
    }
1623
    var x, y, space = getRect(display.lineSpace);
1624
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1625
    try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1626
    return coordsChar(cm, x - space.left, y - space.top);
1627
  }
1628
1629
  var lastClick, lastDoubleClick;
1630
  function onMouseDown(e) {
1631
    if (signalDOMEvent(this, e)) return;
1632
    var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
1633
    sel.shift = e.shiftKey;
1634
1635
    if (eventInWidget(display, e)) {
1636
      if (!webkit) {
1637
        display.scroller.draggable = false;
1638
        setTimeout(function(){display.scroller.draggable = true;}, 100);
1639
      }
1640
      return;
1641
    }
1642
    if (clickInGutter(cm, e)) return;
1643
    var start = posFromMouse(cm, e);
1644
1645
    switch (e_button(e)) {
1646
    case 3:
1647
      if (captureMiddleClick) onContextMenu.call(cm, cm, e);
1648
      return;
1649
    case 2:
1650
      if (start) extendSelection(cm.doc, start);
1651
      setTimeout(bind(focusInput, cm), 20);
1652
      e_preventDefault(e);
1653
      return;
1654
    }
1655
    // For button 1, if it was clicked inside the editor
1656
    // (posFromMouse returning non-null), we have to adjust the
1657
    // selection.
1658
    if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
1659
1660
    if (!cm.state.focused) onFocus(cm);
1661
1662
    var now = +new Date, type = "single";
1663
    if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
1664
      type = "triple";
1665
      e_preventDefault(e);
1666
      setTimeout(bind(focusInput, cm), 20);
1667
      selectLine(cm, start.line);
1668
    } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
1669
      type = "double";
1670
      lastDoubleClick = {time: now, pos: start};
1671
      e_preventDefault(e);
1672
      var word = findWordAt(getLine(doc, start.line).text, start);
1673
      extendSelection(cm.doc, word.from, word.to);
1674
    } else { lastClick = {time: now, pos: start}; }
1675
1676
    var last = start;
1677
    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
1678
        !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
1679
      var dragEnd = operation(cm, function(e2) {
1680
        if (webkit) display.scroller.draggable = false;
1681
        cm.state.draggingText = false;
1682
        off(document, "mouseup", dragEnd);
1683
        off(display.scroller, "drop", dragEnd);
1684
        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
1685
          e_preventDefault(e2);
1686
          extendSelection(cm.doc, start);
1687
          focusInput(cm);
1688
        }
1689
      });
1690
      // Let the drag handler handle this.
1691
      if (webkit) display.scroller.draggable = true;
1692
      cm.state.draggingText = dragEnd;
1693
      // IE's approach to draggable
1694
      if (display.scroller.dragDrop) display.scroller.dragDrop();
1695
      on(document, "mouseup", dragEnd);
1696
      on(display.scroller, "drop", dragEnd);
1697
      return;
1698
    }
1699
    e_preventDefault(e);
1700
    if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
1701
1702
    var startstart = sel.from, startend = sel.to, lastPos = start;
1703
1704
    function doSelect(cur) {
1705
      if (posEq(lastPos, cur)) return;
1706
      lastPos = cur;
1707
1708
      if (type == "single") {
1709
        extendSelection(cm.doc, clipPos(doc, start), cur);
1710
        return;
1711
      }
1712
1713
      startstart = clipPos(doc, startstart);
1714
      startend = clipPos(doc, startend);
1715
      if (type == "double") {
1716
        var word = findWordAt(getLine(doc, cur.line).text, cur);
1717
        if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
1718
        else extendSelection(cm.doc, startstart, word.to);
1719
      } else if (type == "triple") {
1720
        if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
1721
        else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
1722
      }
1723
    }
1724
1725
    var editorSize = getRect(display.wrapper);
1726
    // Used to ensure timeout re-tries don't fire when another extend
1727
    // happened in the meantime (clearTimeout isn't reliable -- at
1728
    // least on Chrome, the timeouts still happen even when cleared,
1729
    // if the clear happens after their scheduled firing time).
1730
    var counter = 0;
1731
1732
    function extend(e) {
1733
      var curCount = ++counter;
1734
      var cur = posFromMouse(cm, e, true);
1735
      if (!cur) return;
1736
      if (!posEq(cur, last)) {
1737
        if (!cm.state.focused) onFocus(cm);
1738
        last = cur;
1739
        doSelect(cur);
1740
        var visible = visibleLines(display, doc);
1741
        if (cur.line >= visible.to || cur.line < visible.from)
1742
          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
1743
      } else {
1744
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
1745
        if (outside) setTimeout(operation(cm, function() {
1746
          if (counter != curCount) return;
1747
          display.scroller.scrollTop += outside;
1748
          extend(e);
1749
        }), 50);
1750
      }
1751
    }
1752
1753
    function done(e) {
1754
      counter = Infinity;
1755
      e_preventDefault(e);
1756
      focusInput(cm);
1757
      off(document, "mousemove", move);
1758
      off(document, "mouseup", up);
1759
    }
1760
1761
    var move = operation(cm, function(e) {
1762
      if (!ie && !e_button(e)) done(e);
1763
      else extend(e);
1764
    });
1765
    var up = operation(cm, done);
1766
    on(document, "mousemove", move);
1767
    on(document, "mouseup", up);
1768
  }
1769
1770
  function clickInGutter(cm, e) {
1771
    var display = cm.display;
1772
    try { var mX = e.clientX, mY = e.clientY; }
1773
    catch(e) { return false; }
1774
1775
    if (mX >= Math.floor(getRect(display.gutters).right)) return false;
1776
    e_preventDefault(e);
1777
    if (!hasHandler(cm, "gutterClick")) return true;
1778
1779
    var lineBox = getRect(display.lineDiv);
1780
    if (mY > lineBox.bottom) return true;
1781
    mY -= lineBox.top - display.viewOffset;
1782
1783
    for (var i = 0; i < cm.options.gutters.length; ++i) {
1784
      var g = display.gutters.childNodes[i];
1785
      if (g && getRect(g).right >= mX) {
1786
        var line = lineAtHeight(cm.doc, mY);
1787
        var gutter = cm.options.gutters[i];
1788
        signalLater(cm, "gutterClick", cm, line, gutter, e);
1789
        break;
1790
      }
1791
    }
1792
    return true;
1793
  }
1794
1795
  // Kludge to work around strange IE behavior where it'll sometimes
1796
  // re-fire a series of drag-related events right after the drop (#1551)
1797
  var lastDrop = 0;
1798
1799
  function onDrop(e) {
1800
    var cm = this;
1801
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
1802
      return;
1803
    e_preventDefault(e);
1804
    if (ie) lastDrop = +new Date;
1805
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
1806
    if (!pos || isReadOnly(cm)) return;
1807
    if (files && files.length && window.FileReader && window.File) {
1808
      var n = files.length, text = Array(n), read = 0;
1809
      var loadFile = function(file, i) {
1810
        var reader = new FileReader;
1811
        reader.onload = function() {
1812
          text[i] = reader.result;
1813
          if (++read == n) {
1814
            pos = clipPos(cm.doc, pos);
1815
            makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
1816
          }
1817
        };
1818
        reader.readAsText(file);
1819
      };
1820
      for (var i = 0; i < n; ++i) loadFile(files[i], i);
1821
    } else {
1822
      // Don't do a replace if the drop happened inside of the selected text.
1823
      if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
1824
        cm.state.draggingText(e);
1825
        // Ensure the editor is re-focused
1826
        setTimeout(bind(focusInput, cm), 20);
1827
        return;
1828
      }
1829
      try {
1830
        var text = e.dataTransfer.getData("Text");
1831
        if (text) {
1832
          var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
1833
          setSelection(cm.doc, pos, pos);
1834
          if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
1835
          cm.replaceSelection(text, null, "paste");
1836
          focusInput(cm);
1837
          onFocus(cm);
1838
        }
1839
      }
1840
      catch(e){}
1841
    }
1842
  }
1843
1844
  function onDragStart(cm, e) {
1845
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
1846
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
1847
1848
    var txt = cm.getSelection();
1849
    e.dataTransfer.setData("Text", txt);
1850
1851
    // Use dummy image instead of default browsers image.
1852
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
1853
    if (e.dataTransfer.setDragImage && !safari) {
1854
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
1855
      if (opera) {
1856
        img.width = img.height = 1;
1857
        cm.display.wrapper.appendChild(img);
1858
        // Force a relayout, or Opera won't use our image for some obscure reason
1859
        img._top = img.offsetTop;
1860
      }
1861
      e.dataTransfer.setDragImage(img, 0, 0);
1862
      if (opera) img.parentNode.removeChild(img);
1863
    }
1864
  }
1865
1866
  function setScrollTop(cm, val) {
1867
    if (Math.abs(cm.doc.scrollTop - val) < 2) return;
1868
    cm.doc.scrollTop = val;
1869
    if (!gecko) updateDisplay(cm, [], val);
1870
    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
1871
    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
1872
    if (gecko) updateDisplay(cm, []);
1873
    startWorker(cm, 100);
1874
  }
1875
  function setScrollLeft(cm, val, isScroller) {
1876
    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
1877
    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
1878
    cm.doc.scrollLeft = val;
1879
    alignHorizontally(cm);
1880
    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
1881
    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
1882
  }
1883
1884
  // Since the delta values reported on mouse wheel events are
1885
  // unstandardized between browsers and even browser versions, and
1886
  // generally horribly unpredictable, this code starts by measuring
1887
  // the scroll effect that the first few mouse wheel events have,
1888
  // and, from that, detects the way it can convert deltas to pixel
1889
  // offsets afterwards.
1890
  //
1891
  // The reason we want to know the amount a wheel event will scroll
1892
  // is that it gives us a chance to update the display before the
1893
  // actual scrolling happens, reducing flickering.
1894
1895
  var wheelSamples = 0, wheelPixelsPerUnit = null;
1896
  // Fill in a browser-detected starting value on browsers where we
1897
  // know one. These don't have to be accurate -- the result of them
1898
  // being wrong would just be a slight flicker on the first wheel
1899
  // scroll (if it is large enough).
1900
  if (ie) wheelPixelsPerUnit = -.53;
1901
  else if (gecko) wheelPixelsPerUnit = 15;
1902
  else if (chrome) wheelPixelsPerUnit = -.7;
1903
  else if (safari) wheelPixelsPerUnit = -1/3;
1904
1905
  function onScrollWheel(cm, e) {
1906
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
1907
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
1908
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
1909
    else if (dy == null) dy = e.wheelDelta;
1910
1911
    var display = cm.display, scroll = display.scroller;
1912
    // Quit if there's nothing to scroll here
1913
    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
1914
          dy && scroll.scrollHeight > scroll.clientHeight)) return;
1915
1916
    // Webkit browsers on OS X abort momentum scrolls when the target
1917
    // of the scroll event is removed from the scrollable element.
1918
    // This hack (see related code in patchDisplay) makes sure the
1919
    // element is kept around.
1920
    if (dy && mac && webkit) {
1921
      for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
1922
        if (cur.lineObj) {
1923
          cm.display.currentWheelTarget = cur;
1924
          break;
1925
        }
1926
      }
1927
    }
1928
1929
    // On some browsers, horizontal scrolling will cause redraws to
1930
    // happen before the gutter has been realigned, causing it to
1931
    // wriggle around in a most unseemly way. When we have an
1932
    // estimated pixels/delta value, we just handle horizontal
1933
    // scrolling entirely here. It'll be slightly off from native, but
1934
    // better than glitching out.
1935
    if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
1936
      if (dy)
1937
        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
1938
      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
1939
      e_preventDefault(e);
1940
      display.wheelStartX = null; // Abort measurement, if in progress
1941
      return;
1942
    }
1943
1944
    if (dy && wheelPixelsPerUnit != null) {
1945
      var pixels = dy * wheelPixelsPerUnit;
1946
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
1947
      if (pixels < 0) top = Math.max(0, top + pixels - 50);
1948
      else bot = Math.min(cm.doc.height, bot + pixels + 50);
1949
      updateDisplay(cm, [], {top: top, bottom: bot});
1950
    }
1951
1952
    if (wheelSamples < 20) {
1953
      if (display.wheelStartX == null) {
1954
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
1955
        display.wheelDX = dx; display.wheelDY = dy;
1956
        setTimeout(function() {
1957
          if (display.wheelStartX == null) return;
1958
          var movedX = scroll.scrollLeft - display.wheelStartX;
1959
          var movedY = scroll.scrollTop - display.wheelStartY;
1960
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
1961
            (movedX && display.wheelDX && movedX / display.wheelDX);
1962
          display.wheelStartX = display.wheelStartY = null;
1963
          if (!sample) return;
1964
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
1965
          ++wheelSamples;
1966
        }, 200);
1967
      } else {
1968
        display.wheelDX += dx; display.wheelDY += dy;
1969
      }
1970
    }
1971
  }
1972
1973
  function doHandleBinding(cm, bound, dropShift) {
1974
    if (typeof bound == "string") {
1975
      bound = commands[bound];
1976
      if (!bound) return false;
1977
    }
1978
    // Ensure previous input has been read, so that the handler sees a
1979
    // consistent view of the document
1980
    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
1981
    var doc = cm.doc, prevShift = doc.sel.shift, done = false;
1982
    try {
1983
      if (isReadOnly(cm)) cm.state.suppressEdits = true;
1984
      if (dropShift) doc.sel.shift = false;
1985
      done = bound(cm) != Pass;
1986
    } finally {
1987
      doc.sel.shift = prevShift;
1988
      cm.state.suppressEdits = false;
1989
    }
1990
    return done;
1991
  }
1992
1993
  function allKeyMaps(cm) {
1994
    var maps = cm.state.keyMaps.slice(0);
1995
    if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
1996
    maps.push(cm.options.keyMap);
1997
    return maps;
1998
  }
1999
2000
  var maybeTransition;
2001
  function handleKeyBinding(cm, e) {
2002
    // Handle auto keymap transitions
2003
    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
2004
    clearTimeout(maybeTransition);
2005
    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
2006
      if (getKeyMap(cm.options.keyMap) == startMap) {
2007
        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
2008
        keyMapChanged(cm);
2009
      }
2010
    }, 50);
2011
2012
    var name = keyName(e, true), handled = false;
2013
    if (!name) return false;
2014
    var keymaps = allKeyMaps(cm);
2015
2016
    if (e.shiftKey) {
2017
      // First try to resolve full name (including 'Shift-'). Failing
2018
      // that, see if there is a cursor-motion command (starting with
2019
      // 'go') bound to the keyname without 'Shift-'.
2020
      handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
2021
             || lookupKey(name, keymaps, function(b) {
2022
                  if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
2023
                    return doHandleBinding(cm, b);
2024
                });
2025
    } else {
2026
      handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
2027
    }
2028
2029
    if (handled) {
2030
      e_preventDefault(e);
2031
      restartBlink(cm);
2032
      if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
2033
      signalLater(cm, "keyHandled", cm, name, e);
2034
    }
2035
    return handled;
2036
  }
2037
2038
  function handleCharBinding(cm, e, ch) {
2039
    var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
2040
                            function(b) { return doHandleBinding(cm, b, true); });
2041
    if (handled) {
2042
      e_preventDefault(e);
2043
      restartBlink(cm);
2044
      signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
2045
    }
2046
    return handled;
2047
  }
2048
2049
  var lastStoppedKey = null;
2050
  function onKeyDown(e) {
2051
    var cm = this;
2052
    if (!cm.state.focused) onFocus(cm);
2053
    if (ie && e.keyCode == 27) { e.returnValue = false; }
2054
    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2055
    var code = e.keyCode;
2056
    // IE does strange things with escape.
2057
    cm.doc.sel.shift = code == 16 || e.shiftKey;
2058
    // First give onKeyEvent option a chance to handle this.
2059
    var handled = handleKeyBinding(cm, e);
2060
    if (opera) {
2061
      lastStoppedKey = handled ? code : null;
2062
      // Opera has no cut event... we try to at least catch the key combo
2063
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
2064
        cm.replaceSelection("");
2065
    }
2066
  }
2067
2068
  function onKeyPress(e) {
2069
    var cm = this;
2070
    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2071
    var keyCode = e.keyCode, charCode = e.charCode;
2072
    if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
2073
    if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
2074
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
2075
    if (this.options.electricChars && this.doc.mode.electricChars &&
2076
        this.options.smartIndent && !isReadOnly(this) &&
2077
        this.doc.mode.electricChars.indexOf(ch) > -1)
2078
      setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
2079
    if (handleCharBinding(cm, e, ch)) return;
2080
    if (ie && !ie_lt9) cm.display.inputHasSelection = null;
2081
    fastPoll(cm);
2082
  }
2083
2084
  function onFocus(cm) {
2085
    if (cm.options.readOnly == "nocursor") return;
2086
    if (!cm.state.focused) {
2087
      signal(cm, "focus", cm);
2088
      cm.state.focused = true;
2089
      if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
2090
        cm.display.wrapper.className += " CodeMirror-focused";
2091
      resetInput(cm, true);
2092
    }
2093
    slowPoll(cm);
2094
    restartBlink(cm);
2095
  }
2096
  function onBlur(cm) {
2097
    if (cm.state.focused) {
2098
      signal(cm, "blur", cm);
2099
      cm.state.focused = false;
2100
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
2101
    }
2102
    clearInterval(cm.display.blinker);
2103
    setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
2104
  }
2105
2106
  var detectingSelectAll;
2107
  function onContextMenu(cm, e) {
2108
    var display = cm.display, sel = cm.doc.sel;
2109
    if (eventInWidget(display, e)) return;
2110
2111
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
2112
    if (!pos || opera) return; // Opera is difficult.
2113
    if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
2114
      operation(cm, setSelection)(cm.doc, pos, pos);
2115
2116
    var oldCSS = display.input.style.cssText;
2117
    display.inputDiv.style.position = "absolute";
2118
    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
2119
      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
2120
      "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
2121
    focusInput(cm);
2122
    resetInput(cm, true);
2123
    // Adds "Select all" to context menu in FF
2124
    if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
2125
2126
    function prepareSelectAllHack() {
2127
      if (display.input.selectionStart != null) {
2128
        var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value);
2129
        display.prevInput = " ";
2130
        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
2131
      }
2132
    }
2133
    function rehide() {
2134
      display.inputDiv.style.position = "relative";
2135
      display.input.style.cssText = oldCSS;
2136
      if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
2137
      slowPoll(cm);
2138
2139
      // Try to detect the user choosing select-all
2140
      if (display.input.selectionStart != null) {
2141
        if (!ie || ie_lt9) prepareSelectAllHack();
2142
        clearTimeout(detectingSelectAll);
2143
        var i = 0, poll = function(){
2144
          if (display.prevInput == " " && display.input.selectionStart == 0)
2145
            operation(cm, commands.selectAll)(cm);
2146
          else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
2147
          else resetInput(cm);
2148
        };
2149
        detectingSelectAll = setTimeout(poll, 200);
2150
      }
2151
    }
2152
2153
    if (ie && !ie_lt9) prepareSelectAllHack();
2154
    if (captureMiddleClick) {
2155
      e_stop(e);
2156
      var mouseup = function() {
2157
        off(window, "mouseup", mouseup);
2158
        setTimeout(rehide, 20);
2159
      };
2160
      on(window, "mouseup", mouseup);
2161
    } else {
2162
      setTimeout(rehide, 50);
2163
    }
2164
  }
2165
2166
  // UPDATING
2167
2168
  var changeEnd = CodeMirror.changeEnd = function(change) {
2169
    if (!change.text) return change.to;
2170
    return Pos(change.from.line + change.text.length - 1,
2171
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
2172
  };
2173
2174
  // Make sure a position will be valid after the given change.
2175
  function clipPostChange(doc, change, pos) {
2176
    if (!posLess(change.from, pos)) return clipPos(doc, pos);
2177
    var diff = (change.text.length - 1) - (change.to.line - change.from.line);
2178
    if (pos.line > change.to.line + diff) {
2179
      var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
2180
      if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2181
      return clipToLen(pos, getLine(doc, preLine).text.length);
2182
    }
2183
    if (pos.line == change.to.line + diff)
2184
      return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
2185
                       getLine(doc, change.to.line).text.length - change.to.ch);
2186
    var inside = pos.line - change.from.line;
2187
    return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
2188
  }
2189
2190
  // Hint can be null|"end"|"start"|"around"|{anchor,head}
2191
  function computeSelAfterChange(doc, change, hint) {
2192
    if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
2193
      return {anchor: clipPostChange(doc, change, hint.anchor),
2194
              head: clipPostChange(doc, change, hint.head)};
2195
2196
    if (hint == "start") return {anchor: change.from, head: change.from};
2197
2198
    var end = changeEnd(change);
2199
    if (hint == "around") return {anchor: change.from, head: end};
2200
    if (hint == "end") return {anchor: end, head: end};
2201
2202
    // hint is null, leave the selection alone as much as possible
2203
    var adjustPos = function(pos) {
2204
      if (posLess(pos, change.from)) return pos;
2205
      if (!posLess(change.to, pos)) return end;
2206
2207
      var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
2208
      if (pos.line == change.to.line) ch += end.ch - change.to.ch;
2209
      return Pos(line, ch);
2210
    };
2211
    return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
2212
  }
2213
2214
  function filterChange(doc, change, update) {
2215
    var obj = {
2216
      canceled: false,
2217
      from: change.from,
2218
      to: change.to,
2219
      text: change.text,
2220
      origin: change.origin,
2221
      cancel: function() { this.canceled = true; }
2222
    };
2223
    if (update) obj.update = function(from, to, text, origin) {
2224
      if (from) this.from = clipPos(doc, from);
2225
      if (to) this.to = clipPos(doc, to);
2226
      if (text) this.text = text;
2227
      if (origin !== undefined) this.origin = origin;
2228
    };
2229
    signal(doc, "beforeChange", doc, obj);
2230
    if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
2231
2232
    if (obj.canceled) return null;
2233
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
2234
  }
2235
2236
  // Replace the range from from to to by the strings in replacement.
2237
  // change is a {from, to, text [, origin]} object
2238
  function makeChange(doc, change, selUpdate, ignoreReadOnly) {
2239
    if (doc.cm) {
2240
      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
2241
      if (doc.cm.state.suppressEdits) return;
2242
    }
2243
2244
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
2245
      change = filterChange(doc, change, true);
2246
      if (!change) return;
2247
    }
2248
2249
    // Possibly split or suppress the update based on the presence
2250
    // of read-only spans in its range.
2251
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
2252
    if (split) {
2253
      for (var i = split.length - 1; i >= 1; --i)
2254
        makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
2255
      if (split.length)
2256
        makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
2257
    } else {
2258
      makeChangeNoReadonly(doc, change, selUpdate);
2259
    }
2260
  }
2261
2262
  function makeChangeNoReadonly(doc, change, selUpdate) {
2263
    var selAfter = computeSelAfterChange(doc, change, selUpdate);
2264
    addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
2265
2266
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
2267
    var rebased = [];
2268
2269
    linkedDocs(doc, function(doc, sharedHist) {
2270
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2271
        rebaseHist(doc.history, change);
2272
        rebased.push(doc.history);
2273
      }
2274
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
2275
    });
2276
  }
2277
2278
  function makeChangeFromHistory(doc, type) {
2279
    if (doc.cm && doc.cm.state.suppressEdits) return;
2280
2281
    var hist = doc.history;
2282
    var event = (type == "undo" ? hist.done : hist.undone).pop();
2283
    if (!event) return;
2284
2285
    var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
2286
                anchorAfter: event.anchorBefore, headAfter: event.headBefore,
2287
                generation: hist.generation};
2288
    (type == "undo" ? hist.undone : hist.done).push(anti);
2289
    hist.generation = event.generation || ++hist.maxGeneration;
2290
2291
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
2292
2293
    for (var i = event.changes.length - 1; i >= 0; --i) {
2294
      var change = event.changes[i];
2295
      change.origin = type;
2296
      if (filter && !filterChange(doc, change, false)) {
2297
        (type == "undo" ? hist.done : hist.undone).length = 0;
2298
        return;
2299
      }
2300
2301
      anti.changes.push(historyChangeFromChange(doc, change));
2302
2303
      var after = i ? computeSelAfterChange(doc, change, null)
2304
                    : {anchor: event.anchorBefore, head: event.headBefore};
2305
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
2306
      var rebased = [];
2307
2308
      linkedDocs(doc, function(doc, sharedHist) {
2309
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2310
          rebaseHist(doc.history, change);
2311
          rebased.push(doc.history);
2312
        }
2313
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
2314
      });
2315
    }
2316
  }
2317
2318
  function shiftDoc(doc, distance) {
2319
    function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
2320
    doc.first += distance;
2321
    if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
2322
    doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
2323
    doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
2324
  }
2325
2326
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
2327
    if (doc.cm && !doc.cm.curOp)
2328
      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
2329
2330
    if (change.to.line < doc.first) {
2331
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
2332
      return;
2333
    }
2334
    if (change.from.line > doc.lastLine()) return;
2335
2336
    // Clip the change to the size of this doc
2337
    if (change.from.line < doc.first) {
2338
      var shift = change.text.length - 1 - (doc.first - change.from.line);
2339
      shiftDoc(doc, shift);
2340
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
2341
                text: [lst(change.text)], origin: change.origin};
2342
    }
2343
    var last = doc.lastLine();
2344
    if (change.to.line > last) {
2345
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
2346
                text: [change.text[0]], origin: change.origin};
2347
    }
2348
2349
    change.removed = getBetween(doc, change.from, change.to);
2350
2351
    if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
2352
    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
2353
    else updateDoc(doc, change, spans, selAfter);
2354
  }
2355
2356
  function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
2357
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
2358
2359
    var recomputeMaxLength = false, checkWidthStart = from.line;
2360
    if (!cm.options.lineWrapping) {
2361
      checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
2362
      doc.iter(checkWidthStart, to.line + 1, function(line) {
2363
        if (line == display.maxLine) {
2364
          recomputeMaxLength = true;
2365
          return true;
2366
        }
2367
      });
2368
    }
2369
2370
    if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
2371
      cm.curOp.cursorActivity = true;
2372
2373
    updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
2374
2375
    if (!cm.options.lineWrapping) {
2376
      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
2377
        var len = lineLength(doc, line);
2378
        if (len > display.maxLineLength) {
2379
          display.maxLine = line;
2380
          display.maxLineLength = len;
2381
          display.maxLineChanged = true;
2382
          recomputeMaxLength = false;
2383
        }
2384
      });
2385
      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
2386
    }
2387
2388
    // Adjust frontier, schedule worker
2389
    doc.frontier = Math.min(doc.frontier, from.line);
2390
    startWorker(cm, 400);
2391
2392
    var lendiff = change.text.length - (to.line - from.line) - 1;
2393
    // Remember that these lines changed, for updating the display
2394
    regChange(cm, from.line, to.line + 1, lendiff);
2395
2396
    if (hasHandler(cm, "change")) {
2397
      var changeObj = {from: from, to: to,
2398
                       text: change.text,
2399
                       removed: change.removed,
2400
                       origin: change.origin};
2401
      if (cm.curOp.textChanged) {
2402
        for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
2403
        cur.next = changeObj;
2404
      } else cm.curOp.textChanged = changeObj;
2405
    }
2406
  }
2407
2408
  function replaceRange(doc, code, from, to, origin) {
2409
    if (!to) to = from;
2410
    if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
2411
    if (typeof code == "string") code = splitLines(code);
2412
    makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
2413
  }
2414
2415
  // POSITION OBJECT
2416
2417
  function Pos(line, ch) {
2418
    if (!(this instanceof Pos)) return new Pos(line, ch);
2419
    this.line = line; this.ch = ch;
2420
  }
2421
  CodeMirror.Pos = Pos;
2422
2423
  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2424
  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2425
  function copyPos(x) {return Pos(x.line, x.ch);}
2426
2427
  // SELECTION
2428
2429
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2430
  function clipPos(doc, pos) {
2431
    if (pos.line < doc.first) return Pos(doc.first, 0);
2432
    var last = doc.first + doc.size - 1;
2433
    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2434
    return clipToLen(pos, getLine(doc, pos.line).text.length);
2435
  }
2436
  function clipToLen(pos, linelen) {
2437
    var ch = pos.ch;
2438
    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2439
    else if (ch < 0) return Pos(pos.line, 0);
2440
    else return pos;
2441
  }
2442
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2443
2444
  // If shift is held, this will move the selection anchor. Otherwise,
2445
  // it'll set the whole selection.
2446
  function extendSelection(doc, pos, other, bias) {
2447
    if (doc.sel.shift || doc.sel.extend) {
2448
      var anchor = doc.sel.anchor;
2449
      if (other) {
2450
        var posBefore = posLess(pos, anchor);
2451
        if (posBefore != posLess(other, anchor)) {
2452
          anchor = pos;
2453
          pos = other;
2454
        } else if (posBefore != posLess(pos, other)) {
2455
          pos = other;
2456
        }
2457
      }
2458
      setSelection(doc, anchor, pos, bias);
2459
    } else {
2460
      setSelection(doc, pos, other || pos, bias);
2461
    }
2462
    if (doc.cm) doc.cm.curOp.userSelChange = true;
2463
  }
2464
2465
  function filterSelectionChange(doc, anchor, head) {
2466
    var obj = {anchor: anchor, head: head};
2467
    signal(doc, "beforeSelectionChange", doc, obj);
2468
    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2469
    obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
2470
    return obj;
2471
  }
2472
2473
  // Update the selection. Last two args are only used by
2474
  // updateDoc, since they have to be expressed in the line
2475
  // numbers before the update.
2476
  function setSelection(doc, anchor, head, bias, checkAtomic) {
2477
    if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
2478
      var filtered = filterSelectionChange(doc, anchor, head);
2479
      head = filtered.head;
2480
      anchor = filtered.anchor;
2481
    }
2482
2483
    var sel = doc.sel;
2484
    sel.goalColumn = null;
2485
    // Skip over atomic spans.
2486
    if (checkAtomic || !posEq(anchor, sel.anchor))
2487
      anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2488
    if (checkAtomic || !posEq(head, sel.head))
2489
      head = skipAtomic(doc, head, bias, checkAtomic != "push");
2490
2491
    if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
2492
2493
    sel.anchor = anchor; sel.head = head;
2494
    var inv = posLess(head, anchor);
2495
    sel.from = inv ? head : anchor;
2496
    sel.to = inv ? anchor : head;
2497
2498
    if (doc.cm)
2499
      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
2500
        doc.cm.curOp.cursorActivity = true;
2501
2502
    signalLater(doc, "cursorActivity", doc);
2503
  }
2504
2505
  function reCheckSelection(cm) {
2506
    setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
2507
  }
2508
2509
  function skipAtomic(doc, pos, bias, mayClear) {
2510
    var flipped = false, curPos = pos;
2511
    var dir = bias || 1;
2512
    doc.cantEdit = false;
2513
    search: for (;;) {
2514
      var line = getLine(doc, curPos.line);
2515
      if (line.markedSpans) {
2516
        for (var i = 0; i < line.markedSpans.length; ++i) {
2517
          var sp = line.markedSpans[i], m = sp.marker;
2518
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2519
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2520
            if (mayClear) {
2521
              signal(m, "beforeCursorEnter");
2522
              if (m.explicitlyCleared) {
2523
                if (!line.markedSpans) break;
2524
                else {--i; continue;}
2525
              }
2526
            }
2527
            if (!m.atomic) continue;
2528
            var newPos = m.find()[dir < 0 ? "from" : "to"];
2529
            if (posEq(newPos, curPos)) {
2530
              newPos.ch += dir;
2531
              if (newPos.ch < 0) {
2532
                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2533
                else newPos = null;
2534
              } else if (newPos.ch > line.text.length) {
2535
                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2536
                else newPos = null;
2537
              }
2538
              if (!newPos) {
2539
                if (flipped) {
2540
                  // Driven in a corner -- no valid cursor position found at all
2541
                  // -- try again *with* clearing, if we didn't already
2542
                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
2543
                  // Otherwise, turn off editing until further notice, and return the start of the doc
2544
                  doc.cantEdit = true;
2545
                  return Pos(doc.first, 0);
2546
                }
2547
                flipped = true; newPos = pos; dir = -dir;
2548
              }
2549
            }
2550
            curPos = newPos;
2551
            continue search;
2552
          }
2553
        }
2554
      }
2555
      return curPos;
2556
    }
2557
  }
2558
2559
  // SCROLLING
2560
2561
  function scrollCursorIntoView(cm) {
2562
    var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
2563
    if (!cm.state.focused) return;
2564
    var display = cm.display, box = getRect(display.sizer), doScroll = null;
2565
    if (coords.top + box.top < 0) doScroll = true;
2566
    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
2567
    if (doScroll != null && !phantom) {
2568
      var hidden = display.cursor.style.display == "none";
2569
      if (hidden) {
2570
        display.cursor.style.display = "";
2571
        display.cursor.style.left = coords.left + "px";
2572
        display.cursor.style.top = (coords.top - display.viewOffset) + "px";
2573
      }
2574
      display.cursor.scrollIntoView(doScroll);
2575
      if (hidden) display.cursor.style.display = "none";
2576
    }
2577
  }
2578
2579
  function scrollPosIntoView(cm, pos, margin) {
2580
    if (margin == null) margin = 0;
2581
    for (;;) {
2582
      var changed = false, coords = cursorCoords(cm, pos);
2583
      var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
2584
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
2585
      if (scrollPos.scrollTop != null) {
2586
        setScrollTop(cm, scrollPos.scrollTop);
2587
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
2588
      }
2589
      if (scrollPos.scrollLeft != null) {
2590
        setScrollLeft(cm, scrollPos.scrollLeft);
2591
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
2592
      }
2593
      if (!changed) return coords;
2594
    }
2595
  }
2596
2597
  function scrollIntoView(cm, x1, y1, x2, y2) {
2598
    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
2599
    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
2600
    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
2601
  }
2602
2603
  function calculateScrollPos(cm, x1, y1, x2, y2) {
2604
    var display = cm.display, snapMargin = textHeight(cm.display);
2605
    if (y1 < 0) y1 = 0;
2606
    var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
2607
    var docBottom = cm.doc.height + paddingVert(display);
2608
    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
2609
    if (y1 < screentop) {
2610
      result.scrollTop = atTop ? 0 : y1;
2611
    } else if (y2 > screentop + screen) {
2612
      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
2613
      if (newTop != screentop) result.scrollTop = newTop;
2614
    }
2615
2616
    var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
2617
    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
2618
    var gutterw = display.gutters.offsetWidth;
2619
    var atLeft = x1 < gutterw + 10;
2620
    if (x1 < screenleft + gutterw || atLeft) {
2621
      if (atLeft) x1 = 0;
2622
      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
2623
    } else if (x2 > screenw + screenleft - 3) {
2624
      result.scrollLeft = x2 + 10 - screenw;
2625
    }
2626
    return result;
2627
  }
2628
2629
  function updateScrollPos(cm, left, top) {
2630
    cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
2631
                                scrollTop: top == null ? cm.doc.scrollTop : top};
2632
  }
2633
2634
  function addToScrollPos(cm, left, top) {
2635
    var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
2636
    var scroll = cm.display.scroller;
2637
    pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
2638
    pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
2639
  }
2640
2641
  // API UTILITIES
2642
2643
  function indentLine(cm, n, how, aggressive) {
2644
    var doc = cm.doc;
2645
    if (how == null) how = "add";
2646
    if (how == "smart") {
2647
      if (!cm.doc.mode.indent) how = "prev";
2648
      else var state = getStateBefore(cm, n);
2649
    }
2650
2651
    var tabSize = cm.options.tabSize;
2652
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
2653
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
2654
    if (how == "smart") {
2655
      indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
2656
      if (indentation == Pass) {
2657
        if (!aggressive) return;
2658
        how = "prev";
2659
      }
2660
    }
2661
    if (how == "prev") {
2662
      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
2663
      else indentation = 0;
2664
    } else if (how == "add") {
2665
      indentation = curSpace + cm.options.indentUnit;
2666
    } else if (how == "subtract") {
2667
      indentation = curSpace - cm.options.indentUnit;
2668
    } else if (typeof how == "number") {
2669
      indentation = curSpace + how;
2670
    }
2671
    indentation = Math.max(0, indentation);
2672
2673
    var indentString = "", pos = 0;
2674
    if (cm.options.indentWithTabs)
2675
      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
2676
    if (pos < indentation) indentString += spaceStr(indentation - pos);
2677
2678
    if (indentString != curSpaceString)
2679
      replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
2680
    line.stateAfter = null;
2681
  }
2682
2683
  function changeLine(cm, handle, op) {
2684
    var no = handle, line = handle, doc = cm.doc;
2685
    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
2686
    else no = lineNo(handle);
2687
    if (no == null) return null;
2688
    if (op(line, no)) regChange(cm, no, no + 1);
2689
    else return null;
2690
    return line;
2691
  }
2692
2693
  function findPosH(doc, pos, dir, unit, visually) {
2694
    var line = pos.line, ch = pos.ch, origDir = dir;
2695
    var lineObj = getLine(doc, line);
2696
    var possible = true;
2697
    function findNextLine() {
2698
      var l = line + dir;
2699
      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
2700
      line = l;
2701
      return lineObj = getLine(doc, l);
2702
    }
2703
    function moveOnce(boundToLine) {
2704
      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
2705
      if (next == null) {
2706
        if (!boundToLine && findNextLine()) {
2707
          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
2708
          else ch = dir < 0 ? lineObj.text.length : 0;
2709
        } else return (possible = false);
2710
      } else ch = next;
2711
      return true;
2712
    }
2713
2714
    if (unit == "char") moveOnce();
2715
    else if (unit == "column") moveOnce(true);
2716
    else if (unit == "word" || unit == "group") {
2717
      var sawType = null, group = unit == "group";
2718
      for (var first = true;; first = false) {
2719
        if (dir < 0 && !moveOnce(!first)) break;
2720
        var cur = lineObj.text.charAt(ch) || "\n";
2721
        var type = isWordChar(cur) ? "w"
2722
          : !group ? null
2723
          : /\s/.test(cur) ? null
2724
          : "p";
2725
        if (sawType && sawType != type) {
2726
          if (dir < 0) {dir = 1; moveOnce();}
2727
          break;
2728
        }
2729
        if (type) sawType = type;
2730
        if (dir > 0 && !moveOnce(!first)) break;
2731
      }
2732
    }
2733
    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
2734
    if (!possible) result.hitSide = true;
2735
    return result;
2736
  }
2737
2738
  function findPosV(cm, pos, dir, unit) {
2739
    var doc = cm.doc, x = pos.left, y;
2740
    if (unit == "page") {
2741
      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
2742
      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
2743
    } else if (unit == "line") {
2744
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
2745
    }
2746
    for (;;) {
2747
      var target = coordsChar(cm, x, y);
2748
      if (!target.outside) break;
2749
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
2750
      y += dir * 5;
2751
    }
2752
    return target;
2753
  }
2754
2755
  function findWordAt(line, pos) {
2756
    var start = pos.ch, end = pos.ch;
2757
    if (line) {
2758
      if (pos.xRel < 0 || end == line.length) --start; else ++end;
2759
      var startChar = line.charAt(start);
2760
      var check = isWordChar(startChar) ? isWordChar
2761
        : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
2762
        : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
2763
      while (start > 0 && check(line.charAt(start - 1))) --start;
2764
      while (end < line.length && check(line.charAt(end))) ++end;
2765
    }
2766
    return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
2767
  }
2768
2769
  function selectLine(cm, line) {
2770
    extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
2771
  }
2772
2773
  // PROTOTYPE
2774
2775
  // The publicly visible API. Note that operation(null, f) means
2776
  // 'wrap f in an operation, performed on its `this` parameter'
2777
2778
  CodeMirror.prototype = {
2779
    constructor: CodeMirror,
2780
    focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
2781
2782
    setOption: function(option, value) {
2783
      var options = this.options, old = options[option];
2784
      if (options[option] == value && option != "mode") return;
2785
      options[option] = value;
2786
      if (optionHandlers.hasOwnProperty(option))
2787
        operation(this, optionHandlers[option])(this, value, old);
2788
    },
2789
2790
    getOption: function(option) {return this.options[option];},
2791
    getDoc: function() {return this.doc;},
2792
2793
    addKeyMap: function(map, bottom) {
2794
      this.state.keyMaps[bottom ? "push" : "unshift"](map);
2795
    },
2796
    removeKeyMap: function(map) {
2797
      var maps = this.state.keyMaps;
2798
      for (var i = 0; i < maps.length; ++i)
2799
        if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
2800
          maps.splice(i, 1);
2801
          return true;
2802
        }
2803
    },
2804
2805
    addOverlay: operation(null, function(spec, options) {
2806
      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
2807
      if (mode.startState) throw new Error("Overlays may not be stateful.");
2808
      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
2809
      this.state.modeGen++;
2810
      regChange(this);
2811
    }),
2812
    removeOverlay: operation(null, function(spec) {
2813
      var overlays = this.state.overlays;
2814
      for (var i = 0; i < overlays.length; ++i) {
2815
        var cur = overlays[i].modeSpec;
2816
        if (cur == spec || typeof spec == "string" && cur.name == spec) {
2817
          overlays.splice(i, 1);
2818
          this.state.modeGen++;
2819
          regChange(this);
2820
          return;
2821
        }
2822
      }
2823
    }),
2824
2825
    indentLine: operation(null, function(n, dir, aggressive) {
2826
      if (typeof dir != "string" && typeof dir != "number") {
2827
        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
2828
        else dir = dir ? "add" : "subtract";
2829
      }
2830
      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
2831
    }),
2832
    indentSelection: operation(null, function(how) {
2833
      var sel = this.doc.sel;
2834
      if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
2835
      var e = sel.to.line - (sel.to.ch ? 0 : 1);
2836
      for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
2837
    }),
2838
2839
    // Fetch the parser token for a given character. Useful for hacks
2840
    // that want to inspect the mode state (say, for completion).
2841
    getTokenAt: function(pos, precise) {
2842
      var doc = this.doc;
2843
      pos = clipPos(doc, pos);
2844
      var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
2845
      var line = getLine(doc, pos.line);
2846
      var stream = new StringStream(line.text, this.options.tabSize);
2847
      while (stream.pos < pos.ch && !stream.eol()) {
2848
        stream.start = stream.pos;
2849
        var style = mode.token(stream, state);
2850
      }
2851
      return {start: stream.start,
2852
              end: stream.pos,
2853
              string: stream.current(),
2854
              className: style || null, // Deprecated, use 'type' instead
2855
              type: style || null,
2856
              state: state};
2857
    },
2858
2859
    getTokenTypeAt: function(pos) {
2860
      pos = clipPos(this.doc, pos);
2861
      var styles = getLineStyles(this, getLine(this.doc, pos.line));
2862
      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
2863
      for (;;) {
2864
        var mid = (before + after) >> 1;
2865
        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
2866
        else if (styles[mid * 2 + 1] < ch) before = mid + 1;
2867
        else return styles[mid * 2 + 2];
2868
      }
2869
    },
2870
2871
    getStateAfter: function(line, precise) {
2872
      var doc = this.doc;
2873
      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
2874
      return getStateBefore(this, line + 1, precise);
2875
    },
2876
2877
    cursorCoords: function(start, mode) {
2878
      var pos, sel = this.doc.sel;
2879
      if (start == null) pos = sel.head;
2880
      else if (typeof start == "object") pos = clipPos(this.doc, start);
2881
      else pos = start ? sel.from : sel.to;
2882
      return cursorCoords(this, pos, mode || "page");
2883
    },
2884
2885
    charCoords: function(pos, mode) {
2886
      return charCoords(this, clipPos(this.doc, pos), mode || "page");
2887
    },
2888
2889
    coordsChar: function(coords, mode) {
2890
      coords = fromCoordSystem(this, coords, mode || "page");
2891
      return coordsChar(this, coords.left, coords.top);
2892
    },
2893
2894
    lineAtHeight: function(height, mode) {
2895
      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
2896
      return lineAtHeight(this.doc, height + this.display.viewOffset);
2897
    },
2898
    heightAtLine: function(line, mode) {
2899
      var end = false, last = this.doc.first + this.doc.size - 1;
2900
      if (line < this.doc.first) line = this.doc.first;
2901
      else if (line > last) { line = last; end = true; }
2902
      var lineObj = getLine(this.doc, line);
2903
      return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
2904
        (end ? lineObj.height : 0);
2905
    },
2906
2907
    defaultTextHeight: function() { return textHeight(this.display); },
2908
    defaultCharWidth: function() { return charWidth(this.display); },
2909
2910
    setGutterMarker: operation(null, function(line, gutterID, value) {
2911
      return changeLine(this, line, function(line) {
2912
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
2913
        markers[gutterID] = value;
2914
        if (!value && isEmpty(markers)) line.gutterMarkers = null;
2915
        return true;
2916
      });
2917
    }),
2918
2919
    clearGutter: operation(null, function(gutterID) {
2920
      var cm = this, doc = cm.doc, i = doc.first;
2921
      doc.iter(function(line) {
2922
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
2923
          line.gutterMarkers[gutterID] = null;
2924
          regChange(cm, i, i + 1);
2925
          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
2926
        }
2927
        ++i;
2928
      });
2929
    }),
2930
2931
    addLineClass: operation(null, function(handle, where, cls) {
2932
      return changeLine(this, handle, function(line) {
2933
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
2934
        if (!line[prop]) line[prop] = cls;
2935
        else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
2936
        else line[prop] += " " + cls;
2937
        return true;
2938
      });
2939
    }),
2940
2941
    removeLineClass: operation(null, function(handle, where, cls) {
2942
      return changeLine(this, handle, function(line) {
2943
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
2944
        var cur = line[prop];
2945
        if (!cur) return false;
2946
        else if (cls == null) line[prop] = null;
2947
        else {
2948
          var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
2949
          if (!found) return false;
2950
          var end = found.index + found[0].length;
2951
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
2952
        }
2953
        return true;
2954
      });
2955
    }),
2956
2957
    addLineWidget: operation(null, function(handle, node, options) {
2958
      return addLineWidget(this, handle, node, options);
2959
    }),
2960
2961
    removeLineWidget: function(widget) { widget.clear(); },
2962
2963
    lineInfo: function(line) {
2964
      if (typeof line == "number") {
2965
        if (!isLine(this.doc, line)) return null;
2966
        var n = line;
2967
        line = getLine(this.doc, line);
2968
        if (!line) return null;
2969
      } else {
2970
        var n = lineNo(line);
2971
        if (n == null) return null;
2972
      }
2973
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
2974
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
2975
              widgets: line.widgets};
2976
    },
2977
2978
    getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
2979
2980
    addWidget: function(pos, node, scroll, vert, horiz) {
2981
      var display = this.display;
2982
      pos = cursorCoords(this, clipPos(this.doc, pos));
2983
      var top = pos.bottom, left = pos.left;
2984
      node.style.position = "absolute";
2985
      display.sizer.appendChild(node);
2986
      if (vert == "over") {
2987
        top = pos.top;
2988
      } else if (vert == "above" || vert == "near") {
2989
        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
2990
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
2991
        // Default to positioning above (if specified and possible); otherwise default to positioning below
2992
        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
2993
          top = pos.top - node.offsetHeight;
2994
        else if (pos.bottom + node.offsetHeight <= vspace)
2995
          top = pos.bottom;
2996
        if (left + node.offsetWidth > hspace)
2997
          left = hspace - node.offsetWidth;
2998
      }
2999
      node.style.top = top + "px";
3000
      node.style.left = node.style.right = "";
3001
      if (horiz == "right") {
3002
        left = display.sizer.clientWidth - node.offsetWidth;
3003
        node.style.right = "0px";
3004
      } else {
3005
        if (horiz == "left") left = 0;
3006
        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
3007
        node.style.left = left + "px";
3008
      }
3009
      if (scroll)
3010
        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
3011
    },
3012
3013
    triggerOnKeyDown: operation(null, onKeyDown),
3014
3015
    execCommand: function(cmd) {return commands[cmd](this);},
3016
3017
    findPosH: function(from, amount, unit, visually) {
3018
      var dir = 1;
3019
      if (amount < 0) { dir = -1; amount = -amount; }
3020
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3021
        cur = findPosH(this.doc, cur, dir, unit, visually);
3022
        if (cur.hitSide) break;
3023
      }
3024
      return cur;
3025
    },
3026
3027
    moveH: operation(null, function(dir, unit) {
3028
      var sel = this.doc.sel, pos;
3029
      if (sel.shift || sel.extend || posEq(sel.from, sel.to))
3030
        pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
3031
      else
3032
        pos = dir < 0 ? sel.from : sel.to;
3033
      extendSelection(this.doc, pos, pos, dir);
3034
    }),
3035
3036
    deleteH: operation(null, function(dir, unit) {
3037
      var sel = this.doc.sel;
3038
      if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
3039
      else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
3040
      this.curOp.userSelChange = true;
3041
    }),
3042
3043
    findPosV: function(from, amount, unit, goalColumn) {
3044
      var dir = 1, x = goalColumn;
3045
      if (amount < 0) { dir = -1; amount = -amount; }
3046
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3047
        var coords = cursorCoords(this, cur, "div");
3048
        if (x == null) x = coords.left;
3049
        else coords.left = x;
3050
        cur = findPosV(this, coords, dir, unit);
3051
        if (cur.hitSide) break;
3052
      }
3053
      return cur;
3054
    },
3055
3056
    moveV: operation(null, function(dir, unit) {
3057
      var sel = this.doc.sel;
3058
      var pos = cursorCoords(this, sel.head, "div");
3059
      if (sel.goalColumn != null) pos.left = sel.goalColumn;
3060
      var target = findPosV(this, pos, dir, unit);
3061
3062
      if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
3063
      extendSelection(this.doc, target, target, dir);
3064
      sel.goalColumn = pos.left;
3065
    }),
3066
3067
    toggleOverwrite: function(value) {
3068
      if (value != null && value == this.state.overwrite) return;
3069
      if (this.state.overwrite = !this.state.overwrite)
3070
        this.display.cursor.className += " CodeMirror-overwrite";
3071
      else
3072
        this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
3073
    },
3074
    hasFocus: function() { return this.state.focused; },
3075
3076
    scrollTo: operation(null, function(x, y) {
3077
      updateScrollPos(this, x, y);
3078
    }),
3079
    getScrollInfo: function() {
3080
      var scroller = this.display.scroller, co = scrollerCutOff;
3081
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
3082
              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
3083
              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
3084
    },
3085
3086
    scrollIntoView: operation(null, function(pos, margin) {
3087
      if (typeof pos == "number") pos = Pos(pos, 0);
3088
      if (!margin) margin = 0;
3089
      var coords = pos;
3090
3091
      if (!pos || pos.line != null) {
3092
        this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
3093
        this.curOp.scrollToPosMargin = margin;
3094
        coords = cursorCoords(this, this.curOp.scrollToPos);
3095
      }
3096
      var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin);
3097
      updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
3098
    }),
3099
3100
    setSize: function(width, height) {
3101
      function interpret(val) {
3102
        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
3103
      }
3104
      if (width != null) this.display.wrapper.style.width = interpret(width);
3105
      if (height != null) this.display.wrapper.style.height = interpret(height);
3106
      this.refresh();
3107
    },
3108
3109
    on: function(type, f) {on(this, type, f);},
3110
    off: function(type, f) {off(this, type, f);},
3111
3112
    operation: function(f){return runInOp(this, f);},
3113
3114
    refresh: operation(null, function() {
3115
      clearCaches(this);
3116
      updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
3117
      regChange(this);
3118
    }),
3119
3120
    swapDoc: operation(null, function(doc) {
3121
      var old = this.doc;
3122
      old.cm = null;
3123
      attachDoc(this, doc);
3124
      clearCaches(this);
3125
      resetInput(this, true);
3126
      updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
3127
      return old;
3128
    }),
3129
3130
    getInputField: function(){return this.display.input;},
3131
    getWrapperElement: function(){return this.display.wrapper;},
3132
    getScrollerElement: function(){return this.display.scroller;},
3133
    getGutterElement: function(){return this.display.gutters;}
3134
  };
3135
3136
  // OPTION DEFAULTS
3137
3138
  var optionHandlers = CodeMirror.optionHandlers = {};
3139
3140
  // The default configuration options.
3141
  var defaults = CodeMirror.defaults = {};
3142
3143
  function option(name, deflt, handle, notOnInit) {
3144
    CodeMirror.defaults[name] = deflt;
3145
    if (handle) optionHandlers[name] =
3146
      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
3147
  }
3148
3149
  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
3150
3151
  // These two are, on init, called from the constructor because they
3152
  // have to be initialized before the editor can start at all.
3153
  option("value", "", function(cm, val) {
3154
    cm.setValue(val);
3155
  }, true);
3156
  option("mode", null, function(cm, val) {
3157
    cm.doc.modeOption = val;
3158
    loadMode(cm);
3159
  }, true);
3160
3161
  option("indentUnit", 2, loadMode, true);
3162
  option("indentWithTabs", false);
3163
  option("smartIndent", true);
3164
  option("tabSize", 4, function(cm) {
3165
    loadMode(cm);
3166
    clearCaches(cm);
3167
    regChange(cm);
3168
  }, true);
3169
  option("electricChars", true);
3170
  option("rtlMoveVisually", !windows);
3171
3172
  option("theme", "default", function(cm) {
3173
    themeChanged(cm);
3174
    guttersChanged(cm);
3175
  }, true);
3176
  option("keyMap", "default", keyMapChanged);
3177
  option("extraKeys", null);
3178
3179
  option("onKeyEvent", null);
3180
  option("onDragEvent", null);
3181
3182
  option("lineWrapping", false, wrappingChanged, true);
3183
  option("gutters", [], function(cm) {
3184
    setGuttersForLineNumbers(cm.options);
3185
    guttersChanged(cm);
3186
  }, true);
3187
  option("fixedGutter", true, function(cm, val) {
3188
    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
3189
    cm.refresh();
3190
  }, true);
3191
  option("coverGutterNextToScrollbar", false, updateScrollbars, true);
3192
  option("lineNumbers", false, function(cm) {
3193
    setGuttersForLineNumbers(cm.options);
3194
    guttersChanged(cm);
3195
  }, true);
3196
  option("firstLineNumber", 1, guttersChanged, true);
3197
  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
3198
  option("showCursorWhenSelecting", false, updateSelection, true);
3199
3200
  option("readOnly", false, function(cm, val) {
3201
    if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
3202
    else if (!val) resetInput(cm, true);
3203
  });
3204
  option("dragDrop", true);
3205
3206
  option("cursorBlinkRate", 530);
3207
  option("cursorScrollMargin", 0);
3208
  option("cursorHeight", 1);
3209
  option("workTime", 100);
3210
  option("workDelay", 100);
3211
  option("flattenSpans", true);
3212
  option("pollInterval", 100);
3213
  option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
3214
  option("historyEventDelay", 500);
3215
  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
3216
  option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true);
3217
  option("moveInputWithCursor", true, function(cm, val) {
3218
    if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
3219
  });
3220
3221
  option("tabindex", null, function(cm, val) {
3222
    cm.display.input.tabIndex = val || "";
3223
  });
3224
  option("autofocus", null);
3225
3226
  // MODE DEFINITION AND QUERYING
3227
3228
  // Known modes, by name and by MIME
3229
  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
3230
3231
  CodeMirror.defineMode = function(name, mode) {
3232
    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
3233
    if (arguments.length > 2) {
3234
      mode.dependencies = [];
3235
      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
3236
    }
3237
    modes[name] = mode;
3238
  };
3239
3240
  CodeMirror.defineMIME = function(mime, spec) {
3241
    mimeModes[mime] = spec;
3242
  };
3243
3244
  CodeMirror.resolveMode = function(spec) {
3245
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
3246
      spec = mimeModes[spec];
3247
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
3248
      var found = mimeModes[spec.name];
3249
      spec = createObj(found, spec);
3250
      spec.name = found.name;
3251
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
3252
      return CodeMirror.resolveMode("application/xml");
3253
    }
3254
    if (typeof spec == "string") return {name: spec};
3255
    else return spec || {name: "null"};
3256
  };
3257
3258
  CodeMirror.getMode = function(options, spec) {
3259
    spec = CodeMirror.resolveMode(spec);
3260
    var mfactory = modes[spec.name];
3261
    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
3262
    var modeObj = mfactory(options, spec);
3263
    if (modeExtensions.hasOwnProperty(spec.name)) {
3264
      var exts = modeExtensions[spec.name];
3265
      for (var prop in exts) {
3266
        if (!exts.hasOwnProperty(prop)) continue;
3267
        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
3268
        modeObj[prop] = exts[prop];
3269
      }
3270
    }
3271
    modeObj.name = spec.name;
3272
    return modeObj;
3273
  };
3274
3275
  CodeMirror.defineMode("null", function() {
3276
    return {token: function(stream) {stream.skipToEnd();}};
3277
  });
3278
  CodeMirror.defineMIME("text/plain", "null");
3279
3280
  var modeExtensions = CodeMirror.modeExtensions = {};
3281
  CodeMirror.extendMode = function(mode, properties) {
3282
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
3283
    copyObj(properties, exts);
3284
  };
3285
3286
  // EXTENSIONS
3287
3288
  CodeMirror.defineExtension = function(name, func) {
3289
    CodeMirror.prototype[name] = func;
3290
  };
3291
  CodeMirror.defineDocExtension = function(name, func) {
3292
    Doc.prototype[name] = func;
3293
  };
3294
  CodeMirror.defineOption = option;
3295
3296
  var initHooks = [];
3297
  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
3298
3299
  // MODE STATE HANDLING
3300
3301
  // Utility functions for working with state. Exported because modes
3302
  // sometimes need to do this.
3303
  function copyState(mode, state) {
3304
    if (state === true) return state;
3305
    if (mode.copyState) return mode.copyState(state);
3306
    var nstate = {};
3307
    for (var n in state) {
3308
      var val = state[n];
3309
      if (val instanceof Array) val = val.concat([]);
3310
      nstate[n] = val;
3311
    }
3312
    return nstate;
3313
  }
3314
  CodeMirror.copyState = copyState;
3315
3316
  function startState(mode, a1, a2) {
3317
    return mode.startState ? mode.startState(a1, a2) : true;
3318
  }
3319
  CodeMirror.startState = startState;
3320
3321
  CodeMirror.innerMode = function(mode, state) {
3322
    while (mode.innerMode) {
3323
      var info = mode.innerMode(state);
3324
      state = info.state;
3325
      mode = info.mode;
3326
    }
3327
    return info || {mode: mode, state: state};
3328
  };
3329
3330
  // STANDARD COMMANDS
3331
3332
  var commands = CodeMirror.commands = {
3333
    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
3334
    killLine: function(cm) {
3335
      var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
3336
      if (!sel && cm.getLine(from.line).length == from.ch)
3337
        cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
3338
      else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
3339
    },
3340
    deleteLine: function(cm) {
3341
      var l = cm.getCursor().line;
3342
      cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
3343
    },
3344
    delLineLeft: function(cm) {
3345
      var cur = cm.getCursor();
3346
      cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
3347
    },
3348
    undo: function(cm) {cm.undo();},
3349
    redo: function(cm) {cm.redo();},
3350
    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
3351
    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
3352
    goLineStart: function(cm) {
3353
      cm.extendSelection(lineStart(cm, cm.getCursor().line));
3354
    },
3355
    goLineStartSmart: function(cm) {
3356
      var cur = cm.getCursor(), start = lineStart(cm, cur.line);
3357
      var line = cm.getLineHandle(start.line);
3358
      var order = getOrder(line);
3359
      if (!order || order[0].level == 0) {
3360
        var firstNonWS = Math.max(0, line.text.search(/\S/));
3361
        var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
3362
        cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
3363
      } else cm.extendSelection(start);
3364
    },
3365
    goLineEnd: function(cm) {
3366
      cm.extendSelection(lineEnd(cm, cm.getCursor().line));
3367
    },
3368
    goLineRight: function(cm) {
3369
      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3370
      cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
3371
    },
3372
    goLineLeft: function(cm) {
3373
      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3374
      cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
3375
    },
3376
    goLineUp: function(cm) {cm.moveV(-1, "line");},
3377
    goLineDown: function(cm) {cm.moveV(1, "line");},
3378
    goPageUp: function(cm) {cm.moveV(-1, "page");},
3379
    goPageDown: function(cm) {cm.moveV(1, "page");},
3380
    goCharLeft: function(cm) {cm.moveH(-1, "char");},
3381
    goCharRight: function(cm) {cm.moveH(1, "char");},
3382
    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
3383
    goColumnRight: function(cm) {cm.moveH(1, "column");},
3384
    goWordLeft: function(cm) {cm.moveH(-1, "word");},
3385
    goGroupRight: function(cm) {cm.moveH(1, "group");},
3386
    goGroupLeft: function(cm) {cm.moveH(-1, "group");},
3387
    goWordRight: function(cm) {cm.moveH(1, "word");},
3388
    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
3389
    delCharAfter: function(cm) {cm.deleteH(1, "char");},
3390
    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
3391
    delWordAfter: function(cm) {cm.deleteH(1, "word");},
3392
    delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
3393
    delGroupAfter: function(cm) {cm.deleteH(1, "group");},
3394
    indentAuto: function(cm) {cm.indentSelection("smart");},
3395
    indentMore: function(cm) {cm.indentSelection("add");},
3396
    indentLess: function(cm) {cm.indentSelection("subtract");},
3397
    insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
3398
    defaultTab: function(cm) {
3399
      if (cm.somethingSelected()) cm.indentSelection("add");
3400
      else cm.replaceSelection("\t", "end", "+input");
3401
    },
3402
    transposeChars: function(cm) {
3403
      var cur = cm.getCursor(), line = cm.getLine(cur.line);
3404
      if (cur.ch > 0 && cur.ch < line.length - 1)
3405
        cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
3406
                        Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
3407
    },
3408
    newlineAndIndent: function(cm) {
3409
      operation(cm, function() {
3410
        cm.replaceSelection("\n", "end", "+input");
3411
        cm.indentLine(cm.getCursor().line, null, true);
3412
      })();
3413
    },
3414
    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
3415
  };
3416
3417
  // STANDARD KEYMAPS
3418
3419
  var keyMap = CodeMirror.keyMap = {};
3420
  keyMap.basic = {
3421
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
3422
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
3423
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
3424
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
3425
  };
3426
  // Note that the save and find-related commands aren't defined by
3427
  // default. Unknown commands are simply ignored.
3428
  keyMap.pcDefault = {
3429
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
3430
    "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
3431
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
3432
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
3433
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
3434
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
3435
    fallthrough: "basic"
3436
  };
3437
  keyMap.macDefault = {
3438
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
3439
    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
3440
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
3441
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
3442
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
3443
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
3444
    fallthrough: ["basic", "emacsy"]
3445
  };
3446
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
3447
  keyMap.emacsy = {
3448
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
3449
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
3450
    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
3451
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
3452
  };
3453
3454
  // KEYMAP DISPATCH
3455
3456
  function getKeyMap(val) {
3457
    if (typeof val == "string") return keyMap[val];
3458
    else return val;
3459
  }
3460
3461
  function lookupKey(name, maps, handle) {
3462
    function lookup(map) {
3463
      map = getKeyMap(map);
3464
      var found = map[name];
3465
      if (found === false) return "stop";
3466
      if (found != null && handle(found)) return true;
3467
      if (map.nofallthrough) return "stop";
3468
3469
      var fallthrough = map.fallthrough;
3470
      if (fallthrough == null) return false;
3471
      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
3472
        return lookup(fallthrough);
3473
      for (var i = 0, e = fallthrough.length; i < e; ++i) {
3474
        var done = lookup(fallthrough[i]);
3475
        if (done) return done;
3476
      }
3477
      return false;
3478
    }
3479
3480
    for (var i = 0; i < maps.length; ++i) {
3481
      var done = lookup(maps[i]);
3482
      if (done) return done != "stop";
3483
    }
3484
  }
3485
  function isModifierKey(event) {
3486
    var name = keyNames[event.keyCode];
3487
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
3488
  }
3489
  function keyName(event, noShift) {
3490
    if (opera && event.keyCode == 34 && event["char"]) return false;
3491
    var name = keyNames[event.keyCode];
3492
    if (name == null || event.altGraphKey) return false;
3493
    if (event.altKey) name = "Alt-" + name;
3494
    if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
3495
    if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
3496
    if (!noShift && event.shiftKey) name = "Shift-" + name;
3497
    return name;
3498
  }
3499
  CodeMirror.lookupKey = lookupKey;
3500
  CodeMirror.isModifierKey = isModifierKey;
3501
  CodeMirror.keyName = keyName;
3502
3503
  // FROMTEXTAREA
3504
3505
  CodeMirror.fromTextArea = function(textarea, options) {
3506
    if (!options) options = {};
3507
    options.value = textarea.value;
3508
    if (!options.tabindex && textarea.tabindex)
3509
      options.tabindex = textarea.tabindex;
3510
    if (!options.placeholder && textarea.placeholder)
3511
      options.placeholder = textarea.placeholder;
3512
    // Set autofocus to true if this textarea is focused, or if it has
3513
    // autofocus and no other element is focused.
3514
    if (options.autofocus == null) {
3515
      var hasFocus = document.body;
3516
      // doc.activeElement occasionally throws on IE
3517
      try { hasFocus = document.activeElement; } catch(e) {}
3518
      options.autofocus = hasFocus == textarea ||
3519
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
3520
    }
3521
3522
    function save() {textarea.value = cm.getValue();}
3523
    if (textarea.form) {
3524
      on(textarea.form, "submit", save);
3525
      // Deplorable hack to make the submit method do the right thing.
3526
      if (!options.leaveSubmitMethodAlone) {
3527
        var form = textarea.form, realSubmit = form.submit;
3528
        try {
3529
          var wrappedSubmit = form.submit = function() {
3530
            save();
3531
            form.submit = realSubmit;
3532
            form.submit();
3533
            form.submit = wrappedSubmit;
3534
          };
3535
        } catch(e) {}
3536
      }
3537
    }
3538
3539
    textarea.style.display = "none";
3540
    var cm = CodeMirror(function(node) {
3541
      textarea.parentNode.insertBefore(node, textarea.nextSibling);
3542
    }, options);
3543
    cm.save = save;
3544
    cm.getTextArea = function() { return textarea; };
3545
    cm.toTextArea = function() {
3546
      save();
3547
      textarea.parentNode.removeChild(cm.getWrapperElement());
3548
      textarea.style.display = "";
3549
      if (textarea.form) {
3550
        off(textarea.form, "submit", save);
3551
        if (typeof textarea.form.submit == "function")
3552
          textarea.form.submit = realSubmit;
3553
      }
3554
    };
3555
    return cm;
3556
  };
3557
3558
  // STRING STREAM
3559
3560
  // Fed to the mode parsers, provides helper functions to make
3561
  // parsers more succinct.
3562
3563
  // The character stream used by a mode's parser.
3564
  function StringStream(string, tabSize) {
3565
    this.pos = this.start = 0;
3566
    this.string = string;
3567
    this.tabSize = tabSize || 8;
3568
    this.lastColumnPos = this.lastColumnValue = 0;
3569
  }
3570
3571
  StringStream.prototype = {
3572
    eol: function() {return this.pos >= this.string.length;},
3573
    sol: function() {return this.pos == 0;},
3574
    peek: function() {return this.string.charAt(this.pos) || undefined;},
3575
    next: function() {
3576
      if (this.pos < this.string.length)
3577
        return this.string.charAt(this.pos++);
3578
    },
3579
    eat: function(match) {
3580
      var ch = this.string.charAt(this.pos);
3581
      if (typeof match == "string") var ok = ch == match;
3582
      else var ok = ch && (match.test ? match.test(ch) : match(ch));
3583
      if (ok) {++this.pos; return ch;}
3584
    },
3585
    eatWhile: function(match) {
3586
      var start = this.pos;
3587
      while (this.eat(match)){}
3588
      return this.pos > start;
3589
    },
3590
    eatSpace: function() {
3591
      var start = this.pos;
3592
      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
3593
      return this.pos > start;
3594
    },
3595
    skipToEnd: function() {this.pos = this.string.length;},
3596
    skipTo: function(ch) {
3597
      var found = this.string.indexOf(ch, this.pos);
3598
      if (found > -1) {this.pos = found; return true;}
3599
    },
3600
    backUp: function(n) {this.pos -= n;},
3601
    column: function() {
3602
      if (this.lastColumnPos < this.start) {
3603
        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
3604
        this.lastColumnPos = this.start;
3605
      }
3606
      return this.lastColumnValue;
3607
    },
3608
    indentation: function() {return countColumn(this.string, null, this.tabSize);},
3609
    match: function(pattern, consume, caseInsensitive) {
3610
      if (typeof pattern == "string") {
3611
        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
3612
        var substr = this.string.substr(this.pos, pattern.length);
3613
        if (cased(substr) == cased(pattern)) {
3614
          if (consume !== false) this.pos += pattern.length;
3615
          return true;
3616
        }
3617
      } else {
3618
        var match = this.string.slice(this.pos).match(pattern);
3619
        if (match && match.index > 0) return null;
3620
        if (match && consume !== false) this.pos += match[0].length;
3621
        return match;
3622
      }
3623
    },
3624
    current: function(){return this.string.slice(this.start, this.pos);}
3625
  };
3626
  CodeMirror.StringStream = StringStream;
3627
3628
  // TEXTMARKERS
3629
3630
  function TextMarker(doc, type) {
3631
    this.lines = [];
3632
    this.type = type;
3633
    this.doc = doc;
3634
  }
3635
  CodeMirror.TextMarker = TextMarker;
3636
3637
  TextMarker.prototype.clear = function() {
3638
    if (this.explicitlyCleared) return;
3639
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
3640
    if (withOp) startOperation(cm);
3641
    var min = null, max = null;
3642
    for (var i = 0; i < this.lines.length; ++i) {
3643
      var line = this.lines[i];
3644
      var span = getMarkedSpanFor(line.markedSpans, this);
3645
      if (span.to != null) max = lineNo(line);
3646
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
3647
      if (span.from != null)
3648
        min = lineNo(line);
3649
      else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
3650
        updateLineHeight(line, textHeight(cm.display));
3651
    }
3652
    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
3653
      var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
3654
      if (len > cm.display.maxLineLength) {
3655
        cm.display.maxLine = visual;
3656
        cm.display.maxLineLength = len;
3657
        cm.display.maxLineChanged = true;
3658
      }
3659
    }
3660
3661
    if (min != null && cm) regChange(cm, min, max + 1);
3662
    this.lines.length = 0;
3663
    this.explicitlyCleared = true;
3664
    if (this.atomic && this.doc.cantEdit) {
3665
      this.doc.cantEdit = false;
3666
      if (cm) reCheckSelection(cm);
3667
    }
3668
    if (withOp) endOperation(cm);
3669
    signalLater(this, "clear");
3670
  };
3671
3672
  TextMarker.prototype.find = function() {
3673
    var from, to;
3674
    for (var i = 0; i < this.lines.length; ++i) {
3675
      var line = this.lines[i];
3676
      var span = getMarkedSpanFor(line.markedSpans, this);
3677
      if (span.from != null || span.to != null) {
3678
        var found = lineNo(line);
3679
        if (span.from != null) from = Pos(found, span.from);
3680
        if (span.to != null) to = Pos(found, span.to);
3681
      }
3682
    }
3683
    if (this.type == "bookmark") return from;
3684
    return from && {from: from, to: to};
3685
  };
3686
3687
  TextMarker.prototype.changed = function() {
3688
    var pos = this.find(), cm = this.doc.cm;
3689
    if (!pos || !cm) return;
3690
    var line = getLine(this.doc, pos.from.line);
3691
    clearCachedMeasurement(cm, line);
3692
    if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) {
3693
      for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
3694
        if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
3695
        break;
3696
      }
3697
      runInOp(cm, function() { cm.curOp.selectionChanged = true; });
3698
    }
3699
  };
3700
3701
  TextMarker.prototype.attachLine = function(line) {
3702
    if (!this.lines.length && this.doc.cm) {
3703
      var op = this.doc.cm.curOp;
3704
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
3705
        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
3706
    }
3707
    this.lines.push(line);
3708
  };
3709
  TextMarker.prototype.detachLine = function(line) {
3710
    this.lines.splice(indexOf(this.lines, line), 1);
3711
    if (!this.lines.length && this.doc.cm) {
3712
      var op = this.doc.cm.curOp;
3713
      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
3714
    }
3715
  };
3716
3717
  function markText(doc, from, to, options, type) {
3718
    if (options && options.shared) return markTextShared(doc, from, to, options, type);
3719
    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
3720
3721
    var marker = new TextMarker(doc, type);
3722
    if (type == "range" && !posLess(from, to)) return marker;
3723
    if (options) copyObj(options, marker);
3724
    if (marker.replacedWith) {
3725
      marker.collapsed = true;
3726
      marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
3727
      if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
3728
    }
3729
    if (marker.collapsed) sawCollapsedSpans = true;
3730
3731
    if (marker.addToHistory)
3732
      addToHistory(doc, {from: from, to: to, origin: "markText"},
3733
                   {head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
3734
3735
    var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
3736
    doc.iter(curLine, to.line + 1, function(line) {
3737
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
3738
        updateMaxLine = true;
3739
      var span = {from: null, to: null, marker: marker};
3740
      size += line.text.length;
3741
      if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
3742
      if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
3743
      if (marker.collapsed) {
3744
        if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
3745
        if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
3746
        else updateLineHeight(line, 0);
3747
      }
3748
      addMarkedSpan(line, span);
3749
      ++curLine;
3750
    });
3751
    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
3752
      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
3753
    });
3754
3755
    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
3756
3757
    if (marker.readOnly) {
3758
      sawReadOnlySpans = true;
3759
      if (doc.history.done.length || doc.history.undone.length)
3760
        doc.clearHistory();
3761
    }
3762
    if (marker.collapsed) {
3763
      if (collapsedAtStart != collapsedAtEnd)
3764
        throw new Error("Inserting collapsed marker overlapping an existing one");
3765
      marker.size = size;
3766
      marker.atomic = true;
3767
    }
3768
    if (cm) {
3769
      if (updateMaxLine) cm.curOp.updateMaxLine = true;
3770
      if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
3771
        regChange(cm, from.line, to.line + 1);
3772
      if (marker.atomic) reCheckSelection(cm);
3773
    }
3774
    return marker;
3775
  }
3776
3777
  // SHARED TEXTMARKERS
3778
3779
  function SharedTextMarker(markers, primary) {
3780
    this.markers = markers;
3781
    this.primary = primary;
3782
    for (var i = 0, me = this; i < markers.length; ++i) {
3783
      markers[i].parent = this;
3784
      on(markers[i], "clear", function(){me.clear();});
3785
    }
3786
  }
3787
  CodeMirror.SharedTextMarker = SharedTextMarker;
3788
3789
  SharedTextMarker.prototype.clear = function() {
3790
    if (this.explicitlyCleared) return;
3791
    this.explicitlyCleared = true;
3792
    for (var i = 0; i < this.markers.length; ++i)
3793
      this.markers[i].clear();
3794
    signalLater(this, "clear");
3795
  };
3796
  SharedTextMarker.prototype.find = function() {
3797
    return this.primary.find();
3798
  };
3799
3800
  function markTextShared(doc, from, to, options, type) {
3801
    options = copyObj(options);
3802
    options.shared = false;
3803
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
3804
    var widget = options.replacedWith;
3805
    linkedDocs(doc, function(doc) {
3806
      if (widget) options.replacedWith = widget.cloneNode(true);
3807
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
3808
      for (var i = 0; i < doc.linked.length; ++i)
3809
        if (doc.linked[i].isParent) return;
3810
      primary = lst(markers);
3811
    });
3812
    return new SharedTextMarker(markers, primary);
3813
  }
3814
3815
  // TEXTMARKER SPANS
3816
3817
  function getMarkedSpanFor(spans, marker) {
3818
    if (spans) for (var i = 0; i < spans.length; ++i) {
3819
      var span = spans[i];
3820
      if (span.marker == marker) return span;
3821
    }
3822
  }
3823
  function removeMarkedSpan(spans, span) {
3824
    for (var r, i = 0; i < spans.length; ++i)
3825
      if (spans[i] != span) (r || (r = [])).push(spans[i]);
3826
    return r;
3827
  }
3828
  function addMarkedSpan(line, span) {
3829
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
3830
    span.marker.attachLine(line);
3831
  }
3832
3833
  function markedSpansBefore(old, startCh, isInsert) {
3834
    if (old) for (var i = 0, nw; i < old.length; ++i) {
3835
      var span = old[i], marker = span.marker;
3836
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
3837
      if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
3838
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
3839
        (nw || (nw = [])).push({from: span.from,
3840
                                to: endsAfter ? null : span.to,
3841
                                marker: marker});
3842
      }
3843
    }
3844
    return nw;
3845
  }
3846
3847
  function markedSpansAfter(old, endCh, isInsert) {
3848
    if (old) for (var i = 0, nw; i < old.length; ++i) {
3849
      var span = old[i], marker = span.marker;
3850
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
3851
      if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
3852
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
3853
        (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
3854
                                to: span.to == null ? null : span.to - endCh,
3855
                                marker: marker});
3856
      }
3857
    }
3858
    return nw;
3859
  }
3860
3861
  function stretchSpansOverChange(doc, change) {
3862
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
3863
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
3864
    if (!oldFirst && !oldLast) return null;
3865
3866
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
3867
    // Get the spans that 'stick out' on both sides
3868
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
3869
    var last = markedSpansAfter(oldLast, endCh, isInsert);
3870
3871
    // Next, merge those two ends
3872
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
3873
    if (first) {
3874
      // Fix up .to properties of first
3875
      for (var i = 0; i < first.length; ++i) {
3876
        var span = first[i];
3877
        if (span.to == null) {
3878
          var found = getMarkedSpanFor(last, span.marker);
3879
          if (!found) span.to = startCh;
3880
          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
3881
        }
3882
      }
3883
    }
3884
    if (last) {
3885
      // Fix up .from in last (or move them into first in case of sameLine)
3886
      for (var i = 0; i < last.length; ++i) {
3887
        var span = last[i];
3888
        if (span.to != null) span.to += offset;
3889
        if (span.from == null) {
3890
          var found = getMarkedSpanFor(first, span.marker);
3891
          if (!found) {
3892
            span.from = offset;
3893
            if (sameLine) (first || (first = [])).push(span);
3894
          }
3895
        } else {
3896
          span.from += offset;
3897
          if (sameLine) (first || (first = [])).push(span);
3898
        }
3899
      }
3900
    }
3901
    if (sameLine && first) {
3902
      // Make sure we didn't create any zero-length spans
3903
      for (var i = 0; i < first.length; ++i)
3904
        if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark")
3905
          first.splice(i--, 1);
3906
      if (!first.length) first = null;
3907
    }
3908
3909
    var newMarkers = [first];
3910
    if (!sameLine) {
3911
      // Fill gap with whole-line-spans
3912
      var gap = change.text.length - 2, gapMarkers;
3913
      if (gap > 0 && first)
3914
        for (var i = 0; i < first.length; ++i)
3915
          if (first[i].to == null)
3916
            (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
3917
      for (var i = 0; i < gap; ++i)
3918
        newMarkers.push(gapMarkers);
3919
      newMarkers.push(last);
3920
    }
3921
    return newMarkers;
3922
  }
3923
3924
  function mergeOldSpans(doc, change) {
3925
    var old = getOldSpans(doc, change);
3926
    var stretched = stretchSpansOverChange(doc, change);
3927
    if (!old) return stretched;
3928
    if (!stretched) return old;
3929
3930
    for (var i = 0; i < old.length; ++i) {
3931
      var oldCur = old[i], stretchCur = stretched[i];
3932
      if (oldCur && stretchCur) {
3933
        spans: for (var j = 0; j < stretchCur.length; ++j) {
3934
          var span = stretchCur[j];
3935
          for (var k = 0; k < oldCur.length; ++k)
3936
            if (oldCur[k].marker == span.marker) continue spans;
3937
          oldCur.push(span);
3938
        }
3939
      } else if (stretchCur) {
3940
        old[i] = stretchCur;
3941
      }
3942
    }
3943
    return old;
3944
  }
3945
3946
  function removeReadOnlyRanges(doc, from, to) {
3947
    var markers = null;
3948
    doc.iter(from.line, to.line + 1, function(line) {
3949
      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
3950
        var mark = line.markedSpans[i].marker;
3951
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
3952
          (markers || (markers = [])).push(mark);
3953
      }
3954
    });
3955
    if (!markers) return null;
3956
    var parts = [{from: from, to: to}];
3957
    for (var i = 0; i < markers.length; ++i) {
3958
      var mk = markers[i], m = mk.find();
3959
      for (var j = 0; j < parts.length; ++j) {
3960
        var p = parts[j];
3961
        if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
3962
        var newParts = [j, 1];
3963
        if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
3964
          newParts.push({from: p.from, to: m.from});
3965
        if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
3966
          newParts.push({from: m.to, to: p.to});
3967
        parts.splice.apply(parts, newParts);
3968
        j += newParts.length - 1;
3969
      }
3970
    }
3971
    return parts;
3972
  }
3973
3974
  function collapsedSpanAt(line, ch) {
3975
    var sps = sawCollapsedSpans && line.markedSpans, found;
3976
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
3977
      sp = sps[i];
3978
      if (!sp.marker.collapsed) continue;
3979
      if ((sp.from == null || sp.from < ch) &&
3980
          (sp.to == null || sp.to > ch) &&
3981
          (!found || found.width < sp.marker.width))
3982
        found = sp.marker;
3983
    }
3984
    return found;
3985
  }
3986
  function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
3987
  function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
3988
3989
  function visualLine(doc, line) {
3990
    var merged;
3991
    while (merged = collapsedSpanAtStart(line))
3992
      line = getLine(doc, merged.find().from.line);
3993
    return line;
3994
  }
3995
3996
  function lineIsHidden(doc, line) {
3997
    var sps = sawCollapsedSpans && line.markedSpans;
3998
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
3999
      sp = sps[i];
4000
      if (!sp.marker.collapsed) continue;
4001
      if (sp.from == null) return true;
4002
      if (sp.marker.replacedWith) continue;
4003
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
4004
        return true;
4005
    }
4006
  }
4007
  function lineIsHiddenInner(doc, line, span) {
4008
    if (span.to == null) {
4009
      var end = span.marker.find().to, endLine = getLine(doc, end.line);
4010
      return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
4011
    }
4012
    if (span.marker.inclusiveRight && span.to == line.text.length)
4013
      return true;
4014
    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
4015
      sp = line.markedSpans[i];
4016
      if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
4017
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
4018
          lineIsHiddenInner(doc, line, sp)) return true;
4019
    }
4020
  }
4021
4022
  function detachMarkedSpans(line) {
4023
    var spans = line.markedSpans;
4024
    if (!spans) return;
4025
    for (var i = 0; i < spans.length; ++i)
4026
      spans[i].marker.detachLine(line);
4027
    line.markedSpans = null;
4028
  }
4029
4030
  function attachMarkedSpans(line, spans) {
4031
    if (!spans) return;
4032
    for (var i = 0; i < spans.length; ++i)
4033
      spans[i].marker.attachLine(line);
4034
    line.markedSpans = spans;
4035
  }
4036
4037
  // LINE WIDGETS
4038
4039
  var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
4040
    for (var opt in options) if (options.hasOwnProperty(opt))
4041
      this[opt] = options[opt];
4042
    this.cm = cm;
4043
    this.node = node;
4044
  };
4045
  function widgetOperation(f) {
4046
    return function() {
4047
      var withOp = !this.cm.curOp;
4048
      if (withOp) startOperation(this.cm);
4049
      try {var result = f.apply(this, arguments);}
4050
      finally {if (withOp) endOperation(this.cm);}
4051
      return result;
4052
    };
4053
  }
4054
  LineWidget.prototype.clear = widgetOperation(function() {
4055
    var ws = this.line.widgets, no = lineNo(this.line);
4056
    if (no == null || !ws) return;
4057
    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
4058
    if (!ws.length) this.line.widgets = null;
4059
    updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
4060
    regChange(this.cm, no, no + 1);
4061
  });
4062
  LineWidget.prototype.changed = widgetOperation(function() {
4063
    var oldH = this.height;
4064
    this.height = null;
4065
    var diff = widgetHeight(this) - oldH;
4066
    if (!diff) return;
4067
    updateLineHeight(this.line, this.line.height + diff);
4068
    var no = lineNo(this.line);
4069
    regChange(this.cm, no, no + 1);
4070
  });
4071
4072
  function widgetHeight(widget) {
4073
    if (widget.height != null) return widget.height;
4074
    if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
4075
      removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
4076
    return widget.height = widget.node.offsetHeight;
4077
  }
4078
4079
  function addLineWidget(cm, handle, node, options) {
4080
    var widget = new LineWidget(cm, node, options);
4081
    if (widget.noHScroll) cm.display.alignWidgets = true;
4082
    changeLine(cm, handle, function(line) {
4083
      (line.widgets || (line.widgets = [])).push(widget);
4084
      widget.line = line;
4085
      if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
4086
        var aboveVisible = heightAtLine(cm, line) < cm.display.scroller.scrollTop;
4087
        updateLineHeight(line, line.height + widgetHeight(widget));
4088
        if (aboveVisible) addToScrollPos(cm, 0, widget.height);
4089
      }
4090
      return true;
4091
    });
4092
    return widget;
4093
  }
4094
4095
  // LINE DATA STRUCTURE
4096
4097
  // Line objects. These hold state related to a line, including
4098
  // highlighting info (the styles array).
4099
  function makeLine(text, markedSpans, estimateHeight) {
4100
    var line = {text: text};
4101
    attachMarkedSpans(line, markedSpans);
4102
    line.height = estimateHeight ? estimateHeight(line) : 1;
4103
    return line;
4104
  }
4105
4106
  function updateLine(line, text, markedSpans, estimateHeight) {
4107
    line.text = text;
4108
    if (line.stateAfter) line.stateAfter = null;
4109
    if (line.styles) line.styles = null;
4110
    if (line.order != null) line.order = null;
4111
    detachMarkedSpans(line);
4112
    attachMarkedSpans(line, markedSpans);
4113
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
4114
    if (estHeight != line.height) updateLineHeight(line, estHeight);
4115
  }
4116
4117
  function cleanUpLine(line) {
4118
    line.parent = null;
4119
    detachMarkedSpans(line);
4120
  }
4121
4122
  // Run the given mode's parser over a line, update the styles
4123
  // array, which contains alternating fragments of text and CSS
4124
  // classes.
4125
  function runMode(cm, text, mode, state, f) {
4126
    var flattenSpans = mode.flattenSpans;
4127
    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
4128
    var curStart = 0, curStyle = null;
4129
    var stream = new StringStream(text, cm.options.tabSize), style;
4130
    if (text == "" && mode.blankLine) mode.blankLine(state);
4131
    while (!stream.eol()) {
4132
      if (stream.pos > cm.options.maxHighlightLength) {
4133
        flattenSpans = false;
4134
        // Webkit seems to refuse to render text nodes longer than 57444 characters
4135
        stream.pos = Math.min(text.length, stream.start + 50000);
4136
        style = null;
4137
      } else {
4138
        style = mode.token(stream, state);
4139
      }
4140
      if (!flattenSpans || curStyle != style) {
4141
        if (curStart < stream.start) f(stream.start, curStyle);
4142
        curStart = stream.start; curStyle = style;
4143
      }
4144
      stream.start = stream.pos;
4145
    }
4146
    if (curStart < stream.pos) f(stream.pos, curStyle);
4147
  }
4148
4149
  function highlightLine(cm, line, state) {
4150
    // A styles array always starts with a number identifying the
4151
    // mode/overlays that it is based on (for easy invalidation).
4152
    var st = [cm.state.modeGen];
4153
    // Compute the base array of styles
4154
    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);});
4155
4156
    // Run overlays, adjust style array.
4157
    for (var o = 0; o < cm.state.overlays.length; ++o) {
4158
      var overlay = cm.state.overlays[o], i = 1, at = 0;
4159
      runMode(cm, line.text, overlay.mode, true, function(end, style) {
4160
        var start = i;
4161
        // Ensure there's a token end at the current position, and that i points at it
4162
        while (at < end) {
4163
          var i_end = st[i];
4164
          if (i_end > end)
4165
            st.splice(i, 1, end, st[i+1], i_end);
4166
          i += 2;
4167
          at = Math.min(end, i_end);
4168
        }
4169
        if (!style) return;
4170
        if (overlay.opaque) {
4171
          st.splice(start, i - start, end, style);
4172
          i = start + 2;
4173
        } else {
4174
          for (; start < i; start += 2) {
4175
            var cur = st[start+1];
4176
            st[start+1] = cur ? cur + " " + style : style;
4177
          }
4178
        }
4179
      });
4180
    }
4181
4182
    return st;
4183
  }
4184
4185
  function getLineStyles(cm, line) {
4186
    if (!line.styles || line.styles[0] != cm.state.modeGen)
4187
      line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
4188
    return line.styles;
4189
  }
4190
4191
  // Lightweight form of highlight -- proceed over this line and
4192
  // update state, but don't save a style array.
4193
  function processLine(cm, line, state) {
4194
    var mode = cm.doc.mode;
4195
    var stream = new StringStream(line.text, cm.options.tabSize);
4196
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
4197
    while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
4198
      mode.token(stream, state);
4199
      stream.start = stream.pos;
4200
    }
4201
  }
4202
4203
  var styleToClassCache = {};
4204
  function styleToClass(style) {
4205
    if (!style) return null;
4206
    return styleToClassCache[style] ||
4207
      (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
4208
  }
4209
4210
  function lineContent(cm, realLine, measure) {
4211
    var merged, line = realLine, empty = true;
4212
    while (merged = collapsedSpanAtStart(line))
4213
      line = getLine(cm.doc, merged.find().from.line);
4214
4215
    var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
4216
                   measure: null, measuredSomething: false, cm: cm};
4217
    if (line.textClass) builder.pre.className = line.textClass;
4218
4219
    do {
4220
      if (line.text) empty = false;
4221
      builder.measure = line == realLine && measure;
4222
      builder.pos = 0;
4223
      builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
4224
      if ((ie || webkit) && cm.getOption("lineWrapping"))
4225
        builder.addToken = buildTokenSplitSpaces(builder.addToken);
4226
      var next = insertLineContent(line, builder, getLineStyles(cm, line));
4227
      if (measure && line == realLine && !builder.measuredSomething) {
4228
        measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
4229
        builder.measuredSomething = true;
4230
      }
4231
      if (next) line = getLine(cm.doc, next.to.line);
4232
    } while (next);
4233
4234
    if (measure && !builder.measuredSomething && !measure[0])
4235
      measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
4236
    if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
4237
      builder.pre.appendChild(document.createTextNode("\u00a0"));
4238
4239
    var order;
4240
    // Work around problem with the reported dimensions of single-char
4241
    // direction spans on IE (issue #1129). See also the comment in
4242
    // cursorCoords.
4243
    if (measure && ie && (order = getOrder(line))) {
4244
      var l = order.length - 1;
4245
      if (order[l].from == order[l].to) --l;
4246
      var last = order[l], prev = order[l - 1];
4247
      if (last.from + 1 == last.to && prev && last.level < prev.level) {
4248
        var span = measure[builder.pos - 1];
4249
        if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
4250
                                               span.nextSibling);
4251
      }
4252
    }
4253
4254
    signal(cm, "renderLine", cm, realLine, builder.pre);
4255
    return builder.pre;
4256
  }
4257
4258
  var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
4259
  function buildToken(builder, text, style, startStyle, endStyle) {
4260
    if (!text) return;
4261
    if (!tokenSpecialChars.test(text)) {
4262
      builder.col += text.length;
4263
      var content = document.createTextNode(text);
4264
    } else {
4265
      var content = document.createDocumentFragment(), pos = 0;
4266
      while (true) {
4267
        tokenSpecialChars.lastIndex = pos;
4268
        var m = tokenSpecialChars.exec(text);
4269
        var skipped = m ? m.index - pos : text.length - pos;
4270
        if (skipped) {
4271
          content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
4272
          builder.col += skipped;
4273
        }
4274
        if (!m) break;
4275
        pos += skipped + 1;
4276
        if (m[0] == "\t") {
4277
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
4278
          content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
4279
          builder.col += tabWidth;
4280
        } else {
4281
          var token = elt("span", "\u2022", "cm-invalidchar");
4282
          token.title = "\\u" + m[0].charCodeAt(0).toString(16);
4283
          content.appendChild(token);
4284
          builder.col += 1;
4285
        }
4286
      }
4287
    }
4288
    if (style || startStyle || endStyle || builder.measure) {
4289
      var fullStyle = style || "";
4290
      if (startStyle) fullStyle += startStyle;
4291
      if (endStyle) fullStyle += endStyle;
4292
      return builder.pre.appendChild(elt("span", [content], fullStyle));
4293
    }
4294
    builder.pre.appendChild(content);
4295
  }
4296
4297
  function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
4298
    var wrapping = builder.cm.options.lineWrapping;
4299
    for (var i = 0; i < text.length; ++i) {
4300
      var ch = text.charAt(i), start = i == 0;
4301
      if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
4302
        ch = text.slice(i, i + 2);
4303
        ++i;
4304
      } else if (i && wrapping && spanAffectsWrapping(text, i)) {
4305
        builder.pre.appendChild(elt("wbr"));
4306
      }
4307
      var span = builder.measure[builder.pos] =
4308
        buildToken(builder, ch, style,
4309
                   start && startStyle, i == text.length - 1 && endStyle);
4310
      // In IE single-space nodes wrap differently than spaces
4311
      // embedded in larger text nodes, except when set to
4312
      // white-space: normal (issue #1268).
4313
      if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
4314
          i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
4315
        span.style.whiteSpace = "normal";
4316
      builder.pos += ch.length;
4317
    }
4318
    if (text.length) builder.measuredSomething = true;
4319
  }
4320
4321
  function buildTokenSplitSpaces(inner) {
4322
    function split(old) {
4323
      var out = " ";
4324
      for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
4325
      out += " ";
4326
      return out;
4327
    }
4328
    return function(builder, text, style, startStyle, endStyle) {
4329
      return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle);
4330
    };
4331
  }
4332
4333
  function buildCollapsedSpan(builder, size, widget) {
4334
    if (widget) {
4335
      if (!builder.display) widget = widget.cloneNode(true);
4336
      if (builder.measure) {
4337
        builder.measure[builder.pos] = size ? widget
4338
          : builder.pre.appendChild(zeroWidthElement(builder.cm.display.measure));
4339
        builder.measuredSomething = true;
4340
      }
4341
      builder.pre.appendChild(widget);
4342
    }
4343
    builder.pos += size;
4344
  }
4345
4346
  // Outputs a number of spans to make up a line, taking highlighting
4347
  // and marked text into account.
4348
  function insertLineContent(line, builder, styles) {
4349
    var spans = line.markedSpans, allText = line.text, at = 0;
4350
    if (!spans) {
4351
      for (var i = 1; i < styles.length; i+=2)
4352
        builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1]));
4353
      return;
4354
    }
4355
4356
    var len = allText.length, pos = 0, i = 1, text = "", style;
4357
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
4358
    for (;;) {
4359
      if (nextChange == pos) { // Update current marker set
4360
        spanStyle = spanEndStyle = spanStartStyle = "";
4361
        collapsed = null; nextChange = Infinity;
4362
        var foundBookmark = null;
4363
        for (var j = 0; j < spans.length; ++j) {
4364
          var sp = spans[j], m = sp.marker;
4365
          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
4366
            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
4367
            if (m.className) spanStyle += " " + m.className;
4368
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
4369
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
4370
            if (m.collapsed && (!collapsed || collapsed.marker.size < m.size))
4371
              collapsed = sp;
4372
          } else if (sp.from > pos && nextChange > sp.from) {
4373
            nextChange = sp.from;
4374
          }
4375
          if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
4376
            foundBookmark = m.replacedWith;
4377
        }
4378
        if (collapsed && (collapsed.from || 0) == pos) {
4379
          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
4380
                             collapsed.from != null && collapsed.marker.replacedWith);
4381
          if (collapsed.to == null) return collapsed.marker.find();
4382
        }
4383
        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
4384
      }
4385
      if (pos >= len) break;
4386
4387
      var upto = Math.min(len, nextChange);
4388
      while (true) {
4389
        if (text) {
4390
          var end = pos + text.length;
4391
          if (!collapsed) {
4392
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
4393
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
4394
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
4395
          }
4396
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
4397
          pos = end;
4398
          spanStartStyle = "";
4399
        }
4400
        text = allText.slice(at, at = styles[i++]);
4401
        style = styleToClass(styles[i++]);
4402
      }
4403
    }
4404
  }
4405
4406
  // DOCUMENT DATA STRUCTURE
4407
4408
  function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
4409
    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
4410
    function update(line, text, spans) {
4411
      updateLine(line, text, spans, estimateHeight);
4412
      signalLater(line, "change", line, change);
4413
    }
4414
4415
    var from = change.from, to = change.to, text = change.text;
4416
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4417
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4418
4419
    // First adjust the line structure
4420
    if (from.ch == 0 && to.ch == 0 && lastText == "") {
4421
      // This is a whole-line replace. Treated specially to make
4422
      // sure line objects move the way they are supposed to.
4423
      for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
4424
        added.push(makeLine(text[i], spansFor(i), estimateHeight));
4425
      update(lastLine, lastLine.text, lastSpans);
4426
      if (nlines) doc.remove(from.line, nlines);
4427
      if (added.length) doc.insert(from.line, added);
4428
    } else if (firstLine == lastLine) {
4429
      if (text.length == 1) {
4430
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4431
      } else {
4432
        for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
4433
          added.push(makeLine(text[i], spansFor(i), estimateHeight));
4434
        added.push(makeLine(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
4435
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4436
        doc.insert(from.line + 1, added);
4437
      }
4438
    } else if (text.length == 1) {
4439
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4440
      doc.remove(from.line + 1, nlines);
4441
    } else {
4442
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4443
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4444
      for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
4445
        added.push(makeLine(text[i], spansFor(i), estimateHeight));
4446
      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
4447
      doc.insert(from.line + 1, added);
4448
    }
4449
4450
    signalLater(doc, "change", doc, change);
4451
    setSelection(doc, selAfter.anchor, selAfter.head, null, true);
4452
  }
4453
4454
  function LeafChunk(lines) {
4455
    this.lines = lines;
4456
    this.parent = null;
4457
    for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
4458
      lines[i].parent = this;
4459
      height += lines[i].height;
4460
    }
4461
    this.height = height;
4462
  }
4463
4464
  LeafChunk.prototype = {
4465
    chunkSize: function() { return this.lines.length; },
4466
    removeInner: function(at, n) {
4467
      for (var i = at, e = at + n; i < e; ++i) {
4468
        var line = this.lines[i];
4469
        this.height -= line.height;
4470
        cleanUpLine(line);
4471
        signalLater(line, "delete");
4472
      }
4473
      this.lines.splice(at, n);
4474
    },
4475
    collapse: function(lines) {
4476
      lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
4477
    },
4478
    insertInner: function(at, lines, height) {
4479
      this.height += height;
4480
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
4481
      for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
4482
    },
4483
    iterN: function(at, n, op) {
4484
      for (var e = at + n; at < e; ++at)
4485
        if (op(this.lines[at])) return true;
4486
    }
4487
  };
4488
4489
  function BranchChunk(children) {
4490
    this.children = children;
4491
    var size = 0, height = 0;
4492
    for (var i = 0, e = children.length; i < e; ++i) {
4493
      var ch = children[i];
4494
      size += ch.chunkSize(); height += ch.height;
4495
      ch.parent = this;
4496
    }
4497
    this.size = size;
4498
    this.height = height;
4499
    this.parent = null;
4500
  }
4501
4502
  BranchChunk.prototype = {
4503
    chunkSize: function() { return this.size; },
4504
    removeInner: function(at, n) {
4505
      this.size -= n;
4506
      for (var i = 0; i < this.children.length; ++i) {
4507
        var child = this.children[i], sz = child.chunkSize();
4508
        if (at < sz) {
4509
          var rm = Math.min(n, sz - at), oldHeight = child.height;
4510
          child.removeInner(at, rm);
4511
          this.height -= oldHeight - child.height;
4512
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
4513
          if ((n -= rm) == 0) break;
4514
          at = 0;
4515
        } else at -= sz;
4516
      }
4517
      if (this.size - n < 25) {
4518
        var lines = [];
4519
        this.collapse(lines);
4520
        this.children = [new LeafChunk(lines)];
4521
        this.children[0].parent = this;
4522
      }
4523
    },
4524
    collapse: function(lines) {
4525
      for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
4526
    },
4527
    insertInner: function(at, lines, height) {
4528
      this.size += lines.length;
4529
      this.height += height;
4530
      for (var i = 0, e = this.children.length; i < e; ++i) {
4531
        var child = this.children[i], sz = child.chunkSize();
4532
        if (at <= sz) {
4533
          child.insertInner(at, lines, height);
4534
          if (child.lines && child.lines.length > 50) {
4535
            while (child.lines.length > 50) {
4536
              var spilled = child.lines.splice(child.lines.length - 25, 25);
4537
              var newleaf = new LeafChunk(spilled);
4538
              child.height -= newleaf.height;
4539
              this.children.splice(i + 1, 0, newleaf);
4540
              newleaf.parent = this;
4541
            }
4542
            this.maybeSpill();
4543
          }
4544
          break;
4545
        }
4546
        at -= sz;
4547
      }
4548
    },
4549
    maybeSpill: function() {
4550
      if (this.children.length <= 10) return;
4551
      var me = this;
4552
      do {
4553
        var spilled = me.children.splice(me.children.length - 5, 5);
4554
        var sibling = new BranchChunk(spilled);
4555
        if (!me.parent) { // Become the parent node
4556
          var copy = new BranchChunk(me.children);
4557
          copy.parent = me;
4558
          me.children = [copy, sibling];
4559
          me = copy;
4560
        } else {
4561
          me.size -= sibling.size;
4562
          me.height -= sibling.height;
4563
          var myIndex = indexOf(me.parent.children, me);
4564
          me.parent.children.splice(myIndex + 1, 0, sibling);
4565
        }
4566
        sibling.parent = me.parent;
4567
      } while (me.children.length > 10);
4568
      me.parent.maybeSpill();
4569
    },
4570
    iterN: function(at, n, op) {
4571
      for (var i = 0, e = this.children.length; i < e; ++i) {
4572
        var child = this.children[i], sz = child.chunkSize();
4573
        if (at < sz) {
4574
          var used = Math.min(n, sz - at);
4575
          if (child.iterN(at, used, op)) return true;
4576
          if ((n -= used) == 0) break;
4577
          at = 0;
4578
        } else at -= sz;
4579
      }
4580
    }
4581
  };
4582
4583
  var nextDocId = 0;
4584
  var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
4585
    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
4586
    if (firstLine == null) firstLine = 0;
4587
4588
    BranchChunk.call(this, [new LeafChunk([makeLine("", null)])]);
4589
    this.first = firstLine;
4590
    this.scrollTop = this.scrollLeft = 0;
4591
    this.cantEdit = false;
4592
    this.history = makeHistory();
4593
    this.cleanGeneration = 1;
4594
    this.frontier = firstLine;
4595
    var start = Pos(firstLine, 0);
4596
    this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
4597
    this.id = ++nextDocId;
4598
    this.modeOption = mode;
4599
4600
    if (typeof text == "string") text = splitLines(text);
4601
    updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
4602
  };
4603
4604
  Doc.prototype = createObj(BranchChunk.prototype, {
4605
    constructor: Doc,
4606
    iter: function(from, to, op) {
4607
      if (op) this.iterN(from - this.first, to - from, op);
4608
      else this.iterN(this.first, this.first + this.size, from);
4609
    },
4610
4611
    insert: function(at, lines) {
4612
      var height = 0;
4613
      for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
4614
      this.insertInner(at - this.first, lines, height);
4615
    },
4616
    remove: function(at, n) { this.removeInner(at - this.first, n); },
4617
4618
    getValue: function(lineSep) {
4619
      var lines = getLines(this, this.first, this.first + this.size);
4620
      if (lineSep === false) return lines;
4621
      return lines.join(lineSep || "\n");
4622
    },
4623
    setValue: function(code) {
4624
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
4625
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
4626
                        text: splitLines(code), origin: "setValue"},
4627
                 {head: top, anchor: top}, true);
4628
    },
4629
    replaceRange: function(code, from, to, origin) {
4630
      from = clipPos(this, from);
4631
      to = to ? clipPos(this, to) : from;
4632
      replaceRange(this, code, from, to, origin);
4633
    },
4634
    getRange: function(from, to, lineSep) {
4635
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
4636
      if (lineSep === false) return lines;
4637
      return lines.join(lineSep || "\n");
4638
    },
4639
4640
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
4641
    setLine: function(line, text) {
4642
      if (isLine(this, line))
4643
        replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
4644
    },
4645
    removeLine: function(line) {
4646
      if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
4647
      else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
4648
    },
4649
4650
    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
4651
    getLineNumber: function(line) {return lineNo(line);},
4652
4653
    lineCount: function() {return this.size;},
4654
    firstLine: function() {return this.first;},
4655
    lastLine: function() {return this.first + this.size - 1;},
4656
4657
    clipPos: function(pos) {return clipPos(this, pos);},
4658
4659
    getCursor: function(start) {
4660
      var sel = this.sel, pos;
4661
      if (start == null || start == "head") pos = sel.head;
4662
      else if (start == "anchor") pos = sel.anchor;
4663
      else if (start == "end" || start === false) pos = sel.to;
4664
      else pos = sel.from;
4665
      return copyPos(pos);
4666
    },
4667
    somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
4668
4669
    setCursor: docOperation(function(line, ch, extend) {
4670
      var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
4671
      if (extend) extendSelection(this, pos);
4672
      else setSelection(this, pos, pos);
4673
    }),
4674
    setSelection: docOperation(function(anchor, head) {
4675
      setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor));
4676
    }),
4677
    extendSelection: docOperation(function(from, to) {
4678
      extendSelection(this, clipPos(this, from), to && clipPos(this, to));
4679
    }),
4680
4681
    getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
4682
    replaceSelection: function(code, collapse, origin) {
4683
      makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
4684
    },
4685
    undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
4686
    redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
4687
4688
    setExtending: function(val) {this.sel.extend = val;},
4689
4690
    historySize: function() {
4691
      var hist = this.history;
4692
      return {undo: hist.done.length, redo: hist.undone.length};
4693
    },
4694
    clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
4695
4696
    markClean: function() {
4697
      this.cleanGeneration = this.changeGeneration();
4698
    },
4699
    changeGeneration: function() {
4700
      this.history.lastOp = this.history.lastOrigin = null;
4701
      return this.history.generation;
4702
    },
4703
    isClean: function (gen) {
4704
      return this.history.generation == (gen || this.cleanGeneration);
4705
    },
4706
4707
    getHistory: function() {
4708
      return {done: copyHistoryArray(this.history.done),
4709
              undone: copyHistoryArray(this.history.undone)};
4710
    },
4711
    setHistory: function(histData) {
4712
      var hist = this.history = makeHistory(this.history.maxGeneration);
4713
      hist.done = histData.done.slice(0);
4714
      hist.undone = histData.undone.slice(0);
4715
    },
4716
4717
    markText: function(from, to, options) {
4718
      return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
4719
    },
4720
    setBookmark: function(pos, options) {
4721
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
4722
                      insertLeft: options && options.insertLeft};
4723
      pos = clipPos(this, pos);
4724
      return markText(this, pos, pos, realOpts, "bookmark");
4725
    },
4726
    findMarksAt: function(pos) {
4727
      pos = clipPos(this, pos);
4728
      var markers = [], spans = getLine(this, pos.line).markedSpans;
4729
      if (spans) for (var i = 0; i < spans.length; ++i) {
4730
        var span = spans[i];
4731
        if ((span.from == null || span.from <= pos.ch) &&
4732
            (span.to == null || span.to >= pos.ch))
4733
          markers.push(span.marker.parent || span.marker);
4734
      }
4735
      return markers;
4736
    },
4737
    getAllMarks: function() {
4738
      var markers = [];
4739
      this.iter(function(line) {
4740
        var sps = line.markedSpans;
4741
        if (sps) for (var i = 0; i < sps.length; ++i)
4742
          if (sps[i].from != null) markers.push(sps[i].marker);
4743
      });
4744
      return markers;
4745
    },
4746
4747
    posFromIndex: function(off) {
4748
      var ch, lineNo = this.first;
4749
      this.iter(function(line) {
4750
        var sz = line.text.length + 1;
4751
        if (sz > off) { ch = off; return true; }
4752
        off -= sz;
4753
        ++lineNo;
4754
      });
4755
      return clipPos(this, Pos(lineNo, ch));
4756
    },
4757
    indexFromPos: function (coords) {
4758
      coords = clipPos(this, coords);
4759
      var index = coords.ch;
4760
      if (coords.line < this.first || coords.ch < 0) return 0;
4761
      this.iter(this.first, coords.line, function (line) {
4762
        index += line.text.length + 1;
4763
      });
4764
      return index;
4765
    },
4766
4767
    copy: function(copyHistory) {
4768
      var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
4769
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
4770
      doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
4771
                 shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
4772
      if (copyHistory) {
4773
        doc.history.undoDepth = this.history.undoDepth;
4774
        doc.setHistory(this.getHistory());
4775
      }
4776
      return doc;
4777
    },
4778
4779
    linkedDoc: function(options) {
4780
      if (!options) options = {};
4781
      var from = this.first, to = this.first + this.size;
4782
      if (options.from != null && options.from > from) from = options.from;
4783
      if (options.to != null && options.to < to) to = options.to;
4784
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
4785
      if (options.sharedHist) copy.history = this.history;
4786
      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
4787
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
4788
      return copy;
4789
    },
4790
    unlinkDoc: function(other) {
4791
      if (other instanceof CodeMirror) other = other.doc;
4792
      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
4793
        var link = this.linked[i];
4794
        if (link.doc != other) continue;
4795
        this.linked.splice(i, 1);
4796
        other.unlinkDoc(this);
4797
        break;
4798
      }
4799
      // If the histories were shared, split them again
4800
      if (other.history == this.history) {
4801
        var splitIds = [other.id];
4802
        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
4803
        other.history = makeHistory();
4804
        other.history.done = copyHistoryArray(this.history.done, splitIds);
4805
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
4806
      }
4807
    },
4808
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
4809
4810
    getMode: function() {return this.mode;},
4811
    getEditor: function() {return this.cm;}
4812
  });
4813
4814
  Doc.prototype.eachLine = Doc.prototype.iter;
4815
4816
  // The Doc methods that should be available on CodeMirror instances
4817
  var dontDelegate = "iter insert remove copy getEditor".split(" ");
4818
  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
4819
    CodeMirror.prototype[prop] = (function(method) {
4820
      return function() {return method.apply(this.doc, arguments);};
4821
    })(Doc.prototype[prop]);
4822
4823
  function linkedDocs(doc, f, sharedHistOnly) {
4824
    function propagate(doc, skip, sharedHist) {
4825
      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
4826
        var rel = doc.linked[i];
4827
        if (rel.doc == skip) continue;
4828
        var shared = sharedHist && rel.sharedHist;
4829
        if (sharedHistOnly && !shared) continue;
4830
        f(rel.doc, shared);
4831
        propagate(rel.doc, doc, shared);
4832
      }
4833
    }
4834
    propagate(doc, null, true);
4835
  }
4836
4837
  function attachDoc(cm, doc) {
4838
    if (doc.cm) throw new Error("This document is already in use.");
4839
    cm.doc = doc;
4840
    doc.cm = cm;
4841
    estimateLineHeights(cm);
4842
    loadMode(cm);
4843
    if (!cm.options.lineWrapping) computeMaxLength(cm);
4844
    cm.options.mode = doc.modeOption;
4845
    regChange(cm);
4846
  }
4847
4848
  // LINE UTILITIES
4849
4850
  function getLine(chunk, n) {
4851
    n -= chunk.first;
4852
    while (!chunk.lines) {
4853
      for (var i = 0;; ++i) {
4854
        var child = chunk.children[i], sz = child.chunkSize();
4855
        if (n < sz) { chunk = child; break; }
4856
        n -= sz;
4857
      }
4858
    }
4859
    return chunk.lines[n];
4860
  }
4861
4862
  function getBetween(doc, start, end) {
4863
    var out = [], n = start.line;
4864
    doc.iter(start.line, end.line + 1, function(line) {
4865
      var text = line.text;
4866
      if (n == end.line) text = text.slice(0, end.ch);
4867
      if (n == start.line) text = text.slice(start.ch);
4868
      out.push(text);
4869
      ++n;
4870
    });
4871
    return out;
4872
  }
4873
  function getLines(doc, from, to) {
4874
    var out = [];
4875
    doc.iter(from, to, function(line) { out.push(line.text); });
4876
    return out;
4877
  }
4878
4879
  function updateLineHeight(line, height) {
4880
    var diff = height - line.height;
4881
    for (var n = line; n; n = n.parent) n.height += diff;
4882
  }
4883
4884
  function lineNo(line) {
4885
    if (line.parent == null) return null;
4886
    var cur = line.parent, no = indexOf(cur.lines, line);
4887
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
4888
      for (var i = 0;; ++i) {
4889
        if (chunk.children[i] == cur) break;
4890
        no += chunk.children[i].chunkSize();
4891
      }
4892
    }
4893
    return no + cur.first;
4894
  }
4895
4896
  function lineAtHeight(chunk, h) {
4897
    var n = chunk.first;
4898
    outer: do {
4899
      for (var i = 0, e = chunk.children.length; i < e; ++i) {
4900
        var child = chunk.children[i], ch = child.height;
4901
        if (h < ch) { chunk = child; continue outer; }
4902
        h -= ch;
4903
        n += child.chunkSize();
4904
      }
4905
      return n;
4906
    } while (!chunk.lines);
4907
    for (var i = 0, e = chunk.lines.length; i < e; ++i) {
4908
      var line = chunk.lines[i], lh = line.height;
4909
      if (h < lh) break;
4910
      h -= lh;
4911
    }
4912
    return n + i;
4913
  }
4914
4915
  function heightAtLine(cm, lineObj) {
4916
    lineObj = visualLine(cm.doc, lineObj);
4917
4918
    var h = 0, chunk = lineObj.parent;
4919
    for (var i = 0; i < chunk.lines.length; ++i) {
4920
      var line = chunk.lines[i];
4921
      if (line == lineObj) break;
4922
      else h += line.height;
4923
    }
4924
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
4925
      for (var i = 0; i < p.children.length; ++i) {
4926
        var cur = p.children[i];
4927
        if (cur == chunk) break;
4928
        else h += cur.height;
4929
      }
4930
    }
4931
    return h;
4932
  }
4933
4934
  function getOrder(line) {
4935
    var order = line.order;
4936
    if (order == null) order = line.order = bidiOrdering(line.text);
4937
    return order;
4938
  }
4939
4940
  // HISTORY
4941
4942
  function makeHistory(startGen) {
4943
    return {
4944
      // Arrays of history events. Doing something adds an event to
4945
      // done and clears undo. Undoing moves events from done to
4946
      // undone, redoing moves them in the other direction.
4947
      done: [], undone: [], undoDepth: Infinity,
4948
      // Used to track when changes can be merged into a single undo
4949
      // event
4950
      lastTime: 0, lastOp: null, lastOrigin: null,
4951
      // Used by the isClean() method
4952
      generation: startGen || 1, maxGeneration: startGen || 1
4953
    };
4954
  }
4955
4956
  function attachLocalSpans(doc, change, from, to) {
4957
    var existing = change["spans_" + doc.id], n = 0;
4958
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
4959
      if (line.markedSpans)
4960
        (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
4961
      ++n;
4962
    });
4963
  }
4964
4965
  function historyChangeFromChange(doc, change) {
4966
    var histChange = {from: change.from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4967
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4968
    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
4969
    return histChange;
4970
  }
4971
4972
  function addToHistory(doc, change, selAfter, opId) {
4973
    var hist = doc.history;
4974
    hist.undone.length = 0;
4975
    var time = +new Date, cur = lst(hist.done);
4976
4977
    if (cur &&
4978
        (hist.lastOp == opId ||
4979
         hist.lastOrigin == change.origin && change.origin &&
4980
         ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
4981
          change.origin.charAt(0) == "*"))) {
4982
      // Merge this change into the last event
4983
      var last = lst(cur.changes);
4984
      if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
4985
        // Optimized case for simple insertion -- don't want to add
4986
        // new changesets for every character typed
4987
        last.to = changeEnd(change);
4988
      } else {
4989
        // Add new sub-event
4990
        cur.changes.push(historyChangeFromChange(doc, change));
4991
      }
4992
      cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
4993
    } else {
4994
      // Can not be merged, start a new event.
4995
      cur = {changes: [historyChangeFromChange(doc, change)],
4996
             generation: hist.generation,
4997
             anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
4998
             anchorAfter: selAfter.anchor, headAfter: selAfter.head};
4999
      hist.done.push(cur);
5000
      hist.generation = ++hist.maxGeneration;
5001
      while (hist.done.length > hist.undoDepth)
5002
        hist.done.shift();
5003
    }
5004
    hist.lastTime = time;
5005
    hist.lastOp = opId;
5006
    hist.lastOrigin = change.origin;
5007
  }
5008
5009
  function removeClearedSpans(spans) {
5010
    if (!spans) return null;
5011
    for (var i = 0, out; i < spans.length; ++i) {
5012
      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
5013
      else if (out) out.push(spans[i]);
5014
    }
5015
    return !out ? spans : out.length ? out : null;
5016
  }
5017
5018
  function getOldSpans(doc, change) {
5019
    var found = change["spans_" + doc.id];
5020
    if (!found) return null;
5021
    for (var i = 0, nw = []; i < change.text.length; ++i)
5022
      nw.push(removeClearedSpans(found[i]));
5023
    return nw;
5024
  }
5025
5026
  // Used both to provide a JSON-safe object in .getHistory, and, when
5027
  // detaching a document, to split the history in two
5028
  function copyHistoryArray(events, newGroup) {
5029
    for (var i = 0, copy = []; i < events.length; ++i) {
5030
      var event = events[i], changes = event.changes, newChanges = [];
5031
      copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
5032
                 anchorAfter: event.anchorAfter, headAfter: event.headAfter});
5033
      for (var j = 0; j < changes.length; ++j) {
5034
        var change = changes[j], m;
5035
        newChanges.push({from: change.from, to: change.to, text: change.text});
5036
        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
5037
          if (indexOf(newGroup, Number(m[1])) > -1) {
5038
            lst(newChanges)[prop] = change[prop];
5039
            delete change[prop];
5040
          }
5041
        }
5042
      }
5043
    }
5044
    return copy;
5045
  }
5046
5047
  // Rebasing/resetting history to deal with externally-sourced changes
5048
5049
  function rebaseHistSel(pos, from, to, diff) {
5050
    if (to < pos.line) {
5051
      pos.line += diff;
5052
    } else if (from < pos.line) {
5053
      pos.line = from;
5054
      pos.ch = 0;
5055
    }
5056
  }
5057
5058
  // Tries to rebase an array of history events given a change in the
5059
  // document. If the change touches the same lines as the event, the
5060
  // event, and everything 'behind' it, is discarded. If the change is
5061
  // before the event, the event's positions are updated. Uses a
5062
  // copy-on-write scheme for the positions, to avoid having to
5063
  // reallocate them all on every rebase, but also avoid problems with
5064
  // shared position objects being unsafely updated.
5065
  function rebaseHistArray(array, from, to, diff) {
5066
    for (var i = 0; i < array.length; ++i) {
5067
      var sub = array[i], ok = true;
5068
      for (var j = 0; j < sub.changes.length; ++j) {
5069
        var cur = sub.changes[j];
5070
        if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
5071
        if (to < cur.from.line) {
5072
          cur.from.line += diff;
5073
          cur.to.line += diff;
5074
        } else if (from <= cur.to.line) {
5075
          ok = false;
5076
          break;
5077
        }
5078
      }
5079
      if (!sub.copied) {
5080
        sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
5081
        sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
5082
        sub.copied = true;
5083
      }
5084
      if (!ok) {
5085
        array.splice(0, i + 1);
5086
        i = 0;
5087
      } else {
5088
        rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
5089
        rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
5090
      }
5091
    }
5092
  }
5093
5094
  function rebaseHist(hist, change) {
5095
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5096
    rebaseHistArray(hist.done, from, to, diff);
5097
    rebaseHistArray(hist.undone, from, to, diff);
5098
  }
5099
5100
  // EVENT OPERATORS
5101
5102
  function stopMethod() {e_stop(this);}
5103
  // Ensure an event has a stop method.
5104
  function addStop(event) {
5105
    if (!event.stop) event.stop = stopMethod;
5106
    return event;
5107
  }
5108
5109
  function e_preventDefault(e) {
5110
    if (e.preventDefault) e.preventDefault();
5111
    else e.returnValue = false;
5112
  }
5113
  function e_stopPropagation(e) {
5114
    if (e.stopPropagation) e.stopPropagation();
5115
    else e.cancelBubble = true;
5116
  }
5117
  function e_defaultPrevented(e) {
5118
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
5119
  }
5120
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
5121
  CodeMirror.e_stop = e_stop;
5122
  CodeMirror.e_preventDefault = e_preventDefault;
5123
  CodeMirror.e_stopPropagation = e_stopPropagation;
5124
5125
  function e_target(e) {return e.target || e.srcElement;}
5126
  function e_button(e) {
5127
    var b = e.which;
5128
    if (b == null) {
5129
      if (e.button & 1) b = 1;
5130
      else if (e.button & 2) b = 3;
5131
      else if (e.button & 4) b = 2;
5132
    }
5133
    if (mac && e.ctrlKey && b == 1) b = 3;
5134
    return b;
5135
  }
5136
5137
  // EVENT HANDLING
5138
5139
  function on(emitter, type, f) {
5140
    if (emitter.addEventListener)
5141
      emitter.addEventListener(type, f, false);
5142
    else if (emitter.attachEvent)
5143
      emitter.attachEvent("on" + type, f);
5144
    else {
5145
      var map = emitter._handlers || (emitter._handlers = {});
5146
      var arr = map[type] || (map[type] = []);
5147
      arr.push(f);
5148
    }
5149
  }
5150
5151
  function off(emitter, type, f) {
5152
    if (emitter.removeEventListener)
5153
      emitter.removeEventListener(type, f, false);
5154
    else if (emitter.detachEvent)
5155
      emitter.detachEvent("on" + type, f);
5156
    else {
5157
      var arr = emitter._handlers && emitter._handlers[type];
5158
      if (!arr) return;
5159
      for (var i = 0; i < arr.length; ++i)
5160
        if (arr[i] == f) { arr.splice(i, 1); break; }
5161
    }
5162
  }
5163
5164
  function signal(emitter, type /*, values...*/) {
5165
    var arr = emitter._handlers && emitter._handlers[type];
5166
    if (!arr) return;
5167
    var args = Array.prototype.slice.call(arguments, 2);
5168
    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
5169
  }
5170
5171
  var delayedCallbacks, delayedCallbackDepth = 0;
5172
  function signalLater(emitter, type /*, values...*/) {
5173
    var arr = emitter._handlers && emitter._handlers[type];
5174
    if (!arr) return;
5175
    var args = Array.prototype.slice.call(arguments, 2);
5176
    if (!delayedCallbacks) {
5177
      ++delayedCallbackDepth;
5178
      delayedCallbacks = [];
5179
      setTimeout(fireDelayed, 0);
5180
    }
5181
    function bnd(f) {return function(){f.apply(null, args);};};
5182
    for (var i = 0; i < arr.length; ++i)
5183
      delayedCallbacks.push(bnd(arr[i]));
5184
  }
5185
5186
  function signalDOMEvent(cm, e) {
5187
    signal(cm, e.type, cm, e);
5188
    return e_defaultPrevented(e);
5189
  }
5190
5191
  function fireDelayed() {
5192
    --delayedCallbackDepth;
5193
    var delayed = delayedCallbacks;
5194
    delayedCallbacks = null;
5195
    for (var i = 0; i < delayed.length; ++i) delayed[i]();
5196
  }
5197
5198
  function hasHandler(emitter, type) {
5199
    var arr = emitter._handlers && emitter._handlers[type];
5200
    return arr && arr.length > 0;
5201
  }
5202
5203
  CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
5204
5205
  // MISC UTILITIES
5206
5207
  // Number of pixels added to scroller and sizer to hide scrollbar
5208
  var scrollerCutOff = 30;
5209
5210
  // Returned or thrown by various protocols to signal 'I'm not
5211
  // handling this'.
5212
  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
5213
5214
  function Delayed() {this.id = null;}
5215
  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
5216
5217
  // Counts the column offset in a string, taking tabs into account.
5218
  // Used mostly to find indentation.
5219
  function countColumn(string, end, tabSize, startIndex, startValue) {
5220
    if (end == null) {
5221
      end = string.search(/[^\s\u00a0]/);
5222
      if (end == -1) end = string.length;
5223
    }
5224
    for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
5225
      if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
5226
      else ++n;
5227
    }
5228
    return n;
5229
  }
5230
  CodeMirror.countColumn = countColumn;
5231
5232
  var spaceStrs = [""];
5233
  function spaceStr(n) {
5234
    while (spaceStrs.length <= n)
5235
      spaceStrs.push(lst(spaceStrs) + " ");
5236
    return spaceStrs[n];
5237
  }
5238
5239
  function lst(arr) { return arr[arr.length-1]; }
5240
5241
  function selectInput(node) {
5242
    if (ios) { // Mobile Safari apparently has a bug where select() is broken.
5243
      node.selectionStart = 0;
5244
      node.selectionEnd = node.value.length;
5245
    } else {
5246
      // Suppress mysterious IE10 errors
5247
      try { node.select(); }
5248
      catch(_e) {}
5249
    }
5250
  }
5251
5252
  function indexOf(collection, elt) {
5253
    if (collection.indexOf) return collection.indexOf(elt);
5254
    for (var i = 0, e = collection.length; i < e; ++i)
5255
      if (collection[i] == elt) return i;
5256
    return -1;
5257
  }
5258
5259
  function createObj(base, props) {
5260
    function Obj() {}
5261
    Obj.prototype = base;
5262
    var inst = new Obj();
5263
    if (props) copyObj(props, inst);
5264
    return inst;
5265
  }
5266
5267
  function copyObj(obj, target) {
5268
    if (!target) target = {};
5269
    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
5270
    return target;
5271
  }
5272
5273
  function emptyArray(size) {
5274
    for (var a = [], i = 0; i < size; ++i) a.push(undefined);
5275
    return a;
5276
  }
5277
5278
  function bind(f) {
5279
    var args = Array.prototype.slice.call(arguments, 1);
5280
    return function(){return f.apply(null, args);};
5281
  }
5282
5283
  var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
5284
  function isWordChar(ch) {
5285
    return /\w/.test(ch) || ch > "\x80" &&
5286
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
5287
  }
5288
5289
  function isEmpty(obj) {
5290
    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
5291
    return true;
5292
  }
5293
5294
  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]/;
5295
5296
  // DOM UTILITIES
5297
5298
  function elt(tag, content, className, style) {
5299
    var e = document.createElement(tag);
5300
    if (className) e.className = className;
5301
    if (style) e.style.cssText = style;
5302
    if (typeof content == "string") setTextContent(e, content);
5303
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
5304
    return e;
5305
  }
5306
5307
  function removeChildren(e) {
5308
    for (var count = e.childNodes.length; count > 0; --count)
5309
      e.removeChild(e.firstChild);
5310
    return e;
5311
  }
5312
5313
  function removeChildrenAndAdd(parent, e) {
5314
    return removeChildren(parent).appendChild(e);
5315
  }
5316
5317
  function setTextContent(e, str) {
5318
    if (ie_lt9) {
5319
      e.innerHTML = "";
5320
      e.appendChild(document.createTextNode(str));
5321
    } else e.textContent = str;
5322
  }
5323
5324
  function getRect(node) {
5325
    return node.getBoundingClientRect();
5326
  }
5327
  CodeMirror.replaceGetRect = function(f) { getRect = f; };
5328
5329
  // FEATURE DETECTION
5330
5331
  // Detect drag-and-drop
5332
  var dragAndDrop = function() {
5333
    // There is *some* kind of drag-and-drop support in IE6-8, but I
5334
    // couldn't get it to work yet.
5335
    if (ie_lt9) return false;
5336
    var div = elt('div');
5337
    return "draggable" in div || "dragDrop" in div;
5338
  }();
5339
5340
  // For a reason I have yet to figure out, some browsers disallow
5341
  // word wrapping between certain characters *only* if a new inline
5342
  // element is started between them. This makes it hard to reliably
5343
  // measure the position of things, since that requires inserting an
5344
  // extra span. This terribly fragile set of tests matches the
5345
  // character combinations that suffer from this phenomenon on the
5346
  // various browsers.
5347
  function spanAffectsWrapping() { return false; }
5348
  if (gecko) // Only for "$'"
5349
    spanAffectsWrapping = function(str, i) {
5350
      return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
5351
    };
5352
  else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
5353
    spanAffectsWrapping = function(str, i) {
5354
      return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
5355
    };
5356
  else if (webkit)
5357
    spanAffectsWrapping = function(str, i) {
5358
      if (i > 1 && str.charCodeAt(i - 1) == 45 && /\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i)))
5359
        return true;
5360
      return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
5361
    };
5362
5363
  var knownScrollbarWidth;
5364
  function scrollbarWidth(measure) {
5365
    if (knownScrollbarWidth != null) return knownScrollbarWidth;
5366
    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
5367
    removeChildrenAndAdd(measure, test);
5368
    if (test.offsetWidth)
5369
      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
5370
    return knownScrollbarWidth || 0;
5371
  }
5372
5373
  var zwspSupported;
5374
  function zeroWidthElement(measure) {
5375
    if (zwspSupported == null) {
5376
      var test = elt("span", "\u200b");
5377
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
5378
      if (measure.firstChild.offsetHeight != 0)
5379
        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
5380
    }
5381
    if (zwspSupported) return elt("span", "\u200b");
5382
    else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
5383
  }
5384
5385
  // See if "".split is the broken IE version, if so, provide an
5386
  // alternative way to split lines.
5387
  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
5388
    var pos = 0, result = [], l = string.length;
5389
    while (pos <= l) {
5390
      var nl = string.indexOf("\n", pos);
5391
      if (nl == -1) nl = string.length;
5392
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
5393
      var rt = line.indexOf("\r");
5394
      if (rt != -1) {
5395
        result.push(line.slice(0, rt));
5396
        pos += rt + 1;
5397
      } else {
5398
        result.push(line);
5399
        pos = nl + 1;
5400
      }
5401
    }
5402
    return result;
5403
  } : function(string){return string.split(/\r\n?|\n/);};
5404
  CodeMirror.splitLines = splitLines;
5405
5406
  var hasSelection = window.getSelection ? function(te) {
5407
    try { return te.selectionStart != te.selectionEnd; }
5408
    catch(e) { return false; }
5409
  } : function(te) {
5410
    try {var range = te.ownerDocument.selection.createRange();}
5411
    catch(e) {}
5412
    if (!range || range.parentElement() != te) return false;
5413
    return range.compareEndPoints("StartToEnd", range) != 0;
5414
  };
5415
5416
  var hasCopyEvent = (function() {
5417
    var e = elt("div");
5418
    if ("oncopy" in e) return true;
5419
    e.setAttribute("oncopy", "return;");
5420
    return typeof e.oncopy == 'function';
5421
  })();
5422
5423
  // KEY NAMING
5424
5425
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
5426
                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
5427
                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
5428
                  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
5429
                  186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
5430
                  221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
5431
                  63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
5432
  CodeMirror.keyNames = keyNames;
5433
  (function() {
5434
    // Number keys
5435
    for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
5436
    // Alphabetic keys
5437
    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
5438
    // Function keys
5439
    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
5440
  })();
5441
5442
  // BIDI HELPERS
5443
5444
  function iterateBidiSections(order, from, to, f) {
5445
    if (!order) return f(from, to, "ltr");
5446
    for (var i = 0; i < order.length; ++i) {
5447
      var part = order[i];
5448
      if (part.from < to && part.to > from || from == to && part.to == from)
5449
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
5450
    }
5451
  }
5452
5453
  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
5454
  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
5455
5456
  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
5457
  function lineRight(line) {
5458
    var order = getOrder(line);
5459
    if (!order) return line.text.length;
5460
    return bidiRight(lst(order));
5461
  }
5462
5463
  function lineStart(cm, lineN) {
5464
    var line = getLine(cm.doc, lineN);
5465
    var visual = visualLine(cm.doc, line);
5466
    if (visual != line) lineN = lineNo(visual);
5467
    var order = getOrder(visual);
5468
    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
5469
    return Pos(lineN, ch);
5470
  }
5471
  function lineEnd(cm, lineN) {
5472
    var merged, line;
5473
    while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
5474
      lineN = merged.find().to.line;
5475
    var order = getOrder(line);
5476
    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
5477
    return Pos(lineN, ch);
5478
  }
5479
5480
  function compareBidiLevel(order, a, b) {
5481
    var linedir = order[0].level;
5482
    if (a == linedir) return true;
5483
    if (b == linedir) return false;
5484
    return a < b;
5485
  }
5486
  var bidiOther;
5487
  function getBidiPartAt(order, pos) {
5488
    for (var i = 0, found; i < order.length; ++i) {
5489
      var cur = order[i];
5490
      if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; }
5491
      if (cur.from == pos || cur.to == pos) {
5492
        if (found == null) {
5493
          found = i;
5494
        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
5495
          bidiOther = found;
5496
          return i;
5497
        } else {
5498
          bidiOther = i;
5499
          return found;
5500
        }
5501
      }
5502
    }
5503
    bidiOther = null;
5504
    return found;
5505
  }
5506
5507
  function moveInLine(line, pos, dir, byUnit) {
5508
    if (!byUnit) return pos + dir;
5509
    do pos += dir;
5510
    while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
5511
    return pos;
5512
  }
5513
5514
  // This is somewhat involved. It is needed in order to move
5515
  // 'visually' through bi-directional text -- i.e., pressing left
5516
  // should make the cursor go left, even when in RTL text. The
5517
  // tricky part is the 'jumps', where RTL and LTR text touch each
5518
  // other. This often requires the cursor offset to move more than
5519
  // one unit, in order to visually move one unit.
5520
  function moveVisually(line, start, dir, byUnit) {
5521
    var bidi = getOrder(line);
5522
    if (!bidi) return moveLogically(line, start, dir, byUnit);
5523
    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
5524
    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
5525
5526
    for (;;) {
5527
      if (target > part.from && target < part.to) return target;
5528
      if (target == part.from || target == part.to) {
5529
        if (getBidiPartAt(bidi, target) == pos) return target;
5530
        part = bidi[pos += dir];
5531
        return (dir > 0) == part.level % 2 ? part.to : part.from;
5532
      } else {
5533
        part = bidi[pos += dir];
5534
        if (!part) return null;
5535
        if ((dir > 0) == part.level % 2)
5536
          target = moveInLine(line, part.to, -1, byUnit);
5537
        else
5538
          target = moveInLine(line, part.from, 1, byUnit);
5539
      }
5540
    }
5541
  }
5542
5543
  function moveLogically(line, start, dir, byUnit) {
5544
    var target = start + dir;
5545
    if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
5546
    return target < 0 || target > line.text.length ? null : target;
5547
  }
5548
5549
  // Bidirectional ordering algorithm
5550
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
5551
  // that this (partially) implements.
5552
5553
  // One-char codes used for character types:
5554
  // L (L):   Left-to-Right
5555
  // R (R):   Right-to-Left
5556
  // r (AL):  Right-to-Left Arabic
5557
  // 1 (EN):  European Number
5558
  // + (ES):  European Number Separator
5559
  // % (ET):  European Number Terminator
5560
  // n (AN):  Arabic Number
5561
  // , (CS):  Common Number Separator
5562
  // m (NSM): Non-Spacing Mark
5563
  // b (BN):  Boundary Neutral
5564
  // s (B):   Paragraph Separator
5565
  // t (S):   Segment Separator
5566
  // w (WS):  Whitespace
5567
  // N (ON):  Other Neutrals
5568
5569
  // Returns null if characters are ordered as they appear
5570
  // (left-to-right), or an array of sections ({from, to, level}
5571
  // objects) in the order in which they occur visually.
5572
  var bidiOrdering = (function() {
5573
    // Character types for codepoints 0 to 0xff
5574
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
5575
    // Character types for codepoints 0x600 to 0x6ff
5576
    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
5577
    function charType(code) {
5578
      if (code <= 0xff) return lowTypes.charAt(code);
5579
      else if (0x590 <= code && code <= 0x5f4) return "R";
5580
      else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
5581
      else if (0x700 <= code && code <= 0x8ac) return "r";
5582
      else return "L";
5583
    }
5584
5585
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
5586
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
5587
    // Browsers seem to always treat the boundaries of block elements as being L.
5588
    var outerType = "L";
5589
5590
    return function(str) {
5591
      if (!bidiRE.test(str)) return false;
5592
      var len = str.length, types = [];
5593
      for (var i = 0, type; i < len; ++i)
5594
        types.push(type = charType(str.charCodeAt(i)));
5595
5596
      // W1. Examine each non-spacing mark (NSM) in the level run, and
5597
      // change the type of the NSM to the type of the previous
5598
      // character. If the NSM is at the start of the level run, it will
5599
      // get the type of sor.
5600
      for (var i = 0, prev = outerType; i < len; ++i) {
5601
        var type = types[i];
5602
        if (type == "m") types[i] = prev;
5603
        else prev = type;
5604
      }
5605
5606
      // W2. Search backwards from each instance of a European number
5607
      // until the first strong type (R, L, AL, or sor) is found. If an
5608
      // AL is found, change the type of the European number to Arabic
5609
      // number.
5610
      // W3. Change all ALs to R.
5611
      for (var i = 0, cur = outerType; i < len; ++i) {
5612
        var type = types[i];
5613
        if (type == "1" && cur == "r") types[i] = "n";
5614
        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
5615
      }
5616
5617
      // W4. A single European separator between two European numbers
5618
      // changes to a European number. A single common separator between
5619
      // two numbers of the same type changes to that type.
5620
      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
5621
        var type = types[i];
5622
        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
5623
        else if (type == "," && prev == types[i+1] &&
5624
                 (prev == "1" || prev == "n")) types[i] = prev;
5625
        prev = type;
5626
      }
5627
5628
      // W5. A sequence of European terminators adjacent to European
5629
      // numbers changes to all European numbers.
5630
      // W6. Otherwise, separators and terminators change to Other
5631
      // Neutral.
5632
      for (var i = 0; i < len; ++i) {
5633
        var type = types[i];
5634
        if (type == ",") types[i] = "N";
5635
        else if (type == "%") {
5636
          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
5637
          var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
5638
          for (var j = i; j < end; ++j) types[j] = replace;
5639
          i = end - 1;
5640
        }
5641
      }
5642
5643
      // W7. Search backwards from each instance of a European number
5644
      // until the first strong type (R, L, or sor) is found. If an L is
5645
      // found, then change the type of the European number to L.
5646
      for (var i = 0, cur = outerType; i < len; ++i) {
5647
        var type = types[i];
5648
        if (cur == "L" && type == "1") types[i] = "L";
5649
        else if (isStrong.test(type)) cur = type;
5650
      }
5651
5652
      // N1. A sequence of neutrals takes the direction of the
5653
      // surrounding strong text if the text on both sides has the same
5654
      // direction. European and Arabic numbers act as if they were R in
5655
      // terms of their influence on neutrals. Start-of-level-run (sor)
5656
      // and end-of-level-run (eor) are used at level run boundaries.
5657
      // N2. Any remaining neutrals take the embedding direction.
5658
      for (var i = 0; i < len; ++i) {
5659
        if (isNeutral.test(types[i])) {
5660
          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
5661
          var before = (i ? types[i-1] : outerType) == "L";
5662
          var after = (end < len - 1 ? types[end] : outerType) == "L";
5663
          var replace = before || after ? "L" : "R";
5664
          for (var j = i; j < end; ++j) types[j] = replace;
5665
          i = end - 1;
5666
        }
5667
      }
5668
5669
      // Here we depart from the documented algorithm, in order to avoid
5670
      // building up an actual levels array. Since there are only three
5671
      // levels (0, 1, 2) in an implementation that doesn't take
5672
      // explicit embedding into account, we can build up the order on
5673
      // the fly, without following the level-based algorithm.
5674
      var order = [], m;
5675
      for (var i = 0; i < len;) {
5676
        if (countsAsLeft.test(types[i])) {
5677
          var start = i;
5678
          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
5679
          order.push({from: start, to: i, level: 0});
5680
        } else {
5681
          var pos = i, at = order.length;
5682
          for (++i; i < len && types[i] != "L"; ++i) {}
5683
          for (var j = pos; j < i;) {
5684
            if (countsAsNum.test(types[j])) {
5685
              if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
5686
              var nstart = j;
5687
              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
5688
              order.splice(at, 0, {from: nstart, to: j, level: 2});
5689
              pos = j;
5690
            } else ++j;
5691
          }
5692
          if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
5693
        }
5694
      }
5695
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
5696
        order[0].from = m[0].length;
5697
        order.unshift({from: 0, to: m[0].length, level: 0});
5698
      }
5699
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
5700
        lst(order).to -= m[0].length;
5701
        order.push({from: len - m[0].length, to: len, level: 0});
5702
      }
5703
      if (order[0].level != lst(order).level)
5704
        order.push({from: len, to: len, level: order[0].level});
5705
5706
      return order;
5707
    };
5708
  })();
5709
5710
  // THE END
5711
5712
  CodeMirror.version = "3.14.0";
5713
5714
  return CodeMirror;
5715
})();
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/lib/runmode.js (-56 lines)
Lines 1-56 Link Here
1
CodeMirror.runMode = function(string, modespec, callback, options) {
2
  var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
3
  var ie = /MSIE \d/.test(navigator.userAgent);
4
  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
5
6
  if (callback.nodeType == 1) {
7
    var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
8
    var node = callback, col = 0;
9
    node.innerHTML = "";
10
    callback = function(text, style) {
11
      if (text == "\n") {
12
        // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
13
        // Emitting a carriage return makes everything ok.
14
        node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
15
        col = 0;
16
        return;
17
      }
18
      var content = "";
19
      // replace tabs
20
      for (var pos = 0;;) {
21
        var idx = text.indexOf("\t", pos);
22
        if (idx == -1) {
23
          content += text.slice(pos);
24
          col += text.length - pos;
25
          break;
26
        } else {
27
          col += idx - pos;
28
          content += text.slice(pos, idx);
29
          var size = tabSize - col % tabSize;
30
          col += size;
31
          for (var i = 0; i < size; ++i) content += " ";
32
          pos = idx + 1;
33
        }
34
      }
35
36
      if (style) {
37
        var sp = node.appendChild(document.createElement("span"));
38
        sp.className = "cm-" + style.replace(/ +/g, " cm-");
39
        sp.appendChild(document.createTextNode(content));
40
      } else {
41
        node.appendChild(document.createTextNode(content));
42
      }
43
    };
44
  }
45
46
  var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
47
  for (var i = 0, e = lines.length; i < e; ++i) {
48
    if (i) callback("\n");
49
    var stream = new CodeMirror.StringStream(lines[i]);
50
    while (!stream.eol()) {
51
      var style = mode.token(stream, state);
52
      callback(stream.current(), style, i, stream.start);
53
      stream.start = stream.pos;
54
    }
55
  }
56
};
(-)a/koha-tmpl/intranet-tmpl/lib/jquery/plugins/humanmsg.js (-12 / +14 lines)
Lines 29-37 var humanMsg = { Link Here
29
	},
29
	},
30
30
31
	displayAlert: function(msg, options) {
31
	displayAlert: function(msg, options) {
32
		humanMsg.displayMsg('<p>' + msg + '</p>', $.extend({log: false}, options), true);
32
		humanMsg.displayMsg('<p>' + msg + '</p>', options);
33
	},
33
	},
34
34
35
    logMsg: function(msg) {
36
        jQuery('#'+humanMsg.logID)
37
            .show().children('ul').prepend('<li>'+msg+'</li>')	// Prepend message to log
38
            .children('li:first').slideDown(200)				// Slide it down
39
40
        if ( jQuery('#'+humanMsg.logID+' ul').css('display') == 'none') {
41
            jQuery('#'+humanMsg.logID+' p').animate({ bottom: 40 }, 200, 'linear', function() {
42
                jQuery(this).animate({ bottom: 0 }, 300, 'swing', function() { jQuery(this).css({ bottom: 0 }) })
43
            })
44
        }
45
    },
46
35
	displayMsg: function(msg, options) {
47
	displayMsg: function(msg, options) {
36
		if (msg == '')
48
		if (msg == '')
37
			return;
49
			return;
Lines 51-67 var humanMsg = { Link Here
51
63
52
		// Show message
64
		// Show message
53
		jQuery('#'+humanMsg.msgID).attr('class', 'humanMsg ' + options.className).show().animate({ opacity: humanMsg.msgOpacity}, 200, function() {
65
		jQuery('#'+humanMsg.msgID).attr('class', 'humanMsg ' + options.className).show().animate({ opacity: humanMsg.msgOpacity}, 200, function() {
54
            if ( !options.log ) return true;
66
            humanMsg.logMsg(msg, options);
55
			jQuery('#'+humanMsg.logID)
56
				.show().children('ul').prepend('<li>'+msg+'</li>')	// Prepend message to log
57
				.children('li:first').slideDown(200)				// Slide it down
58
59
			if ( jQuery('#'+humanMsg.logID+' ul').css('display') == 'none') {
60
				jQuery('#'+humanMsg.logID+' p').animate({ bottom: 40 }, 200, 'linear', function() {
61
					jQuery(this).animate({ bottom: 0 }, 300, 'swing', function() { jQuery(this).css({ bottom: 0 }) })
62
				})
63
			}
64
65
		})
67
		})
66
68
67
		// Watch for mouse & keyboard in `delay`
69
		// Watch for mouse & keyboard in `delay`
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/koha-backend.js (+201 lines)
Line 0 Link Here
1
define( [ '/cgi-bin/koha/svc/cataloguing/framework?frameworkcode=&callback=define', 'marc-record' ], function( defaultFramework, MARC ) {
2
    var _authorised_values = defaultFramework.authorised_values;
3
    var _frameworks = {};
4
    var _framework_mappings = {};
5
6
    function _fromXMLStruct( data ) {
7
        result = {};
8
9
        $(data).children().eq(0).children().each( function() {
10
            var $contents = $(this).contents();
11
            if ( $contents.length == 1 && $contents[0].nodeType == Node.TEXT_NODE ) {
12
                result[ this.localName ] = $contents[0].data;
13
            } else {
14
                result[ this.localName ] = $contents.filter( function() { return this.nodeType != Node.TEXT_NODE || !this.data.match( /^\s+$/ ) } ).toArray();
15
            }
16
        } );
17
18
        return result;
19
    }
20
21
    function _importFramework( frameworkcode, frameworkinfo ) {
22
        _frameworks[frameworkcode] = frameworkinfo;
23
        _framework_mappings[frameworkcode] = {};
24
25
        $.each( frameworkinfo, function( i, tag ) {
26
            var tagnum = tag[0], taginfo = tag[1];
27
28
            var subfields = {};
29
30
            $.each( taginfo.subfields, function( i, subfield ) {
31
                subfields[ subfield[0] ] = subfield[1];
32
            } );
33
34
            _framework_mappings[frameworkcode][tagnum] = $.extend( {}, taginfo, { subfields: subfields } );
35
        } );
36
    }
37
38
    _importFramework( '', defaultFramework.framework );
39
40
    var KohaBackend = {
41
        NOT_EMPTY: {}, // Sentinel value
42
43
        GetAllTagsInfo: function( frameworkcode, tagnumber ) {
44
            return _framework_mappings[frameworkcode];
45
        },
46
47
        GetAuthorisedValues: function( category ) {
48
            return _authorised_values[category];
49
        },
50
51
        GetTagInfo: function( frameworkcode, tagnumber ) {
52
            if ( !_framework_mappings[frameworkcode] ) return undefined;
53
            return _framework_mappings[frameworkcode][tagnumber];
54
        },
55
56
        GetRecord: function( id, callback ) {
57
            $.get(
58
                '/cgi-bin/koha/svc/bib/' + id
59
            ).done( function( data ) {
60
                var record = new MARC.Record();
61
                record.loadMARCXML(data);
62
                callback(record);
63
            } ).fail( function( data ) {
64
                callback( { data: { error: data } } );
65
            } );
66
        },
67
68
        CreateRecord: function( record, callback ) {
69
            $.ajax( {
70
                type: 'POST',
71
                url: '/cgi-bin/koha/svc/new_bib',
72
                data: record.toXML(),
73
                contentType: 'text/xml'
74
            } ).done( function( data ) {
75
                callback( _fromXMLStruct( data ) );
76
            } ).fail( function( data ) {
77
                callback( { error: data } );
78
            } );
79
        },
80
81
        SaveRecord: function( id, record, callback ) {
82
            $.ajax( {
83
                type: 'POST',
84
                url: '/cgi-bin/koha/svc/bib/' + id,
85
                data: record.toXML(),
86
                contentType: 'text/xml'
87
            } ).done( function( data ) {
88
                callback( _fromXMLStruct( data ) );
89
            } ).fail( function( data ) {
90
                callback( { data: { error: data } } );
91
            } );
92
        },
93
94
        GetTagsBy: function( frameworkcode, field, value ) {
95
            var result = {};
96
97
            $.each( _frameworks[frameworkcode], function( undef, tag ) {
98
                var tagnum = tag[0], taginfo = tag[1];
99
100
                if ( taginfo[field] == value ) result[tagnum] = true;
101
            } );
102
103
            return result;
104
        },
105
106
        GetSubfieldsBy: function( frameworkcode, field, value ) {
107
            var result = {};
108
109
            $.each( _frameworks[frameworkcode], function( undef, tag ) {
110
                var tagnum = tag[0], taginfo = tag[1];
111
112
                $.each( taginfo.subfields, function( undef, subfield ) {
113
                    var subfieldcode = subfield[0], subfieldinfo = subfield[1];
114
115
                    if ( subfieldinfo[field] == value ) {
116
                        if ( !result[tagnum] ) result[tagnum] = {};
117
118
                        result[tagnum][subfieldcode] = true;
119
                    }
120
                } );
121
            } );
122
123
            return result;
124
        },
125
126
        FillRecord: function( frameworkcode, record, allTags ) {
127
            $.each( _frameworks[frameworkcode], function( undef, tag ) {
128
                var tagnum = tag[0], taginfo = tag[1];
129
130
                if ( taginfo.mandatory != "1" && !allTags ) return;
131
132
                var fields = record.fields(tagnum);
133
134
                if ( fields.length == 0 ) {
135
                    var newField = new MARC.Field( tagnum, ' ', ' ', [] );
136
                    fields.push( newField );
137
                    record.addFieldGrouped( newField );
138
139
                    if ( tagnum < '010' ) {
140
                        newField.addSubfield( [ '@', '' ] );
141
                        return;
142
                    }
143
                }
144
145
                $.each( taginfo.subfields, function( undef, subfield ) {
146
                    var subfieldcode = subfield[0], subfieldinfo = subfield[1];
147
148
                    if ( subfieldinfo.mandatory != "1" && !allTags ) return;
149
150
                    $.each( fields, function( undef, field ) {
151
                        if ( !field.hasSubfield(subfieldcode) ) field.addSubfieldGrouped( [ subfieldcode, '' ] );
152
                    } );
153
                } );
154
            } );
155
        },
156
157
        ValidateRecord: function( frameworkcode, record ) {
158
            var errors = [];
159
160
            var mandatoryTags = KohaBackend.GetTagsBy( '', 'mandatory', '1' );
161
            var mandatorySubfields = KohaBackend.GetSubfieldsBy( '', 'mandatory', '1' );
162
            var nonRepeatableTags = KohaBackend.GetTagsBy( '', 'repeatable', '0' );
163
            var nonRepeatableSubfields = KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' );
164
165
            $.each( mandatoryTags, function( tag ) {
166
                if ( !record.hasField( tag ) ) errors.push( { type: 'missingTag', tag: tag } );
167
            } );
168
169
            var seenTags = {};
170
171
            $.each( record.fields(), function( undef, field ) {
172
                if ( seenTags[ field.tagnumber() ] && nonRepeatableTags[ field.tagnumber() ] ) {
173
                    errors.push( { type: 'unrepeatableTag', line: field.sourceLine, tag: field.tagnumber() } );
174
                    return;
175
                }
176
177
                seenTags[ field.tagnumber() ] = true;
178
179
                var seenSubfields = {};
180
181
                $.each( field.subfields(), function( undef, subfield ) {
182
                    if ( seenSubfields[ subfield[0] ] != null && nonRepeatableSubfields[ field.tagnumber() ][ subfield[0] ] ) {
183
                        errors.push( { type: 'unrepeatableSubfield', subfield: subfield[0], line: field.sourceLine } );
184
                    } else {
185
                        seenSubfields[ subfield[0] ] = subfield[1];
186
                    }
187
                } );
188
189
                $.each( mandatorySubfields[ field.tagnumber() ] || {}, function( subfield ) {
190
                    if ( !seenSubfields[ subfield ] ) {
191
                        errors.push( { type: 'missingSubfield', subfield: subfield[0], line: field.sourceLine } );
192
                    }
193
                } );
194
            } );
195
196
            return errors;
197
        },
198
    };
199
200
    return KohaBackend;
201
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/macros.js (+196 lines)
Line 0 Link Here
1
define( [ 'widget' ], function( Widget ) {
2
    function _setIndicators( editor, ind1, ind2 ) {
3
        var info = editor.getLineInfo( editor.cm.getCursor() );
4
        if (!info || !info.subfields) return false;
5
6
        var cur = editor.cm.getCursor();
7
8
        var indicators = [ ind1 || info.contents.substring(4, 5) || '_', ind2 || info.contents.substring(6, 7) || '_' ];
9
10
        editor.cm.replaceRange(
11
            info.tagNumber + ' ' + indicators.join(' ') + ' ' + info.contents.substring(8),
12
            { line: cur.line, ch: 0 },
13
            { line: cur.line },
14
            'marcAware'
15
        );
16
17
        return true;
18
    }
19
20
    var _commandGenerators = [
21
        [ /^copy field data$/i, function() {
22
            return function( editor, state ) {
23
                var info = editor.getLineInfo( editor.cm.getCursor() );
24
                if (!info) return false;
25
26
                if (info.subfields) {
27
                    state.clipboard = info.contents.substring(4);
28
                } else {
29
                    state.clipboard = info.contents.substring(8);
30
                }
31
            };
32
        } ],
33
        [ /^copy subfield data$/i, function() {
34
            return function( editor, state ) {
35
                var info = editor.getLineInfo( editor.cm.getCursor() );
36
                if (!info) return false;
37
38
                var cur = editor.cm.getCursor();
39
40
                if (info.subfields) {
41
                    for (var i = 0; i < info.subfields.length; i++) {
42
                        var end = i == info.subfields.length - 1 ? info.contents.length : info.subfields[i+1].ch;
43
                        if (cur.ch > end) continue;
44
45
                        state.clipboard = info.contents.substring(info.subfields[i].ch + 3, end);
46
                        return;
47
                    }
48
                }
49
50
                return false;
51
            }
52
        } ],
53
        [ /^delete field$/i, function() {
54
            return function( editor, state ) {
55
                var cur = editor.cm.getCursor();
56
57
                editor.cm.replaceRange( "", { line: cur.line, ch: 0 }, { line: cur.line + 1, ch: 0 }, 'marcAware' );
58
            }
59
        } ],
60
        [ /^goto field end$/i, function() {
61
            return function( editor, state ) {
62
                editor.cm.setCursor( { line: editor.cm.lastLine() } );
63
            }
64
        } ],
65
        [ /^goto field (\w{3})$/i, function(field) {
66
            var matcher = new RegExp('^' + field + ' ');
67
            return function( editor, state ) {
68
                for ( var line = 0, contents; (contents = editor.cm.getLine(line)); line++ ) {
69
                    if ( matcher.exec( contents ) ) {
70
                        editor.cm.setCursor( { line: line, ch: 0 } );
71
                        return;
72
                    }
73
                }
74
75
                return false;
76
            }
77
        } ],
78
        [ /^goto subfield end$/i, function() {
79
            return function( editor, state ) {
80
                var cur = editor.cm.getCursor();
81
82
                editor.cm.setCursor( { line: cur.line } );
83
            }
84
        } ],
85
        [ /^goto subfield (\w)$/i, function( code ) {
86
            return function( editor, state ) {
87
                var info = editor.getLineInfo( editor.cm.getCursor() );
88
                if (!info || !info.subfields) return false;
89
90
                var cur = editor.cm.getCursor();
91
92
                for (var i = 0; i < info.subfields.length; i++) {
93
                    if ( info.subfields[i].code != code ) continue;
94
95
                    var end = i == info.subfields.length - 1 ? info.contents.length : info.subfields[i+1].ch;
96
                    editor.cm.setCursor( { line: cur.line, ch: end } );
97
                    return;
98
                }
99
100
                return false;
101
            }
102
        } ],
103
        [ /^insert (new )?field (\w{3}) data=(.*)/i, function(undef, field, data) {
104
            var new_contents = field + ( field < '100' ? ' ' : ' _ _ ' ) + data.replace(/\\([0-9a-z])/g, '$$$1 ');
105
            return function( editor, state ) {
106
                var line, contents;
107
108
                for ( line = 0; (contents = editor.cm.getLine(line)); line++ ) {
109
                    if ( contents && contents[0] > field[0] ) break;
110
                }
111
112
                if ( line > editor.cm.lastLine() ) {
113
                    new_contents = '\n' + new_contents;
114
                } else {
115
                    new_contents = new_contents + '\n';
116
                }
117
118
                editor.cm.replaceRange( new_contents, { line: line, ch: 0 }, null, 'marcAware' );
119
                editor.cm.setCursor( { line: line, ch: 0 } );
120
            }
121
        } ],
122
        [ /^insert (new )?subfield (\w) data=(.*)/i, function(undef, subfield, data) {
123
            return function( editor, state ) {
124
                editor.cm.replaceRange( '$' + subfield + ' ' + data, { line: editor.cm.getCursor().line }, null, 'marcAware' );
125
            }
126
        } ],
127
        [ /^paste$/i, function() {
128
            return function( editor, state ) {
129
                var cur = editor.cm.getCursor();
130
131
                editor.cm.replaceRange( state.clipboard, cur, null, 'marcAware' );
132
            }
133
        } ],
134
        [ /^set indicator([12])=([ _0-9])$/i, function( ind, value ) {
135
            return function( editor, state ) {
136
                return ind == '1' ? _setIndicators( editor, ind1, null ) : _setIndicators( editor, null, ind2 );
137
            }
138
        } ],
139
        [ /^set indicators=([ _0-9])([ _0-9])$/i, function( ind1, ind2 ) {
140
            return function( editor, state ) {
141
                return _setIndicators( editor, ind1, ind2 );
142
            }
143
        } ],
144
    ];
145
146
    var Macros = {
147
        Compile: function( macro ) {
148
            var result = { commands: [], errors: [] };
149
150
            $.each( macro.split(/\r\n|\n/), function( line, contents ) {
151
                var command;
152
153
                if ( contents.match(/^\s*$/) ) return;
154
155
                $.each( _commandGenerators, function( undef, gen ) {
156
                    var match;
157
158
                    if ( !( match = gen[0].exec( contents ) ) ) return;
159
160
                    command = gen[1].apply(null, match.slice(1));
161
                    return false;
162
                } );
163
164
                if ( !command ) {
165
                    result.errors.push( { line: line, error: 'unrecognized' } );
166
                }
167
168
                result.commands.push( { func: command, orig: contents, line: line } );
169
            } );
170
171
            return result;
172
        },
173
        Run: function( editor, macro ) {
174
            var compiled = Macros.Compile(macro);
175
            if ( compiled.errors.length ) return { errors: compiled.errors };
176
            var state = {
177
                clipboard: '',
178
            };
179
180
            var result = { errors: [] };
181
182
            editor.cm.operation( function() {
183
                $.each( compiled.commands, function( undef, command ) {
184
                    if ( command.func( editor, state ) === false ) {
185
                        result.errors.push( { line: command.line, error: 'failed' } );
186
                        return false;
187
                    }
188
                } );
189
            } );
190
191
            return result;
192
        },
193
    };
194
195
    return Macros;
196
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/marc-editor.js (+358 lines)
Line 0 Link Here
1
define( [ 'marc-record', 'koha-backend', 'preferences', 'text-marc', 'widget' ], function( MARC, KohaBackend, Preferences, TextMARC, Widget ) {
2
    var NOTIFY_TIMEOUT = 250;
3
4
    function editorCursorActivity( cm ) {
5
        var editor = cm.marceditor;
6
        if ( editor.textMode ) return;
7
8
        $('#status-tag-info').empty();
9
        $('#status-subfield-info').empty();
10
11
        var info = editor.getLineInfo( cm.getCursor() );
12
13
        if ( !info ) return; // No tag at all on this line
14
15
        var taginfo = KohaBackend.GetTagInfo( '', info.tagNumber );
16
        $('#status-tag-info').html( '<strong>' + info.tagNumber + ':</strong> ' );
17
18
        if ( taginfo ) {
19
            $('#status-tag-info').append( taginfo.lib );
20
21
            if ( !info.currentSubfield ) return; // No current subfield
22
23
            var subfieldinfo = taginfo.subfields[info.currentSubfield];
24
            $('#status-subfield-info').html( '<strong>$' + info.currentSubfield + ':</strong> ' );
25
26
            if ( subfieldinfo ) {
27
                $('#status-subfield-info').append( subfieldinfo.lib );
28
            } else {
29
                $('#status-subfield-info').append( '<em>' + _("Unknown subfield") + '</em>' );
30
            }
31
        } else {
32
            $('#status-tag-info').append( '<em>' + _("Unknown tag") + '</em>' );
33
        }
34
    }
35
36
    function editorBeforeChange( cm, change ) {
37
        var editor = cm.marceditor;
38
        if ( editor.textMode || change.origin == 'marcAware' ) return;
39
40
        // FIXME: Should only cancel changes if this is a control field/subfield widget
41
        if ( change.from.line !== change.to.line || Math.abs( change.from.ch - change.to.ch ) > 1 || change.text.length != 1 || change.text[0].length != 0 ) return; // Not single-char change
42
43
        if ( change.from.ch == change.to.ch - 1 && cm.findMarksAt( { line: change.from.line, ch: change.from.ch + 1 } ).length ) {
44
            change.cancel();
45
        } else if ( change.from.ch == change.to.ch && cm.findMarksAt(change.from).length && !change.text[0].match(/^[$|ǂ‡]$/) ) {
46
            change.cancel();
47
        }
48
    }
49
50
    function editorChange( cm, change ) {
51
        var editor = cm.marceditor;
52
        if ( editor.textMode ) return;
53
54
        var updatedLines = {};
55
        do {
56
            var from = change.from;
57
            var to = change.to;
58
            if ( to.line < from.line || to.ch < from.ch ) {
59
                var temp = from;
60
                from = to;
61
                to = temp;
62
            }
63
64
            var startLine, endLine;
65
            if ( change.text.length == 2 && from.line == to.line && from.ch == to.ch) {
66
                if ( from.ch == 0 ) {
67
                    startLine = endLine = from.line;
68
                } else if ( from.ch == cm.getLine(from.line).length ){
69
                    startLine = endLine = from.line + 1;
70
                }
71
            } else {
72
                startLine = (from.ch == cm.getLine(from.line).length && from.line < to.line) ? Math.min(cm.lastLine(), from.line + 1) : from.line;
73
                endLine = ((to.ch == 0 && from.line < to.line) ? Math.max(to.line - 1, 0) : to.line) + change.text.length - 1;
74
            }
75
76
            for ( var line = startLine; line <= endLine; line++ ) {
77
                if ( updatedLines[line] ) continue;
78
79
                if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( cm.marceditor, line );
80
                if ( change.origin != 'setValue' && change.origin != 'marcWidgetPrefill' ) cm.addLineClass( line, 'wrapper', 'modified-line' );
81
                updatedLines[line] = true;
82
            }
83
        } while ( change = change.next )
84
85
        Widget.ActivateAt( cm, cm.getCursor() );
86
        cm.marceditor.startNotify();
87
    }
88
89
    // Editor helper functions
90
    function activateTabPosition( cm, cur, idx ) {
91
        cm.setCursor( cur );
92
        Widget.ActivateAt( cm, cur, idx );
93
    }
94
95
    function getTabPositions( editor, cur ) {
96
        var info = editor.getLineInfo( cur || editor.cm.getCursor() );
97
98
        if ( info ) {
99
            if ( info.subfields ) {
100
                var positions = [ 0, 4, 6 ];
101
102
                $.each( info.subfields, function( undef, subfield ) {
103
                    positions.push( subfield.ch + 3 );
104
                } );
105
106
                return positions;
107
            } else {
108
                return [ 0, 4 ];
109
            }
110
        } else {
111
            return [];
112
        }
113
    }
114
115
    var _editorKeys = {
116
        Enter: function( cm ) {
117
            var cursor = cm.getCursor();
118
            cm.replaceRange( '\n', { line: cursor.line }, null, 'marcAware' );
119
            cm.setCursor( { line: cursor.line + 1, ch: 0 } );
120
        },
121
122
        'Shift-Enter': function( cm ) {
123
            var cursor = cm.getCursor();
124
            cm.replaceRange( '\n', { line: cursor.line, ch: 0 }, null, 'marcAware' );
125
            cm.setCursor( { line: cursor.line, ch: 0 } );
126
        },
127
128
        'Ctrl-X': function( cm ) {
129
            // Delete subfield (or cut)
130
            if ( cm.somethingSelected() ) return true;
131
132
            var cur = cm.getCursor();
133
            var info = cm.marceditor.getLineInfo( cur );
134
            if ( !info || !info.subfields ) return true;
135
136
            for (var i = 0; i < info.subfields.length; i++) {
137
                var end = i == info.subfields.length - 1 ? info.contents.length : info.subfields[i+1].ch;
138
                if (cur.ch > end) continue;
139
140
                cm.replaceRange( "", { line: cur.line, ch: info.subfields[i].ch }, { line: cur.line, ch: end }, 'marcAware' );
141
                return;
142
            }
143
        },
144
145
        'Shift-Ctrl-X': function( cm ) {
146
            // Delete line
147
            var cur = cm.getCursor();
148
149
            cm.replaceRange( "", { line: cur.line, ch: 0 }, { line: cur.line + 1, ch: 0 }, 'marcAware' );
150
        },
151
152
        Tab: function( cm ) {
153
            // Move through parts of tag/fixed fields
154
            var positions = getTabPositions( cm.marceditor );
155
            var cur = cm.getCursor();
156
157
            for ( var i = 0; i < positions.length; i++ ) {
158
                if ( positions[i] > cur.ch ) {
159
                    activateTabPosition( cm, { line: cur.line, ch: positions[i] } );
160
                    return false;
161
                }
162
            }
163
164
            cm.setCursor( { line: cur.line + 1, ch: 0 } );
165
        },
166
167
        'Shift-Tab': function( cm ) {
168
            // Move backwards through parts of tag/fixed fields
169
            var positions = getTabPositions( cm.marceditor );
170
            var cur = cm.getCursor();
171
172
            for ( var i = positions.length - 1; i >= 0; i-- ) {
173
                if ( positions[i] < cur.ch ) {
174
                    activateTabPosition( cm, { line: cur.line, ch: positions[i] } );
175
                    return false;
176
                }
177
            }
178
179
            if ( cur.line == 0 ) return;
180
181
            var prevPositions = getTabPositions( cm, { line: cur.line - 1, ch: cm.getLine( cur.line - 1 ).length } );
182
183
            if ( prevPositions.length ) {
184
                activateTabPosition( cm, { line: cur.line - 1, ch: prevPositions[ prevPositions.length - 1 ] }, -1 );
185
            } else {
186
                cm.setCursor( { line: cur.line - 1, ch: 0 } );
187
            }
188
        },
189
    };
190
191
    function MARCEditor( position ) {
192
        this.cm = CodeMirror(
193
            position,
194
            {
195
                extraKeys: _editorKeys,
196
                gutters: [
197
                    'modified-line-gutter',
198
                ],
199
                lineWrapping: true,
200
                mode: {
201
                    name: 'marc',
202
                    nonRepeatableTags: KohaBackend.GetTagsBy( '', 'repeatable', '0' ),
203
                    nonRepeatableSubfields: KohaBackend.GetSubfieldsBy( '', 'repeatable', '0' )
204
                }
205
            }
206
        );
207
        this.cm.marceditor = this;
208
209
        this.cm.on( 'beforeChange', editorBeforeChange );
210
        this.cm.on( 'change', editorChange );
211
        this.cm.on( 'cursorActivity', editorCursorActivity );
212
213
        this.subscribers = [];
214
        this.subscribe( function( marceditor ) {
215
            Widget.Notify( marceditor );
216
        } );
217
    }
218
219
    MARCEditor.prototype.setUseWidgets = function( val ) {
220
        if ( val ) {
221
            for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
222
                Widget.UpdateLine( this, line );
223
            }
224
        } else {
225
            $.each( this.cm.getAllMarks(), function( undef, mark ) {
226
                if ( mark.widget ) mark.widget.clearToText();
227
            } );
228
        }
229
    };
230
231
    MARCEditor.prototype.focus = function() {
232
        this.cm.focus();
233
    };
234
235
    MARCEditor.prototype.refresh = function() {
236
        this.cm.refresh();
237
    };
238
239
    MARCEditor.prototype.displayRecord = function( record ) {
240
        this.cm.setValue( TextMARC.RecordToText(record) );
241
    };
242
243
    MARCEditor.prototype.getRecord = function() {
244
        this.textMode = true;
245
246
        $.each( this.cm.getAllMarks(), function( undef, mark ) {
247
            if ( mark.widget ) mark.widget.clearToText();
248
        } );
249
        var record = TextMARC.TextToRecord( this.cm.getValue() );
250
        for ( var line = 0; line <= this.cm.lastLine(); line++ ) {
251
            if ( Preferences.user.fieldWidgets ) Widget.UpdateLine( this, line );
252
        }
253
254
        this.textMode = false;
255
256
        return record;
257
    };
258
259
    MARCEditor.prototype.getLineInfo = function( pos ) {
260
        var contents = this.cm.getLine( pos.line );
261
        if ( contents == null ) return {};
262
263
        var tagNumber = contents.match( /^([A-Za-z0-9]{3}) / );
264
265
        if ( !tagNumber ) return null; // No tag at all on this line
266
        tagNumber = tagNumber[1];
267
268
        if ( tagNumber < '010' ) return { tagNumber: tagNumber, contents: contents }; // No current subfield
269
270
        var matcher = /[$|ǂ‡]([a-z0-9%]) /g;
271
        var match;
272
273
        var subfields = [];
274
        var currentSubfield;
275
276
        while ( ( match = matcher.exec(contents) ) ) {
277
            subfields.push( { code: match[1], ch: match.index } );
278
            if ( match.index < pos.ch ) currentSubfield = match[1];
279
        }
280
281
        return { tagNumber: tagNumber, subfields: subfields, currentSubfield: currentSubfield, contents: contents };
282
    };
283
284
    MARCEditor.prototype.addError = function( line, error ) {
285
        var found = false;
286
        var options = {};
287
288
        if ( line == null ) {
289
            line = 0;
290
            options.above = true;
291
        }
292
293
        $.each( this.cm.getLineHandle(line).widgets || [], function( undef, widget ) {
294
            if ( !widget.isErrorMarker ) return;
295
296
            found = true;
297
298
            $( widget.node ).append( '; ' + error );
299
            widget.changed();
300
301
            return false;
302
        } );
303
304
        if ( found ) return;
305
306
        var node = $( '<div class="structure-error"><i class="icon-remove"></i> ' + error + '</div>' )[0];
307
        var widget = this.cm.addLineWidget( line, node, options );
308
309
        widget.node = node;
310
        widget.isErrorMarker = true;
311
    };
312
313
    MARCEditor.prototype.removeErrors = function() {
314
        for ( var line = 0; line < this.cm.lineCount(); line++ ) {
315
            $.each( this.cm.getLineHandle( line ).widgets || [], function( undef, lineWidget ) {
316
                if ( lineWidget.isErrorMarker ) lineWidget.clear();
317
            } );
318
        }
319
    };
320
321
    MARCEditor.prototype.getFixedField = function(field) {
322
        field += ' ';
323
        for ( var line = 0; line < this.cm.lineCount(); line++ ) {
324
            var contents = this.cm.getLine(line);
325
            if ( contents.substr( 0, 4 ) != field ) continue;
326
327
            var marks = this.cm.findMarksAt( { line: line, ch: 4 } );
328
            if ( marks[0] && marks[0].widget ) {
329
                return marks[0].widget.text;
330
            } else {
331
                return contents.substr(4);
332
            }
333
        }
334
335
        return null;
336
    };
337
338
    MARCEditor.prototype.startNotify = function() {
339
        if ( this.notifyTimeout ) clearTimeout( this.notifyTimeout );
340
        this.notifyTimeout = setTimeout( $.proxy( function() {
341
            this.notifyAll();
342
343
            this.notifyTimeout = null;
344
        }, this ), NOTIFY_TIMEOUT );
345
    };
346
347
    MARCEditor.prototype.notifyAll = function() {
348
        $.each( this.subscribers, $.proxy( function( undef, subscriber ) {
349
            subscriber(this);
350
        }, this ) );
351
    };
352
353
    MARCEditor.prototype.subscribe = function( subscriber ) {
354
        this.subscribers.push( subscriber );
355
    };
356
357
    return MARCEditor;
358
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/marc-mode.js (+129 lines)
Line 0 Link Here
1
/**
2
 * Textual MARC mode for CodeMirror.
3
 * Copyright (c) 2013 ByWater
4
 */
5
6
// Expected format: 245 _ 1 $a Pizza |c 34ars
7
8
CodeMirror.defineMode( 'marc', function( config, modeConfig ) {
9
    modeConfig.nonRepeatableTags = modeConfig.nonRepeatableTags || {};
10
    modeConfig.nonRepeatableSubfields = modeConfig.nonRepeatableSubfields || {};
11
12
    return {
13
        startState: function( prevState ) {
14
            var state = prevState || {};
15
16
            if ( !prevState ) {
17
                state.seenTags = {};
18
            }
19
20
            state.indicatorNeeded = false;
21
            state.subAllowed = true;
22
            state.subfieldCode = undefined;
23
            state.tagNumber = undefined;
24
            state.seenSubfields = {};
25
26
            return state;
27
        },
28
        copyState: function( prevState ) {
29
            var result = $.extend( {}, prevState );
30
            result.seenTags = $.extend( {}, prevState.seenTags );
31
            result.seenSubfields = $.extend( {}, prevState.seenSubfields );
32
33
            return result;
34
        },
35
        token: function( stream, state ) {
36
            var match;
37
            if ( stream.sol() ) {
38
                this.startState( state );
39
                if ( match = stream.match( /[0-9A-Za-z]+/ ) ) {
40
                    match = match[0];
41
                    if ( match.length != 3 ) {
42
                        if ( stream.eol() && match.length < 3 ) {
43
                            // Don't show error for incomplete number
44
                            return 'tagnumber';
45
                        } else {
46
                            stream.skipToEnd();
47
                            return 'error';
48
                        }
49
                    }
50
51
                    state.tagNumber = match;
52
                    if ( state.tagNumber < '010' ) {
53
                        // Control field
54
                        state.subAllowed = false;
55
                    }
56
57
                    if ( state.seenTags[state.tagNumber] && modeConfig.nonRepeatableTags[state.tagNumber] ) {
58
                        return 'bad-tagnumber';
59
                    } else {
60
                        state.seenTags[state.tagNumber] = true;
61
                        return 'tagnumber';
62
                    }
63
                } else {
64
                    stream.skipToEnd();
65
                    return 'error';
66
                }
67
            }
68
69
            if ( stream.eol() ) {
70
                return;
71
            }
72
73
            if ( !state.subAllowed && stream.pos == 3 ) {
74
                if ( stream.next() == ' ' ) {
75
                    return 'reqspace';
76
                } else {
77
                    stream.skipToEnd();
78
                    return 'error';
79
                }
80
            }
81
82
            if ( stream.pos < 8 && state.subAllowed ) {
83
                switch ( stream.pos ) {
84
                    case 3:
85
                    case 5:
86
                    case 7:
87
                        if ( stream.next() == ' ' ) {
88
                            return 'reqspace';
89
                        } else {
90
                            stream.skipToEnd();
91
                            return 'error';
92
                        }
93
                    case 4:
94
                    case 6:
95
                        if ( /[0-9A-Za-z_]/.test( stream.next() ) ) {
96
                            return 'indicator';
97
                        } else {
98
                            stream.skipToEnd();
99
                            return 'error';
100
                        }
101
                }
102
            }
103
104
            if ( state.subAllowed ) {
105
                if ( stream.pos != 8 && stream.match( /[^$|ǂ‡]+/ ) ) return;
106
107
                if ( stream.eat( /[$|ǂ‡]/ ) ) {
108
                    var subfieldCode;
109
                    if ( ( subfieldCode = stream.eat( /[a-z0-9%]/ ) ) && stream.eat( ' ' ) ) {
110
                        state.subfieldCode = subfieldCode;
111
                        if ( state.seenSubfields[state.subfieldCode] && ( modeConfig.nonRepeatableSubfields[state.tagNumber] || {} )[state.subfieldCode] ) {
112
                            return 'bad-subfieldcode';
113
                        } else {
114
                            state.seenSubfields[state.subfieldCode] = true;
115
                            return 'subfieldcode';
116
                        }
117
                    }
118
                }
119
120
                if ( stream.pos < 11 && ( !stream.eol() || stream.pos == 8 ) ) {
121
                    stream.skipToEnd();
122
                    return 'error';
123
                }
124
            } else {
125
                stream.skipToEnd();
126
            }
127
        }
128
    };
129
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/marc-record.js (+351 lines)
Line 0 Link Here
1
/**
2
 * Adapted and cleaned up from biblios.net, which is purportedly under the GPL.
3
 * Source: http://git.librarypolice.com/?p=biblios.git;a=blob_plain;f=plugins/marc21editor/marcrecord.js;hb=master
4
 *
5
 * ISO2709 import/export is cribbed from marcjs, which is under the MIT license.
6
 * Source: https://github.com/fredericd/marcjs/blob/master/lib/marcjs.js
7
 */
8
9
define( function() {
10
    var MARC = {};
11
12
    var _escape_map = {
13
        "<": "&lt;",
14
        "&": "&amp;",
15
        "\"": "&quot;"
16
    };
17
18
    function _escape(str) {
19
        return str.replace( /[<&"]/, function (c) { return _escape_map[c] } );
20
    }
21
22
    function _intpadded(i, digits) {
23
        i = i + '';
24
        while (i.length < digits) {
25
            i = '0' + i;
26
        }
27
        return i;
28
    }
29
30
    MARC.Record = function (fieldlist) {
31
        this._fieldlist = fieldlist || [];
32
    }
33
34
    $.extend( MARC.Record.prototype, {
35
        leader: function(val) {
36
            var field = this.field('000');
37
38
            if (val) {
39
                if (field) {
40
                    field.subfield( '@', val );
41
                } else {
42
                    field = new MARC.Field( '000', '', '', [ [ '@', val ] ] );
43
                    this.addFieldGrouped(field);
44
                }
45
            } else {
46
                return ( field && field.subfield('@') ) || '     nam a22     7a 4500';
47
            }
48
        },
49
50
        /**
51
         * If a tagnumber is given, returns all fields with that tagnumber.
52
         * Otherwise, returns all fields.
53
         */
54
        fields: function(fieldno) {
55
            if (!fieldno) return this._fieldlist;
56
57
            var results = [];
58
            for(var i=0; i<this._fieldlist.length; i++){
59
                if( this._fieldlist[i].tagnumber() == fieldno ) {
60
                    results.push(this._fieldlist[i]);
61
                }
62
            }
63
64
            return results;
65
        },
66
67
        /**
68
         * Returns the first field with the given tagnumber, or false.
69
         */
70
        field: function(fieldno) {
71
            for(var i=0; i<this._fieldlist.length; i++){
72
                if( this._fieldlist[i].tagnumber() == fieldno ) {
73
                    return this._fieldlist[i];
74
                }
75
            }
76
            return false;
77
        },
78
79
        /**
80
         * Adds the given MARC.Field to the record, at the end.
81
         */
82
        addField: function(field) {
83
            this._fieldlist.push(field);
84
            return true;
85
        },
86
87
        /**
88
         * Adds the given MARC.Field to the record, at the end of the matching
89
         * x00 group. If a record has a 100, 245 and 300 field, for instance, a
90
         * 260 field would be added after the 245 field.
91
         */
92
        addFieldGrouped: function(field) {
93
            for ( var i = this._fieldlist.length - 1; i >= 0; i-- ) {
94
                if ( this._fieldlist[i].tagnumber()[0] <= field.tagnumber()[0] ) {
95
                    this._fieldlist.splice(i+1, 0, field);
96
                    return true;
97
                }
98
            }
99
            this._fieldlist.push(field);
100
            return true;
101
        },
102
103
        /**
104
         * Removes the first field with the given tagnumber. Returns false if no
105
         * such field was found.
106
         */
107
        removeField: function(fieldno) {
108
            for(var i=0; i<this._fieldlist.length; i++){
109
                if( this._fieldlist[i].tagnumber() == fieldno ) {
110
                    this._fieldlist.splice(i, 1);
111
                    return true;
112
                }
113
            }
114
            return false;
115
        },
116
117
        /**
118
         * Check to see if this record contains a field with the given
119
         * tagnumber.
120
         */
121
        hasField: function(fieldno) {
122
            for(var i=0; i<this._fieldlist.length; i++){
123
                if( this._fieldlist[i].tagnumber() == fieldno ) {
124
                    return true;
125
                }
126
            }
127
            return false;
128
        },
129
130
        toXML: function() {
131
            var xml = '<record xmlns="http://www.loc.gov/MARC21/slim">';
132
            for(var i=0; i<this._fieldlist.length; i++){
133
                xml += this._fieldlist[i].toXML();
134
            }
135
            xml += '</record>';
136
            return xml;
137
        },
138
139
        /**
140
         * Truncates this record, and loads in the data from the given MARCXML
141
         * document.
142
         */
143
        loadMARCXML: function(xmldoc) {
144
            var record = this;
145
            record.xmlSource = xmldoc;
146
            this._fieldlist.length = 0;
147
            this.leader( $('leader', xmldoc).text() );
148
            $('controlfield', xmldoc).each( function(i) {
149
                val = $(this).text();
150
                tagnum = $(this).attr('tag');
151
                record._fieldlist.push( new MARC.Field(tagnum, '', '', [ [ '@', val ] ]) );
152
            });
153
            $('datafield', xmldoc).each(function(i) {
154
                var value = $(this).text();
155
                var tagnum = $(this).attr('tag');
156
                var ind1 = $(this).attr('ind1') || ' ';
157
                var ind2 = $(this).attr('ind2') || ' ';
158
                var subfields = new Array();
159
                $('subfield', this).each(function(j) {
160
                    var sfval = $(this).text();
161
                    var sfcode = $(this).attr('code');
162
                    subfields.push( [ sfcode, sfval ] );
163
                });
164
                record._fieldlist.push( new MARC.Field(tagnum, ind1, ind2, subfields) );
165
            });
166
        },
167
168
        toISO2709: function() {
169
            var FT = '\x1e', RT = '\x1d', DE = '\x1f';
170
            var directory = '',
171
                from = 0,
172
                chunks = ['', ''];
173
174
            $.each( this._fieldlist, function( undef, element ) {
175
                var chunk = '';
176
                var tag = element.tagnumber();
177
                if (tag == '000') {
178
                    return;
179
                } else if (tag < '010') {
180
                    chunk = element.subfields()[0][1];
181
                } else {
182
                    chunk = element.indicators().join('');
183
                    $.each( element.subfields(), function( undef, subfield ) {
184
                        chunk += DE + subfield[0] + subfield[1];
185
                    } );
186
                }
187
                chunk += FT;
188
                chunks.push(chunk);
189
                directory += _intpadded(tag,3) + _intpadded(chunk.length,4) + _intpadded(from,5);
190
                from += chunk.length;
191
            });
192
193
            chunks.push(RT);
194
            directory += FT;
195
            var offset = 24 + 12 * (this._fieldlist.length - 1) + 1;
196
            var length = offset + from + 1;
197
            var leader = this.leader();
198
            leader = _intpadded(length,5) + leader.substr(5,7) + _intpadded(offset,5) +
199
                leader.substr(17);
200
            chunks[0] = leader;
201
            chunks[1] = directory;
202
            return chunks.join('');
203
        },
204
205
        loadISO2709: function(data) {
206
            this._fieldlist.length = 0;
207
            this.leader(data.substr(0, 24));
208
            var directory_len = parseInt(data.substring(12, 17), 0) - 25,
209
                number_of_tag = directory_len / 12;
210
            for (var i = 0; i < number_of_tag; i++) {
211
                var off = 24 + i * 12,
212
                    tag = data.substring(off, off+3),
213
                    len = parseInt(data.substring(off+3, off+7), 0) - 1,
214
                    pos = parseInt(data.substring(off+7, off+12), 0) + 25 + directory_len,
215
                    value = data.substring(pos, pos+len);
216
                if ( parseInt(tag) < 10 ) {
217
                    this.addField( new MARC.Field( tag, '', '', [ [ '@', value ] ] ) );
218
                } else {
219
                    if ( value.indexOf('\x1F') ) { // There are some letters
220
                        var ind1 = value.substr(0, 1), ind2 = value.substr(1, 1);
221
                        var subfields = [];
222
223
                        $.each( value.substr(3).split('\x1f'), function( undef, v ) {
224
                            if (v.length < 2) return;
225
                            subfields.push([v.substr(0, 1), v.substr(1)]);
226
                        } );
227
228
                        this.addField( new MARC.Field( tag, ind1, ind2, subfields ) );
229
                    }
230
                }
231
            }
232
        }
233
    } );
234
235
    MARC.Field = function(tagnumber, indicator1, indicator2, subfields) {
236
        this._tagnumber = tagnumber;
237
        this._indicators = [ indicator1, indicator2 ];
238
        this._subfields = subfields;
239
    };
240
241
    $.extend( MARC.Field.prototype, {
242
        tagnumber: function() {
243
            return this._tagnumber;
244
        },
245
246
        isControlField: function() {
247
            return this._tagnumber < '010';
248
        },
249
250
        indicator: function(num, val) {
251
            if( val != null ) {
252
                this._indicators[num] = val;
253
            }
254
            return this._indicators[num];
255
        },
256
257
        indicators: function() {
258
            return this._indicators;
259
        },
260
261
        hasSubfield: function(code) {
262
            for(var i = 0; i<this._subfields.length; i++) {
263
                if( this._subfields[i][0] == code ) {
264
                    return true;
265
                }
266
            }
267
            return false;
268
        },
269
270
        removeSubfield: function(code) {
271
            for(var i = 0; i<this._subfields.length; i++) {
272
                if( this._subfields[i][0] == code ) {
273
                    this._subfields.splice(i,1);
274
                    return true;
275
                }
276
            }
277
            return false;
278
        },
279
280
        subfields: function() {
281
            return this._subfields;
282
        },
283
284
        addSubfield: function(sf) {
285
            this._subfields.push(sf);
286
            return true;
287
        },
288
289
        addSubfieldGrouped: function(sf) {
290
            function _kind( sc ) {
291
                if ( /[a-z]/.test( sc ) ) {
292
                    return 0;
293
                } else if ( /[0-9]/.test( sc ) ) {
294
                    return 1;
295
                } else {
296
                    return 2;
297
                }
298
            }
299
300
            for ( var i = this._subfields.length - 1; i >= 0; i-- ) {
301
                if ( i == 0 && _kind( sf[0] ) < _kind( this._subfields[i][0] ) ) {
302
                    this._subfields.splice( 0, 0, sf );
303
                    return true;
304
                } else if ( _kind( this._subfields[i][0] ) <= _kind( sf[0] )  ) {
305
                    this._subfields.splice( i + 1, 0, sf );
306
                    return true;
307
                }
308
            }
309
310
            this._subfields.push(sf);
311
            return true;
312
        },
313
314
        subfield: function(code, val) {
315
            var sf = '';
316
            for(var i = 0; i<this._subfields.length; i++) {
317
                if( this._subfields[i][0] == code ) {
318
                    sf = this._subfields[i];
319
                    if( val != null ) {
320
                        sf[1] = val;
321
                    }
322
                    return sf[1];
323
                }
324
            }
325
            return false;
326
        },
327
328
        toXML: function() {
329
            // decide if it's controlfield of datafield
330
            if( this._tagnumber == '000') {
331
                return '<leader>' + _escape( this._subfields[0][1] ) + '</leader>';
332
            } else if ( this._tagnumber < '010' ) {
333
                return '<controlfield tag="' + this._tagnumber + '">' + _escape( this._subfields[0][1] ) + '</controlfield>';
334
            } else {
335
                var result = '<datafield tag="' + this._tagnumber + '"';
336
                result += ' ind1="' + this._indicators[0] + '"';
337
                result += ' ind2="' + this._indicators[1] + '">';
338
                for( var i = 0; i< this._subfields.length; i++) {
339
                    result += '<subfield code="' + this._subfields[i][0] + '">';
340
                    result += _escape( this._subfields[i][1] );
341
                    result += '</subfield>';
342
                }
343
                result += '</datafield>';
344
345
                return result;
346
            }
347
        }
348
    } );
349
350
    return MARC;
351
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/preferences.js (+28 lines)
Line 0 Link Here
1
define( function() {
2
    var Preferences = {
3
        Load: function( borrowernumber ) {
4
            if ( !borrowernumber ) return;
5
            var saved_prefs;
6
            try {
7
                saved_prefs = JSON.parse( localStorage[ 'cateditor_preferences_' + borrowernumber ] );
8
            } catch (e) {}
9
10
            Preferences.user = $.extend( {
11
                // Preference defaults
12
                fieldWidgets: true,
13
                font: 'monospace',
14
                fontSize: '1em',
15
                macros: {},
16
            }, saved_prefs );
17
        },
18
19
        Save: function( borrowernumber ) {
20
            if ( !borrowernumber ) return;
21
            if ( !Preferences.user ) Preferences.Load(borrowernumber);
22
23
            localStorage[ 'cateditor_preferences_' + borrowernumber ] = JSON.stringify(Preferences.user);
24
        },
25
    };
26
27
    return Preferences;
28
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/resources.js (+19 lines)
Line 0 Link Here
1
define( [ 'module' ], function( module ) {
2
    var _allResources = [];
3
4
    var Resources = {
5
        GetAll: function() {
6
            return $.when.call( null, _allResources );
7
        }
8
    };
9
10
    function _res( name, deferred ) {
11
        Resources[name] = deferred;
12
        _allResources.push(deferred);
13
    }
14
15
    _res( 'marc21/xml/006', $.get( module.config().themelang + '/data/marc21_field_006.xml' ) );
16
    _res( 'marc21/xml/008', $.get( module.config().themelang + '/data/marc21_field_008.xml' ) );
17
18
    return Resources;
19
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/search.js (+96 lines)
Line 0 Link Here
1
define( [ 'marc-record', 'pz2' ], function( MARC, Pazpar2 ) {
2
    //var _pz;
3
    var _onresults;
4
    var _recordCache = {};
5
    var _options;
6
7
    var Search = {
8
        Init: function( targets, options ) {
9
            var initOpts = {};
10
11
            $.each( targets, function ( url, info ) {
12
                initOpts[ 'pz:name[' + url + ']' ] = info.name;
13
                initOpts[ 'pz:queryencoding[' + url + ']' ] = info.encoding;
14
                initOpts[ 'pz:xslt[' + url + ']' ] = info.kohasyntax.toLowerCase() + '-work-groups.xsl';
15
                initOpts[ 'pz:requestsyntax[' + url + ']' ] = info.syntax;
16
17
                // Load in default CCL mappings
18
                // Pazpar2 seems to have a bug where wildcard cclmaps are ignored.
19
                // What an incredible surprise.
20
                initOpts[ 'pz:cclmap:term[' + url + ']' ] = 'u=1016 t=l,r s=al';
21
                initOpts[ 'pz:cclmap:Author-name[' + url + ']' ] = 'u=1004 s=al';
22
                initOpts[ 'pz:cclmap:Classification-Dewey[' + url + ']' ] = 'u=13';
23
                initOpts[ 'pz:cclmap:Classification-LC[' + url + ']' ] = 'u=16';
24
                initOpts[ 'pz:cclmap:Date[' + url + ']' ] = 'u=30 r=r';
25
                initOpts[ 'pz:cclmap:Identifier-ISBN[' + url + ']' ] = 'u=7';
26
                initOpts[ 'pz:cclmap:Identifier-ISSN[' + url + ']' ] = 'u=8';
27
                initOpts[ 'pz:cclmap:Identifier-publisher-for-music[' + url + ']' ] = 'u=51';
28
                initOpts[ 'pz:cclmap:Identifier-standard[' + url + ']' ] = 'u=1007';
29
                initOpts[ 'pz:cclmap:LC-card-number[' + url + ']' ] = 'u=9';
30
                initOpts[ 'pz:cclmap:Local-number[' + url + ']' ] = 'u=12';
31
                initOpts[ 'pz:cclmap:Subject[' + url + ']' ] = 'u=21 s=al';
32
                initOpts[ 'pz:cclmap:Title[' + url + ']' ] = 'u=4 s=al';
33
34
                if ( info.authentication ) initOpts[ 'pz:authentication[' + url + ']' ] = info.authentication;
35
            } );
36
37
            _options =  $.extend( {
38
                initopts: initOpts,
39
                onshow: Search._onshow,
40
                errorhandler: Search._onerror,
41
            }, options );
42
43
            _pz = new Pazpar2( _options );
44
        },
45
        Reconnect: function() {
46
            _pz.reset();
47
            _pz = new Pazpar2( _options );
48
        },
49
        Start: function( targets, q, limit ) {
50
            Search.includedTargets = [];
51
            recordcache = {};
52
53
            $.each( targets, function ( url, info ) {
54
                if ( !info.disabled ) Search.includedTargets.push( url );
55
            } );
56
57
            _pz.search( q, limit, 'relevance:0', 'pz:id=' + Search.includedTargets.join( '|' ) );
58
            return true;
59
        },
60
        Fetch: function( offset ) {
61
            _pz.show( offset );
62
        },
63
        GetDetailedRecord: function( recid, callback ) {
64
            if ( _recordCache[recid] ) {
65
                callback( _recordCache[recid] );
66
                return;
67
            }
68
69
            _pz.record( recid, 0, undefined, { callback: function(data) {
70
                var record = _recordCache[recid] = new MARC.Record();
71
                record.loadMARCXML(data.xmlDoc);
72
73
                callback(record);
74
            } } );
75
        },
76
        IsAvailable: function() {
77
            return _pz.initStatusOK;
78
        },
79
        _onshow: function( data ) {
80
            $.each( data.hits, function( undef, hit ) {
81
                hit.id = 'search:' + encodeURIComponent( hit.recid[0] );
82
            } );
83
84
            _options.onresults( data );
85
        },
86
        _onerror: function( error ) {
87
            if ( _options.oniniterror && !_pz.initStatusOK ) {
88
                _options.oniniterror( error );
89
            } else {
90
                _options.onerror( error );
91
            }
92
        }
93
    };
94
95
    return Search;
96
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/text-marc.js (+78 lines)
Line 0 Link Here
1
define( [ 'marc-record' ], function( MARC ) {
2
    return {
3
        RecordToText: function( record ) {
4
            var lines = [];
5
            var fields = record.fields();
6
7
            for ( var i = 0; i < fields.length; i++ ) {
8
                var field = fields[i];
9
10
                if ( field.isControlField() ) {
11
                    lines.push( field.tagnumber() + ' ' + field.subfield( '@' ) );
12
                } else {
13
                    var result = [ field.tagnumber() + ' ' ];
14
15
                    result.push( field.indicator(0) == ' ' ? '_' : field.indicator(0), ' ' );
16
                    result.push( field.indicator(1) == ' ' ? '_' : field.indicator(1), ' ' );
17
18
                    $.each( field.subfields(), function( i, subfield ) {
19
                        result.push( '$' + subfield[0] + ' ' + subfield[1] );
20
                    } );
21
22
                    lines.push( result.join('') );
23
                }
24
            }
25
26
            return lines.join('\n');
27
        },
28
29
        TextToRecord: function( text ) {
30
            var record = new MARC.Record();
31
            var errors = [];
32
33
            $.each( text.split('\n'), function( i, line ) {
34
                var tagNumber = line.match( /^([A-Za-z0-9]{3}) / );
35
36
                if ( !tagNumber ) {
37
                    errors.push( { type: 'noTag', line: i } );
38
                    return;
39
                }
40
                tagNumber = tagNumber[1];
41
42
                if ( tagNumber < '010' ) {
43
                    var field = new MARC.Field( tagNumber, ' ', ' ', [ [ '@', line.substring( 4 ) ] ] );
44
                    field.sourceLine = i;
45
                    record.addField( field );
46
                } else {
47
                    var indicators = line.match( /^... ([0-9A-Za-z_]) ([0-9A-Za-z_])/ );
48
                    if ( !indicators ) {
49
                        errors.push( { type: 'noIndicators', line: i } );
50
                        return;
51
                    }
52
53
                    var field = new MARC.Field( tagNumber, ( indicators[1] == '_' ? ' ' : indicators[1] ), ( indicators[2] == '_' ? ' ' : indicators[2] ), [] );
54
55
                    var matcher = /[$|ǂ‡]([a-z0-9%]) /g;
56
                    var match;
57
58
                    var subfields = [];
59
60
                    while ( ( match = matcher.exec(line) ) ) {
61
                        subfields.push( { code: match[1], ch: match.index } );
62
                    }
63
64
                    $.each( subfields, function( i, subfield ) {
65
                        var next = subfields[ i + 1 ];
66
67
                        field.addSubfield( [ subfield.code, line.substring( subfield.ch + 3, next ? next.ch : line.length ) ] );
68
                    } );
69
70
                    field.sourceLine = i;
71
                    record.addField( field );
72
                }
73
            } );
74
75
            return errors.length ? { errors: errors } : record;
76
        }
77
    };
78
} );
(-)a/koha-tmpl/intranet-tmpl/lib/koha/cateditor/widget.js (+287 lines)
Line 0 Link Here
1
define( [ 'resources' ], function( Resources ) {
2
    var _widgets = {};
3
4
    var Widget = {
5
        Register: function( tagfield, widget ) {
6
            _widgets[tagfield] = widget;
7
        },
8
9
        PadNum: function( number, length ) {
10
            var result = number.toString();
11
12
            while ( result.length < length ) result = '0' + result;
13
14
            return result;
15
        },
16
17
        PadString: function( result, length ) {
18
            while ( result.length < length ) result = ' ' + result;
19
20
            return result;
21
        },
22
23
        PadStringRight: function( result, length ) {
24
            result = '' + result;
25
            while ( result.length < length ) result += ' ';
26
27
            return result;
28
        },
29
30
        Base: {
31
            // Marker utils
32
            clearToText: function() {
33
                var range = this.mark.find();
34
                if ( this.text == null ) throw new Error('Tried to clear widget with no text');
35
                this.mark.doc.replaceRange( this.text, range.from, range.to, 'marcAware' );
36
            },
37
38
            reCreate: function() {
39
                this.postCreate( this.node, this.mark );
40
            },
41
42
            // Fixed field utils
43
            bindFixed: function( sel, start, end ) {
44
                var $node = $( this.node ).find( sel );
45
                $node.val( this.getFixed( start, end ) );
46
47
                var widget = this;
48
                var $collapsed = $( '<span class="fixed-collapsed" title="' + $node.attr('title') + '">' + $node.val() + '</span>' ).insertAfter( $node );
49
50
                function show() {
51
                    $collapsed.hide();
52
                    $node.val( widget.getFixed( start, end ).replace(/\s+$/, '') );
53
                    $node.show();
54
                    $node[0].focus();
55
                }
56
57
                function hide() {
58
                    $node.hide();
59
                    $collapsed.text( Widget.PadStringRight( $node.val(), end - start ) ).show();
60
                }
61
62
                $node.on( 'change keyup', function() {
63
                    widget.setFixed( start, end, $node.val(), '+input' );
64
                } ).focus( show ).blur( hide );
65
66
                hide();
67
68
                $collapsed.click( show );
69
            },
70
71
            getFixed: function( start, end ) {
72
                return this.text.substring( start, end );
73
            },
74
75
            setFixed: function( start, end, value, source ) {
76
                this.setText( this.text.substring( 0, start ) + Widget.PadStringRight( value.toString().substr( 0, end - start ), end - start ) + this.text.substring( end ), source );
77
            },
78
79
            setText: function( text, source ) {
80
                if ( source == '+input' ) this.mark.doc.cm.addLineClass( this.mark.find().from.line, 'wrapper', 'modified-line' );
81
                this.text = text;
82
                this.editor.startNotify();
83
            },
84
85
            createFromXML: function( resourceId ) {
86
                var widget = this;
87
88
                Resources[resourceId].done( function( xml ) {
89
                    $(widget.node).find('.widget-loading').remove();
90
                    var $matSelect = $('<select class="material-select"></select>').appendTo(widget.node);
91
                    var $contents = $('<span class="material-contents"/>').appendTo(widget.node);
92
                    var materialInfo = {};
93
94
                    $('Tagfield', xml).children('Material').each( function() {
95
                        $matSelect.append( '<option value="' + $(this).attr('id') + '">' + $(this).attr('id') + ' - ' + $(this).children('name').text() + '</option>' );
96
97
                        materialInfo[ $(this).attr('id') ] = this;
98
                    } );
99
100
                    $matSelect.change( function() {
101
                        widget.loadXMLMaterial( materialInfo[ $matSelect.val() ] );
102
                    } ).change();
103
                } );
104
            },
105
106
            loadXMLMaterial: function( materialInfo ) {
107
                var $contents = $(this.node).children('.material-contents');
108
                $contents.empty();
109
110
                var widget = this;
111
112
                $(materialInfo).children('Position').each( function() {
113
                    var match = $(this).attr('pos').match(/(\d+)(?:-(\d+))?/);
114
                    if (!match) return;
115
116
                    var start = parseInt(match[1]);
117
                    var end = ( match[2] ? parseInt(match[2]) : start ) + 1;
118
                    var $input;
119
                    var $values = $(this).children('Value');
120
121
                    if ($values.length == 0) {
122
                        $contents.append( '<span title="' + $(this).children('name').text() + '">' + widget.getFixed(start, end) + '</span>' );
123
                        return;
124
                    }
125
126
                    if ( match[2] ) {
127
                        $input = $( '<input name="f' + Widget.PadNum(start, 2) + '" title="' + $(this).children('name').text() + '" maxlength="' + (end - start) + '" />' );
128
                    } else {
129
                        $input = $( '<select name="f' + Widget.PadNum(start, 2) + '" title="' + $(this).children('name').text() + '"></select>' );
130
131
                        $values.each( function() {
132
                            $input.append( '<option value="' + $(this).attr('code') + '">' + $(this).attr('code') + ' - ' + $(this).children('description').text() + '</option>' );
133
                        } );
134
                    }
135
136
                    $contents.append( $input );
137
                    widget.bindFixed( $input, start, end );
138
                } );
139
            },
140
141
            nodeChanged: function() {
142
                this.mark.changed();
143
                var widget = this;
144
145
                var $inputs = $(this.node).find('input, select');
146
                if ( !$inputs.length ) return;
147
148
                $inputs.off('keydown.marc-tab');
149
                var editor = widget.editor;
150
151
                $inputs.each( function( i ) {
152
                    $(this).on( 'keydown.marc-tab', function( e ) {
153
                        if ( e.which != 9 ) return; // Tab
154
155
                        var span = widget.mark.find();
156
                        var cur = editor.cm.getCursor();
157
158
                        if ( e.shiftKey ) {
159
                            if ( i > 0 ) {
160
                                $inputs.eq(i - 1).trigger( 'focus' );
161
                            } else {
162
                                editor.cm.setCursor( span.from );
163
                                // FIXME: ugly hack
164
                                editor.cm.options.extraKeys['Shift-Tab']( editor.cm );
165
                                editor.focus();
166
                            }
167
                        } else {
168
                            if ( i < $inputs.length - 1 ) {
169
                                $inputs.eq(i + 1).trigger( 'focus' );
170
                            } else {
171
                                editor.cm.setCursor( span.to );
172
                                editor.focus();
173
                            }
174
                        }
175
176
                        return false;
177
                    } );
178
                } );
179
            },
180
181
            // Template utils
182
            insertTemplate: function( sel ) {
183
                var wsOnly = /^\s*$/;
184
                $( sel ).contents().clone().each( function() {
185
                    if ( this.nodeType == Node.TEXT_NODE ) {
186
                        this.data = this.data.replace( /^\s+|\s+$/g, '' );
187
                    }
188
                } ).appendTo( this.node );
189
            },
190
        },
191
192
        ActivateAt: function( editor, cur, idx ) {
193
            var marks = editor.findMarksAt( cur );
194
            if ( !marks.length ) return false;
195
196
            var $input = $(marks[0].widget.node).find('input, select').eq(idx || 0);
197
            if ( !$input.length ) return false;
198
199
            $input.focus();
200
            return true;
201
        },
202
203
        Notify: function( editor ) {
204
            $.each( editor.cm.getAllMarks(), function( undef, mark ) {
205
                if ( mark.widget && mark.widget.notify ) mark.widget.notify();
206
            } );
207
        },
208
209
        UpdateLine: function( editor, line ) {
210
            var info = editor.getLineInfo( { line: line, ch: 0 } );
211
            var lineh = editor.cm.getLineHandle( line );
212
            if ( !lineh ) return;
213
214
            if ( !info ) {
215
                if ( lineh.markedSpans ) {
216
                    $.each( lineh.markedSpans, function ( undef, span ) {
217
                        var mark = span.marker;
218
                        if ( !mark.widget ) return;
219
220
                        mark.widget.clearToText();
221
                    } );
222
                }
223
                return;
224
            }
225
226
            var subfields = [];
227
228
            var end = editor.cm.getLine( line ).length;
229
            if ( info.tagNumber < '010' ) {
230
                if ( end >= 4 ) subfields.push( { code: '@', from: 4, to: end } );
231
            } else {
232
                for ( var i = 0; i < info.subfields.length; i++ ) {
233
                    var next = ( i < info.subfields.length - 1 ) ? info.subfields[i + 1].ch : end;
234
                    subfields.push( { code: info.subfields[i].code, from: info.subfields[i].ch + 3, to: next } );
235
                }
236
            }
237
238
            $.each( subfields, function ( undef, subfield ) {
239
                var id = info.tagNumber + subfield.code;
240
                var marks = editor.cm.findMarksAt( { line: line, ch: subfield.from } );
241
242
                if ( marks.length ) {
243
                    if ( marks[0].id == id ) {
244
                        return;
245
                    } else {
246
                        marks[0].widget.clearToText();
247
                    }
248
                }
249
250
                if ( !_widgets[id] ) return;
251
                var fullBase = $.extend( Object.create( Widget.Base ), _widgets[id] );
252
                var widget = Object.create( fullBase );
253
254
                if ( subfield.from == subfield.to ) {
255
                    editor.cm.replaceRange( widget.makeTemplate ? widget.makeTemplate() : '<empty>', { line: line, ch: subfield.from }, null, 'marcWidgetPrefill' );
256
                    return; // We'll do the actual work when the change event is triggered again
257
                }
258
259
                var text = editor.cm.getRange( { line: line, ch: subfield.from }, { line: line, ch: subfield.to } );
260
261
                widget.text = text;
262
                var node = widget.init();
263
264
                var mark = editor.cm.markText( { line: line, ch: subfield.from }, { line: line, ch: subfield.to }, {
265
                    inclusiveLeft: false,
266
                    inclusiveRight: false,
267
                    replacedWith: node,
268
                } );
269
270
                mark.id = id;
271
                mark.widget = widget;
272
273
                widget.node = node;
274
                widget.mark = mark;
275
                widget.editor = editor;
276
277
                if ( widget.postCreate ) {
278
                    widget.postCreate();
279
                }
280
281
                widget.nodeChanged();
282
            } );
283
        },
284
    };
285
286
    return Widget;
287
} );
(-)a/koha-tmpl/intranet-tmpl/prog/en/css/cateditor.css (+402 lines)
Line 0 Link Here
1
/*> Infrastructure */
2
body {
3
    padding: 0;
4
}
5
6
#loading {
7
    background-color: #FFF;
8
    cursor: wait;
9
    height: 100%;
10
    left: 0;
11
    opacity: .7;
12
    position: fixed;
13
    top: 0;
14
    width: 100%;
15
    z-index: 1000;
16
}
17
18
#loading div {
19
    background : transparent url(../../img/loading.gif) top left no-repeat;
20
    font-size : 175%;
21
    font-weight: bold;
22
    height: 2em;
23
    left: 50%;
24
    margin: -1em 0 0 -2.5em;
25
    padding-left : 50px;
26
    position: absolute;
27
    top: 50%;
28
    width: 15em;
29
}
30
31
#alerts-container {
32
    font-size: 12px;
33
}
34
35
#alerts-container h3 {
36
    font-size: inherit;
37
}
38
39
#alerts-container > ul {
40
    padding: 0;
41
}
42
43
#alerts-container > ul > li {
44
    border-bottom: 1px solid #DDD;
45
    display: block;
46
    padding: 4px 0;
47
}
48
49
#alerts-container > ul > li:first-child {
50
    padding-top: 0;
51
}
52
53
#alerts-container > ul > li:last-child {
54
    border-bottom: none;
55
    padding-bottom: 0;
56
}
57
58
/*> MARC editor */
59
#editor .CodeMirror {
60
    line-height: 1.2;
61
}
62
63
.cm-tagnumber {
64
    color: #080;
65
    font-weight: bold;
66
}
67
68
.cm-bad-tagnumber {
69
    color: #A20;
70
    font-weight: bold;
71
}
72
73
.cm-indicator {
74
    color: #884;
75
}
76
77
.cm-subfieldcode {
78
    background-color: #F4F4F4;
79
    color: #187848;
80
    border-radius: 3px 8px 8px 3px;
81
    border-right: 2px solid white;
82
    font-weight: bold;
83
    margin-right: -2px;
84
}
85
86
.cm-bad-subfieldcode {
87
    background-color: #FFD9D9;
88
    color: #482828;
89
    border-radius: 3px 8px 8px 3px;
90
    font-weight: bold;
91
}
92
93
#editor .modified-line-gutter {
94
    width: 10px;
95
}
96
97
#editor .modified-line {
98
    background: #F8F8F8;
99
    border-left: 5px solid black;
100
    margin-left: -10px;
101
    padding-left: 5px;
102
}
103
104
#editor .CodeMirror-gutters {
105
    background: transparent;
106
    border-right: none;
107
}
108
109
/*> MARC editor widgets */
110
111
#editor .subfield-widget {
112
    color: #538200;
113
    border: solid 2px #538200;
114
    border-radius: 6px;
115
    font-family: inherit;
116
    line-height: 2.75;
117
    margin: 3px 0;
118
    padding: 4px;
119
}
120
121
#editor .subfield-widget select, #editor .subfield-widget input {
122
    height: 1.5em;
123
    vertical-align: middle;
124
}
125
126
#editor .subfield-widget select:focus {
127
    outline: 2px #83A230 solid;
128
}
129
130
#editor .fixed-widget input {
131
    width: 4em;
132
}
133
134
#editor .fixed-widget select {
135
    width: 3em;
136
}
137
138
#editor .fixed-widget .material-select {
139
    width: 4.5em;
140
    margin-right: .5em;
141
}
142
143
#editor .fixed-collapsed {
144
    display: inline-block;
145
    margin: 0 .25em;
146
    text-align: center;
147
    text-decoration: underline;
148
}
149
150
#editor .hidden-widget {
151
    color: #999999;
152
    border: solid 2px #AAAAAA;
153
    line-height: 2;
154
    padding: 2px;
155
}
156
157
.structure-error {
158
    background: #FFEEEE;
159
    font-size: 0.9em;
160
    line-height: 1.5;
161
    margin: .5em;
162
    padding: 0 .5em;
163
}
164
165
.structure-error i {
166
    vertical-align: text-bottom;
167
}
168
169
#statusbar {
170
    background-color: #F4F8F9;
171
    border: solid 2px #b9d8d9;
172
    border-bottom-style: none;
173
    border-radius: 6px 6px 0 0;
174
    height: 18px;
175
    margin-bottom: -32px;
176
    overflow: auto;
177
    padding: 4px;
178
    padding-bottom: 0;
179
}
180
181
#statusbar #status-tag-info, #statusbar #status-subfield-info {
182
    float: left;
183
    overflow: hidden;
184
    padding-right: 2%;
185
    width: 48%;
186
}
187
188
#record-info .label {
189
    float: none;
190
}
191
192
#record-info .label + span {
193
    display: block;
194
    padding-left: 1em;
195
}
196
197
/*> Search */
198
199
#advanced-search-ui, #search-results-ui, #macro-ui {
200
    padding: 5px;
201
    width: 90%;
202
}
203
204
.modal-body {
205
    height: 400px;
206
    padding: 0;
207
}
208
209
#quicksearch-overlay {
210
    background: rgba(255, 255, 255, .9);
211
    border: 2px solid #CC8877;
212
    border-radius: 5px;
213
    -moz-box-sizing: border-box;
214
    -webkit-box-sizing: border-box;
215
    box-sizing: border-box;
216
    color: #664444;
217
    position: relative;
218
    vertical-align: middle;
219
}
220
221
#quicksearch-overlay h3 {
222
    font-size: 1.5em%;
223
    margin: 0;
224
    text-align: center;
225
    padding: 50px 5px;
226
}
227
228
#quicksearch-overlay p {
229
    bottom: 0;
230
    font-size: .8em;
231
    overflow: hidden;
232
    padding: 8px 15px;
233
    position: absolute;
234
    text-align: center;
235
}
236
237
#quicksearch input, #quicksearch a {
238
    font-size: 1.2em;
239
    padding: 3px 0;
240
    width: 96%; // I have no idea why this is necessary
241
}
242
243
#show-advanced-search {
244
    display: block;
245
    margin-top: .3em;
246
}
247
248
#advanced-search-fields {
249
    margin: 0;
250
    padding: 0;
251
}
252
253
#advanced-search-fields li {
254
    display: inline-block;
255
    list-style-type: none;
256
}
257
258
#advanced-search-fields label {
259
    display: inline-block;
260
    font-weight: bold;
261
    padding: 1em 1em 1em 0;
262
    width: 10em;
263
    text-align: right;
264
}
265
266
#advanced-search-fields input {
267
    display: inline-block;
268
    margin: 0px auto;
269
    width: 14em;
270
}
271
272
.icon-loading {
273
    display: inline-block;
274
    height: 16px;
275
    width: 16px;
276
    background: transparent url("../../img/spinner-small.gif") top left no-repeat;
277
    padding: -1px;
278
    vertical-align: text-top;
279
}
280
281
/*> Search results */
282
283
#searchresults table {
284
    width: 100%;
285
}
286
287
.sourcecol {
288
    width: 50px;
289
}
290
291
.results-info {
292
    height: 100px;
293
    overflow: auto;
294
}
295
296
.toolscol {
297
    padding: 0;
298
    width: 100px;
299
}
300
301
.toolscol ul {
302
    margin: 0;
303
    padding: 0;
304
}
305
306
#searchresults .toolscol li {
307
    list-style-type: none;
308
    list-style-image: none;
309
}
310
311
.toolscol a {
312
    border-bottom: 1px solid #BCBCBC;
313
    display: block;
314
    padding: 0 1em;
315
    line-height: 24px;
316
}
317
318
.results-marc {
319
    font-family: monospace;
320
    height: auto;
321
    white-space: pre-wrap;
322
}
323
324
#searchresults {
325
    position: relative;
326
}
327
328
#search-overlay {
329
    background: white;
330
    bottom: 0;
331
    font-size: 2em;
332
    left: 0;
333
    opacity: .7;
334
    padding: 2em;
335
    position: absolute;
336
    right: 0;
337
    text-align: center;
338
    top: 0;
339
    z-index: 9001;
340
}
341
342
/*> Macros */
343
344
#macro-ui .CodeMirror {
345
    width: 100%;
346
}
347
348
#macro-save-message {
349
    color: #666;
350
    font-size: 13px;
351
    float: right;
352
    line-height: 26px;
353
}
354
355
#macro-list > li {
356
    border: 2px solid #F0F0F0;
357
    border-radius: 6px;
358
    display: block;
359
    font-size: 115%;
360
}
361
362
#macro-list > li + li {
363
    margin-top: -2px;
364
}
365
366
#macro-list .active {
367
    background: #EDF4F6;
368
    border-color: none;
369
}
370
371
#macro-list a {
372
    display: block;
373
    padding: 6px;
374
}
375
376
#macro-list a:focus {
377
    outline: none;
378
}
379
380
.macro-info {
381
    background-color: #F4F4F4;
382
    display: none;
383
    margin: 0;
384
    padding: 10px;
385
    text-align: right;
386
}
387
388
.macro-info li {
389
    color: #666;
390
    font-size: 75%;
391
    list-style-type: none;
392
}
393
394
.macro-info .label {
395
    clear: left;
396
    font-weight: bold;
397
    float: left;
398
}
399
400
#macro-list .active .macro-info {
401
    display: block;
402
}
(-)a/koha-tmpl/intranet-tmpl/prog/en/includes/cateditor-ui.inc (+835 lines)
Line 0 Link Here
1
<script src="/intranet-tmpl/lib/codemirror/codemirror-compressed.js"></script>
2
<script src="/intranet-tmpl/lib/filesaver.js"></script>
3
<script src="/intranet-tmpl/lib/koha/cateditor/marc-mode.js"></script>
4
<script src="/intranet-tmpl/lib/require.js"></script>
5
<script>
6
require.config( {
7
    baseUrl: '/intranet-tmpl/lib/koha/cateditor/',
8
    config: {
9
        resources: {
10
            themelang: '[% themelang %]',
11
        },
12
    },
13
    paths: {
14
        pz2: '../../pz2',
15
    },
16
    shim: {
17
        pz2: { exports: 'pz2' },
18
    },
19
} );
20
</script>
21
22
[% IF marcflavour == 'MARC21' %]
23
[% PROCESS 'cateditor-widgets-marc21.inc' %]
24
[% ELSE %]
25
<script>var editorWidgets = {};</script>
26
[% END %]
27
28
<script>
29
require( [ 'koha-backend', 'search', 'macros', 'marc-editor', 'marc-record', 'preferences', 'resources', 'text-marc', 'widget' ], function( KohaBackend, Search, Macros, MARCEditor, MARC, Preferences, Resources, TextMARC, Widget ) {
30
    var z3950Targets = {
31
        [% FOREACH target = z3950_targets %]
32
            '[% target.host %]:[% target.port %]/[% target.db %]': {
33
                'name': '[% target.name %]',
34
                'authentication': '[% target.userid %]:[% target.password %]',
35
                'syntax': '[% target.syntax %]',
36
                'kohasyntax': '[% target.syntax == 'USMARC' ? 'MARC21' : target.syntax %]',
37
                'encoding': '[% target.encoding %]',
38
                'checked': [% target.checked ? 'true' : 'false' %],
39
            },
40
        [% END %]
41
    };
42
43
    // The columns that should show up in a search, in order, and keyed by the corresponding <metadata> tag in the XSL and Pazpar2 config
44
    var z3950Labels = [
45
		[ "md-work-title", _("Title") ],
46
		[ "md-series-title", _("Series Title") ],
47
		[ "md-work-author", _("Author") ],
48
		[ "md-lccn", _("LCCN") ],
49
		[ "md-isbn", _("ISBN") ],
50
		[ "md-issn", _("ISSN") ],
51
		[ "md-medium", _("Medium") ],
52
		[ "md-edition", _("Edition") ],
53
		[ "md-description", _("Description") ],
54
    ];
55
56
    var state = {
57
        backend: '',
58
        saveBackend: 'catalog',
59
        recordID: undefined
60
    };
61
62
    var editor;
63
    var macroEditor;
64
65
    function makeAuthorisedValueWidgets( frameworkCode ) {
66
        $.each( KohaBackend.GetAllTagsInfo( frameworkCode ), function( tag, tagInfo ) {
67
            $.each( tagInfo.subfields, function( subfield, subfieldInfo ) {
68
                if ( !subfieldInfo.authorised_value ) return;
69
                var authvals = KohaBackend.GetAuthorisedValues( subfieldInfo.authorised_value );
70
                if ( !authvals ) return;
71
72
                var defaultvalue = subfield.defaultvalue || authvals[0].value;
73
74
                Widget.Register( tag + subfield, {
75
                    init: function() {
76
                        var $result = $( '<span class="subfield-widget"></span>' );
77
78
                        return $result[0];
79
                    },
80
                    postCreate: function() {
81
                        this.setText( defaultvalue );
82
83
                        $( '<select></select>' ).appendTo( this.node );
84
                        var $node = $( this.node ).find( 'select' );
85
                        $.each( authvals, function( undef, authval ) {
86
                            $node.append( '<option value="' + authval.value + '"' + (authval.value == defaultvalue ? ' selected="selected"' : '') + '>' + authval.lib + '</option>' );
87
                        } );
88
                        $node.val( this.text );
89
90
                        $node.change( $.proxy( function() {
91
                            this.setText( $node.val() );
92
                        }, this ) );
93
                    },
94
                    makeTemplate: function() {
95
                        return defaultvalue;
96
                    },
97
                } );
98
            } );
99
        } );
100
    }
101
102
    function bindGlobalKeys() {
103
        shortcut.add( 'ctrl+s', function(event) {
104
            $( '#save-record' ).click();
105
106
            event.preventDefault();
107
        } );
108
109
        shortcut.add( 'alt+ctrl+k', function(event) {
110
            if ( Search.IsAvailable() ) $( '#search-by-keywords' ).focus();
111
112
            return false;
113
        } );
114
115
        shortcut.add( 'alt+ctrl+a', function(event) {
116
            if ( Search.IsAvailable() ) $( '#search-by-author' ).focus();
117
118
            return false;
119
        } );
120
121
        shortcut.add( 'alt+ctrl+i', function(event) {
122
            if ( Search.IsAvailable() ) $( '#search-by-isbn' ).focus();
123
124
            return false;
125
        } );
126
127
        shortcut.add( 'alt+ctrl+t', function(event) {
128
            if ( Search.IsAvailable() ) $( '#search-by-title' ).focus();
129
130
            return false;
131
        } );
132
133
        $('#quicksearch .search-box').each( function() {
134
            shortcut.add( 'enter', $.proxy( function() {
135
                var q = this.value;
136
                if (!q) return false;
137
138
                if ( Search.Start( z3950Targets, $(this).data('qualifier') + q, 20 ) ) {
139
                    showResultsBox();
140
                }
141
142
                return false;
143
            }, this), { target: this, type: 'keypress' } );
144
        } );
145
    }
146
147
    // Record loading
148
    var backends = {
149
       'new': {
150
            titleForRecord: _("Editing new record"),
151
            get: function( id, callback ) {
152
                record = new MARC.Record();
153
                KohaBackend.FillRecord( '', record );
154
155
                callback( record );
156
            },
157
        },
158
        'new-full': {
159
            titleForRecord: _("Editing new full record"),
160
            get: function( id, callback ) {
161
                record = new MARC.Record();
162
                KohaBackend.FillRecord( '', record, true );
163
164
                callback( record );
165
            },
166
        },
167
        'catalog': {
168
            titleForRecord: _("Editing catalog record #{ID}"),
169
            href: "/cgi-bin/koha/catalogue/detail.pl?biblionumber={ID}",
170
            saveLabel: _("Save to catalog"),
171
            get: function( id, callback ) {
172
                if ( !id ) return false;
173
174
                KohaBackend.GetRecord( id, callback );
175
            },
176
            save: function( id, record, done ) {
177
                function finishCb( data ) {
178
                    done( { error: data.error, newRecord: data.marcxml && data.marcxml[0], newId: data.biblionumber && [ 'catalog', data.biblionumber ] } );
179
                }
180
181
                if ( id ) {
182
                    KohaBackend.SaveRecord( id, record, finishCb );
183
                } else {
184
                    KohaBackend.CreateRecord( record, finishCb );
185
                }
186
            }
187
        },
188
        'iso2709': {
189
            saveLabel: _("Save as ISO2709 (.mrc) file"),
190
            save: function( id, record, done ) {
191
                saveAs( new Blob( [record.toISO2709()], { 'type': 'application/octet-stream;charset=utf-8' } ), 'record.mrc' );
192
193
                done( {} );
194
            }
195
        },
196
        'marcxml': {
197
            saveLabel: _("Save as MARCXML (.xml) file"),
198
            save: function( id, record, done ) {
199
                saveAs( new Blob( [record.toXML()], { 'type': 'application/octet-stream;charset=utf-8' } ), 'record.xml' );
200
201
                done( {} );
202
            }
203
        },
204
        'search': {
205
            titleForRecord: _("Editing search result"),
206
            get: function( id, callback ) {
207
                if ( !id ) return false;
208
209
                Search.GetDetailedRecord( decodeURIComponent(id), callback );
210
            },
211
        },
212
    };
213
214
    function setSource(parts) {
215
        state.backend = parts[0];
216
        state.recordID = parts[1];
217
        state.canSave = backends[ state.backend ].save != null;
218
        state.saveBackend = state.canSave ? state.backend : 'catalog';
219
220
        var backend = backends[state.backend];
221
222
        document.location.hash = '#' + parts[0] + ':' + parts[1];
223
224
        if ( backend.href ) {
225
            $( '#title' ).html( backend.titleForRecord.replace( '{ID}', parts[1] ) + ' <a target="_blank" href="' + backend.href.replace( '{ID}', parts[1] ) + '">' + _("(view)") + '</a>' );
226
        } else {
227
            $( '#title' ).text( backend.titleForRecord.replace( '{ID}', parts[1] ) );
228
        }
229
        $( 'title', document.head ).html( _("Koha &rsaquo; Cataloging &rsaquo; ") + backend.titleForRecord.replace( '{ID}', parts[1] ) );
230
        $( '#save-record span' ).text( backends[ state.saveBackend ].saveLabel );
231
    }
232
233
    function saveRecord( recid, editor, callback ) {
234
        var parts = recid.split(':');
235
        if ( parts.length != 2 ) return false;
236
237
        if ( !backends[ parts[0] ] || !backends[ parts[0] ].save ) return false;
238
239
        editor.removeErrors();
240
        var record = editor.getRecord();
241
242
        if ( record.errors ) {
243
            state.saving = false;
244
            callback( { error: 'syntax', errors: record.errors } );
245
            return;
246
        }
247
248
        var errors = KohaBackend.ValidateRecord( '', record );
249
        if ( errors.length ) {
250
            state.saving = false;
251
            callback( { error: 'invalid', errors: errors } );
252
            return;
253
        }
254
255
        backends[ parts[0] ].save( parts[1], record, function(data) {
256
            state.saving = false;
257
258
            if (data.newRecord) {
259
                var record = new MARC.Record();
260
                record.loadMARCXML(data.newRecord);
261
                editor.displayRecord( record );
262
            }
263
264
            if (data.newId) {
265
                setSource(data.newId);
266
                } else {
267
                setSource( [ state.backend, state.recordID ] );
268
            }
269
270
            if (callback) callback( data );
271
        } );
272
    }
273
274
    function loadRecord( recid, editor, callback ) {
275
        var parts = recid.split(':');
276
        if ( parts.length != 2 ) return false;
277
278
        if ( !backends[ parts[0] ] || !backends[ parts[0] ].get ) return false;
279
280
        backends[ parts[0] ].get( parts[1], function( record ) {
281
            editor.displayRecord( record );
282
            editor.focus();
283
284
            if (callback) callback(record);
285
        } );
286
287
        return true;
288
    }
289
290
    function openRecord( recid, editor, callback ) {
291
        return loadRecord( recid, editor, function ( record ) {
292
            setSource( recid.split(':') );
293
294
            if (callback) callback( record );
295
        } );
296
    }
297
298
    // Search functions
299
    function showAdvancedSearch() {
300
        $('#advanced-search-ui').modal('show');
301
    }
302
303
    function startAdvancedSearch() {
304
        var search = '';
305
306
        $('#advanced-search-ui input').each( function() {
307
            if (!this.value) return;
308
            if (search) search += ' and ';
309
            search += $(this).data('qualifier') + this.value;
310
        } );
311
312
        if (!search) return;
313
314
        $('#advanced-search-ui').modal('hide');
315
316
        if ( Search.Start( z3950Targets, search, 20 ) ) {
317
            showResultsBox();
318
        }
319
    }
320
321
    function showResultsBox(data) {
322
        $('#searchresults thead tr').empty();
323
        $('#searchresults tbody').empty();
324
        $('#search-targetsinfo').empty().append('<li>' + _("Loading...") + '</li>');
325
        $('#search-results-ui').modal('show');
326
    }
327
328
    function showSearchResults( editor, data ) {
329
        $('#searchresults thead tr').empty();
330
        $('#searchresults tbody').empty();
331
332
        var seenColumns = {};
333
334
        $.each( data.hits, function( undef, hit ) {
335
            for ( key in hit ) {
336
                if ( /^md-/.test(key) ) seenColumns[key] = true;
337
            }
338
339
            $.each( hit.location, function( undef, location ) {
340
                for ( key in location ) {
341
                    if ( /^md-/.test(key) ) seenColumns[key] = true;
342
                }
343
            } );
344
        } );
345
346
        $('#searchresults thead tr').append('<th>' + _("Source") + '</th>');
347
348
        $.each( z3950Labels, function( undef, label ) {
349
            if ( seenColumns[ label[0] ] ) {
350
                $('#searchresults thead tr').append( '<th>' + label[1] + '</th>' );
351
            }
352
        } );
353
354
        $('#searchresults thead tr').append('<th>' + _("Tools") + '</th>');
355
356
        $.each( data.hits, function( undef, hit ) {
357
            var result = '<tr>';
358
            result += '<td class="sourcecol">' + hit.location[0]['@name'] + '</td>';
359
360
            $.each( z3950Labels, function( undef, label ) {
361
                if ( !seenColumns[ label[0] ] ) return;
362
363
                if ( hit[ label[0] ] ) {
364
                    result += '<td class="infocol">' + hit[ label[0] ].join('<br/>') + '</td>';
365
                } else if ( hit.location[0][ label[0] ] ) {
366
                    result += '<td class="infocol">' + hit.location[0][ label[0] ].join('<br/>') + '</td>';
367
                } else {
368
                    result += '<td class="infocol">&nbsp;</td>';
369
                }
370
            } );
371
372
            result += '<td class="toolscol"><ul><li><a href="#" class="marc-link">' + _("View MARC") + '</a></li>';
373
            result += '<li><a href="#" class="open-link">' + _("Import") + '</a></li>';
374
            if ( state.canSave ) result += '<li><a href="#" class="substitute-link" title="' + _("Replace the current record's contents") + '">' + _("Substitute") + '</a></li>';
375
            result += '</ul></td></tr>';
376
377
            var $tr = $( result );
378
            $tr.find( '.marc-link' ).click( function() {
379
                Search.GetDetailedRecord( hit.recid, function( record ) {
380
                    var $columns = $tr.find( '.infocol' );
381
                    CodeMirror.runMode( TextMARC.RecordToText( record ), 'marc', $( '<td class="infocol results-marc" colspan="' + $columns.length + '"></td>' ).replaceAll( $columns.slice(1).remove().end()[0] )[0] );
382
                } );
383
384
                return false;
385
            } );
386
            $tr.find( '.open-link' ).click( function() {
387
                $( '#search-results-ui' ).modal('hide');
388
                openRecord( hit.id, editor );
389
390
                return false;
391
            } );
392
            $tr.find( '.substitute-link' ).click( function() {
393
                $( '#search-results-ui' ).modal('hide');
394
                loadRecord( hit.id, editor );
395
396
                return false;
397
            } );
398
            $('#searchresults tbody').append( $tr );
399
        } );
400
401
        var $overlay = $('#search-overlay');
402
        $overlay.find('span').text(_("Loading"));
403
        $overlay.find('.bar').css( { display: 'block', width: 100 * ( 1 - data.activeclients / Search.includedTargets.length ) + '%' } );
404
405
        if ( data.activeclients ) {
406
            $overlay.find('.bar').css( { display: 'block', width: 100 * ( 1 - data.activeclients / Search.includedTargets.length ) + '%' } );
407
            $overlay.show();
408
        } else {
409
            $overlay.find('.bar').css( { display: 'block', width: '100%' } );
410
            $overlay.fadeOut();
411
        }
412
    }
413
414
    function invalidateSearchResults() {
415
        var $overlay = $('#search-overlay');
416
        $overlay.find('span').text(_("Search expired, please try again"));
417
        $overlay.find('.bar').css( { display: 'none' } );
418
        $overlay.show();
419
    }
420
421
    function showSearchTargets(data) {
422
        $('#search-targetsinfo').empty();
423
424
        $.each( data, function( undef, target ) {
425
            $('#search-targetsinfo').append( '<li>' + target.name + ' (' + target.hits + ')' + '</li>' );
426
        } );
427
    }
428
429
    function handleSearchError(error) {
430
        if (error.code == 1) {
431
            invalidateSearchResults();
432
            Search.Reconnect();
433
        } else {
434
            humanMsg.displayMsg( _("<h3>Internal search error</h3>") + '<p>' + error + '</p>' + _("<p>Please <b>refresh</b> the page and try again."), { className: 'humanError' } );
435
        }
436
    }
437
438
    function handleSearchInitError(error) {
439
        $('#quicksearch-overlay').fadeIn().find('p').text(error);
440
    }
441
442
    // Preference functions
443
    function showPreference( pref ) {
444
        var value = Preferences.user[pref];
445
446
        switch (pref) {
447
            case 'fieldWidgets':
448
                $( '#set-field-widgets' ).text( value ? _("Show fields verbatim") : _("Show helpers for fixed and coded fields") );
449
                break;
450
            case 'font':
451
                $( '#editor .CodeMirror' ).css( { fontFamily: value } );
452
                editor.refresh();
453
                break;
454
            case 'fontSize':
455
                $( '#editor .CodeMirror' ).css( { fontSize: value } );
456
                editor.refresh();
457
                break;
458
            case 'macros':
459
                showSavedMacros();
460
                break;
461
        }
462
    }
463
464
    function bindPreference( editor, pref ) {
465
        function _addHandler( sel, event, handler ) {
466
            $( sel ).on( event, function (e) {
467
                e.preventDefault();
468
                handler( e, Preferences.user[pref] );
469
                Preferences.Save( [% USER_INFO.0.borrowernumber %] );
470
                showPreference(pref);
471
            } );
472
        }
473
474
        switch (pref) {
475
            case 'fieldWidgets':
476
                _addHandler( '#set-field-widgets', 'click', function( e, oldValue ) {
477
                    editor.setUseWidgets( Preferences.user.fieldWidgets = !Preferences.user.fieldWidgets );
478
                } );
479
                break;
480
            case 'font':
481
                _addHandler( '#prefs-menu .set-font', 'click', function( e, oldValue ) {
482
                    Preferences.user.font = $( e.target ).css( 'font-family' );
483
                } );
484
                break;
485
            case 'fontSize':
486
                _addHandler( '#prefs-menu .set-fontSize', 'click', function( e, oldValue ) {
487
                    Preferences.user.fontSize = $( e.target ).css( 'font-size' );
488
                } );
489
                break;
490
        }
491
    }
492
493
    function displayPreferences( editor ) {
494
        $.each( Preferences.user, function( pref, value ) {
495
            showPreference( pref );
496
            bindPreference( editor, pref );
497
        } );
498
    }
499
500
    //> Macro functions
501
    function loadMacro( name ) {
502
        $( '#macro-list li' ).removeClass( 'active' );
503
        macroEditor.activeMacro = name;
504
505
        if ( !name ) {
506
            macroEditor.setValue( '' );
507
            return;
508
        }
509
510
        $( '#macro-list li[data-name="' + name + '"]' ).addClass( 'active' );
511
        var macro = Preferences.user.macros[name];
512
        macroEditor.setValue( macro.contents );
513
        if ( macro.history ) macroEditor.setHistory( macro.history );
514
    }
515
516
    function storeMacro( name, macro ) {
517
        if ( macro ) {
518
            Preferences.user.macros[name] = macro;
519
        } else {
520
            delete Preferences.user.macros[name];
521
        }
522
523
        Preferences.Save( [% USER_INFO.0.borrowernumber %] );
524
    }
525
526
    function showSavedMacros( macros ) {
527
        var scrollTop = $('#macro-list').scrollTop();
528
        $( '#macro-list' ).empty();
529
        var macro_list = $.map( Preferences.user.macros, function( macro, name ) {
530
            return $.extend( { name: name }, macro );
531
        } );
532
        macro_list.sort( function( a, b ) {
533
            return a.name.localeCompare(b.name);
534
        } );
535
        $.each( macro_list, function( undef, macro ) {
536
            var $li = $( '<li data-name="' + macro.name + '"><a href="#">' + macro.name + '</a><ol class="macro-info"></ol></li>' );
537
            $li.click( function() {
538
                loadMacro(macro.name);
539
                return false;
540
            } );
541
            if ( macro.name == macroEditor.activeMacro ) $li.addClass( 'active' );
542
            var modified = macro.modified && new Date(macro.modified);
543
            $li.find( '.macro-info' ).append(
544
                '<li><span class="label">' + _("Last changed:") + '</span>' +
545
                ( modified ? modified.toLocaleFormat() : _("never") ) + '</li>'
546
            );
547
            $('#macro-list').append($li);
548
        } );
549
        var $new_li = $( '<li class="new-macro"><a href="#">' + _("New macro...") + '</a></li>' );
550
        $new_li.click( function() {
551
            // TODO: make this a bit less retro
552
            var name = prompt(_("Please enter the name for the new macro:"));
553
            if (!name) return;
554
555
            if ( !Preferences.user.macros[name] ) storeMacro( name, { contents: "" } );
556
            showSavedMacros();
557
            loadMacro( name );
558
        } );
559
        $('#macro-list').append($new_li);
560
        $('#macro-list').scrollTop(scrollTop);
561
    }
562
563
    function saveMacro() {
564
        var name = macroEditor.activeMacro;
565
566
        if ( !name || macroEditor.savedGeneration == macroEditor.changeGeneration() ) return;
567
568
        macroEditor.savedGeneration = macroEditor.changeGeneration();
569
        storeMacro( name, { contents: macroEditor.getValue(), modified: (new Date()).valueOf(), history: macroEditor.getHistory() } );
570
        $('#macro-save-message').text(_("Saved"));
571
        showSavedMacros();
572
    }
573
574
    $(document).ready( function() {
575
        // Editor setup
576
        editor = new MARCEditor( function (elt) { $(elt).insertAfter('#toolbar') } );
577
578
        macroEditor = CodeMirror(
579
            $('#macro-editor')[0],
580
            {
581
                mode: 'null',
582
                lineNumbers: true,
583
            }
584
        );
585
586
        var resizeTimer = null;
587
        $( window ).resize( function() {
588
            if ( resizeTimer == null ) resizeTimer = setTimeout( function() {
589
                resizeTimer = null;
590
591
                var pos = $('#editor .CodeMirror').position();
592
                $('#editor .CodeMirror').height( $(window).height() - pos.top - 24 );
593
            }, 100);
594
        } ).resize();
595
596
        var saveableBackends = [];
597
        $.each( backends, function( id, backend ) {
598
            if ( backend.save ) saveableBackends.push( [ backend.saveLabel, id ] );
599
        } );
600
        saveableBackends.sort();
601
        $.each( saveableBackends, function( undef, backend ) {
602
            $( '#save-dropdown' ).append( '<li><a href="#" data-backend="' + backend[1] + '">' + backend[0] + '</a></li>' );
603
        } );
604
605
        // Click bindings
606
        $( '#save-record, #save-dropdown a' ).click( function() {
607
            $( '#save-record' ).find('i').attr( 'class', 'icon-loading' ).siblings( 'span' ).text( _("Saving...") );
608
609
            function finishCb(result) {
610
                if ( result.error == 'syntax' ) {
611
                    humanMsg.displayAlert( _("Incorrect syntax, cannot save"), { className: 'humanError' } );
612
                } else if ( result.error == 'invalid' ) {
613
                    humanMsg.displayAlert( _("Record structure invalid, cannot save"), { className: 'humanError' } );
614
                } else if ( !result.error ) {
615
                    humanMsg.displayAlert( _("Record saved "), { className: 'humanSuccess' } );
616
                }
617
618
                $.each( result.errors || [], function( undef, error ) {
619
                    switch ( error.type ) {
620
                        case 'noTag':
621
                            editor.addError( error.line, _("Invalid tag number") );
622
                            break;
623
                        case 'noIndicators':
624
                            editor.addError( error.line, _("Invalid indicators") );
625
                            break;
626
                        case 'missingTag':
627
                            editor.addError( null, _("Missing mandatory tag: ") + error.tag );
628
                            break;
629
                        case 'missingSubfield':
630
                            if ( error.subfield == '@' ) {
631
                                editor.addError( error.line, _("Missing control field contents") );
632
                            } else {
633
                                editor.addError( error.line, _("Missing mandatory subfield: $") + error.subfield );
634
                            }
635
                            break;
636
                        case 'unrepeatableTag':
637
                            editor.addError( error.line, _("Tag ") + error.tag + _(" cannot be repeated") );
638
                            break;
639
                        case 'unrepeatableSubfield':
640
                            editor.addError( error.line, _("Subfield $") + error.subfield + _(" cannot be repeated") );
641
                            break;
642
                    }
643
                } );
644
645
                $( '#save-record' ).find('i').attr( 'class', 'icon-hdd' );
646
647
                if ( result.error ) {
648
                    // Reset backend info
649
                    setSource( [ state.backend, state.recordID ] );
650
                }
651
            }
652
653
            var backend = $( this ).data( 'backend' ) || ( state.saveBackend );
654
            if ( state.backend == backend ) {
655
                saveRecord( backend + ':' + state.recordID, editor, finishCb );
656
            } else {
657
                saveRecord( backend + ':', editor, finishCb );
658
            }
659
660
            return false;
661
        } );
662
663
        $('#import-records').click( function() {
664
            $('#import-records-input')
665
                .off('change')
666
                .change( function() {
667
                    if ( !this.files || !this.files.length ) return;
668
669
                    var file = this.files[0];
670
                    var reader = new FileReader();
671
672
                    reader.onload = function() {
673
                        var record = new MARC.Record();
674
675
                        if ( /\.mrc$/.test( file.name ) ) {
676
                            record.loadISO2709( reader.result );
677
                        } else if ( /\.xml$/.test( file.name ) ) {
678
                            record.loadMARCXML( reader.result );
679
                        } else {
680
                            humanMsg.displayAlert( _("Unknown record type, cannot import"), { className: 'humanError' } );
681
                            return;
682
                        }
683
684
                       editor.displayRecord( record );
685
                    };
686
687
                    reader.readAsText( file );
688
                } )
689
                .click();
690
691
            return false;
692
        } );
693
694
        $('#open-macros').click( function() {
695
            $('#macro-ui').modal('show');
696
697
            return false;
698
        } );
699
700
        $('#run-macro').click( function() {
701
            var result = Macros.Run( editor, macroEditor.getValue() );
702
703
            if ( !result.errors.length ) return false;
704
705
            var errors = [];
706
            $.each( result.errors, function() {
707
                var error = '<b>' + _("Line ") + (this.line + 1) + ':</b> ';
708
709
                switch ( this.error ) {
710
                    case 'failed': error += _("failed to run"); break;
711
                    case 'unrecognized': error += _("unrecognized command"); break;
712
                }
713
714
                errors.push(error);
715
            } );
716
717
            humanMsg.displayMsg( _("<h3>Failed to run macro:</h3>") + '<ul><li>' + errors.join('</li><li>') + '</li></ul>', { className: 'humanError' } );
718
719
            return false;
720
        } );
721
722
        $('#delete-macro').click( function() {
723
            if ( !macroEditor.activeMacro || !confirm( _("Are you sure you want to delete this macro?") ) ) return;
724
725
            storeMacro( macroEditor.activeMacro, undefined );
726
            showSavedMacros();
727
            loadMacro( undefined );
728
729
            return false;
730
        } );
731
732
        var saveTimeout;
733
        macroEditor.on( 'change', function( cm, change ) {
734
            $('#macro-save-message').empty();
735
            if ( change.origin == 'setValue' ) return;
736
737
            if ( saveTimeout ) clearTimeout( saveTimeout );
738
            saveTimeout = setTimeout( function() {
739
                saveMacro();
740
741
                saveTimeout = null;
742
            }, 500 );
743
        } );
744
745
        $( '#switch-editor' ).click( function() {
746
            if ( !confirm( _("Any changes will not be saved. Continue?") ) ) return;
747
748
            $.cookie( 'catalogue_editor_[% USER_INFO.0.borrowernumber %]', 'basic', { expires: 365, path: '/' } );
749
750
            if ( state.backend == 'catalog' ) {
751
                window.location = '/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=' + state.recordID;
752
            } else if ( state.backend == 'new' ) {
753
                window.location = '/cgi-bin/koha/cataloguing/addbiblio.pl';
754
            } else {
755
                humanMsg.displayAlert( _("Cannot open this record in the basic editor"), { className: 'humanError' } );
756
            }
757
        } );
758
759
        $( '#show-advanced-search' ).click( function() {
760
            showAdvancedSearch();
761
762
            return false;
763
        } );
764
765
        $('#advanced-search').submit( function() {
766
            startAdvancedSearch();
767
768
            return false;
769
        } );
770
771
        // Key bindings
772
        bindGlobalKeys();
773
774
        // Setup UI
775
        $("#advanced-search-ui, #search-results-ui, #macro-ui").each( function() {
776
            $(this).modal({ show: false }).css({
777
                marginLeft: function() {
778
                    return -($(this).width() / 2);
779
                }
780
            });
781
        } );
782
783
        var $quicksearch = $('#quicksearch fieldset');
784
        $('<div id="quicksearch-overlay"><h3>' + _("Search unavailable") + '</h3> <p></p></div>').css({
785
            position: 'absolute',
786
            top: $quicksearch.offset().top,
787
            left: $quicksearch.offset().left,
788
            height: $quicksearch.outerHeight(),
789
            width: $quicksearch.outerWidth(),
790
        }).appendTo(document.body).hide();
791
792
        var prevAlerts = [];
793
        humanMsg.logMsg = function(msg, options) {
794
            $('#show-alerts').popover('hide');
795
            prevAlerts.unshift('<li>' + msg + '</li>');
796
            prevAlerts.splice(5, 999); // Truncate old messages
797
        };
798
799
        $('#show-alerts').popover({
800
            html: true,
801
            placement: 'bottom',
802
            content: function() {
803
                return '<div id="alerts-container"><ul>' + prevAlerts.join('') + '</ul></div>';
804
            },
805
        });
806
807
        // Start editor
808
        Preferences.Load( [% USER_INFO.0.borrowernumber %] );
809
        displayPreferences(editor);
810
        makeAuthorisedValueWidgets( '' );
811
        Search.Init( z3950Targets, {
812
            onresults: function(data) { showSearchResults( editor, data ) },
813
            onbytarget: showSearchTargets,
814
            onerror: handleSearchError,
815
            oniniterror: handleSearchInitError,
816
        } );
817
818
        function finishCb() {
819
            Resources.GetAll().done( function() {
820
                $("#loading").hide();
821
                editor.focus();
822
            } );
823
        }
824
825
        if ( "[% auth_forwarded_hash %]" ) {
826
            document.location.hash = "[% auth_forwarded_hash %]";
827
        }
828
829
        if ( !document.location.hash || !openRecord( document.location.hash.slice(1), editor, finishCb ) ) {
830
            openRecord( 'new:', editor, finishCb );
831
        }
832
    } );
833
} )();
834
835
</script>
(-)a/koha-tmpl/intranet-tmpl/prog/en/includes/cateditor-widgets-marc21.inc (+158 lines)
Line 0 Link Here
1
<div id="editor-widget-templates" style="display:none">
2
    <div id="widget-leader">
3
        Leader:&nbsp;<span title="Record length (autogenerated)">#####</span>
4
        <select name="f5" title="Record status">
5
            <option value="a">a - Increase in encoding level</option>
6
            <option value="c">c - Corrected or revised</option>
7
            <option value="d">d - Deleted</option>
8
            <option value="n">n - New</option>
9
            <option value="p">p - Increase in encoding level from prepublication</option>
10
        </select>
11
        <select name="f6" title="Type of record">
12
            <option value="a">a - Language material</option>
13
            <option value="c">c - Notated music</option>
14
            <option value="d">d - Manuscript notated music</option>
15
            <option value="e">e - Cartographic material</option>
16
            <option value="f">f - Manuscript cartographic material</option>
17
            <option value="g">g - Projected medium</option>
18
            <option value="i">i - Nonmusical sound recording</option>
19
            <option value="j">j - Musical sound recording</option>
20
            <option value="k">k - Two-dimensional nonprojectable graphic</option>
21
            <option value="m">m - Computer file</option>
22
            <option value="o">o - Kit</option>
23
            <option value="p">p - Mixed materials</option>
24
            <option value="r">r - Three-dimensional artifact or naturally occurring object</option>
25
            <option value="t">t - Manuscript language material</option>
26
        </select>
27
        <select name="f7" title="Bibliographic level">
28
            <option value="a">a - Monographic component part</option>
29
            <option value="b">b - Serial component part</option>
30
            <option value="c">c - Collection</option>
31
            <option value="d">d - Subunit</option>
32
            <option value="i">i - Integrating resource</option>
33
            <option value="m">m - Monograph/item</option>
34
            <option value="s">s - Serial</option>
35
        </select>
36
        <select name="f8" title="Type of control">
37
                <option value=" ">_ - No specific type</option>
38
                <option value="a">a - Archival</option>
39
        </select>
40
        <span title="Encoding (forced Unicode)">a</span>
41
        <span title="Indicator/subfield lengths">22</span>
42
        <span title="Data base address (autogenerated)">#####</span>
43
        <select name="f17" title="Encoding level">
44
            <option value=" ">_ - Full level</option>
45
            <option value="1">1 - Full level, material not examined</option>
46
            <option value="2">2 - Less-than-full level, material not examined</option>
47
            <option value="3">3 - Abbreviated level</option>
48
            <option value="4">4 - Core level</option>
49
            <option value="5">5 - Partial (preliminary) level</option>
50
            <option value="7">7 - Minimal level</option>
51
            <option value="8">8 - Prepublication level</option>
52
            <option value="u">u - Unknown</option>
53
            <option value="z">z - Not applicable</option>
54
        </select>
55
        <select name="f18" title="Descriptive cataloging form">
56
            <option value=" ">_ - Non-ISBD</option>
57
            <option value="a">a - AACR 2</option>
58
            <option value="c">c - ISBD punctuation omitted</option>
59
            <option value="i">i - ISBD punctuation included</option>
60
            <option value="u">u - Unknown</option>
61
        </select>
62
        <select name="f19" title="Multipart record resource level">
63
            <option value=" ">_ - Not specified or not applicable</option>
64
            <option value="a">a - Set</option>
65
            <option value="b">b - Part with independent title</option>
66
            <option value="c">c - Part with dependent title</option>
67
        </select>
68
        <span title="Length of directory elements">4500</span>
69
    </div>
70
</div>
71
72
<script>
73
74
/**
75
 * Each widget should provide one to three methods:
76
 *   init( text ): Returns the DOM node for this widget.
77
 *   postCreate( node, mark ): Optional, called once the mark has been created
78
 *                             and the node shown. Bind event handlers here.
79
 *   makeTemplate(): Optional, should return some sane default contents for a
80
 *                   newly created field/subfield. '<empty>' will be used if this
81
 *                   method is unset.
82
 *
83
 * Following the Koha convention, control fields are defined as tags with a
84
 * single subfield, '@'.
85
 */
86
87
require( [ 'widget' ], function( Widget ) {
88
    Widget.Register( '000@', {
89
        makeTemplate: function() {
90
            return '     nam a22     7a 4500';
91
        },
92
        init: function() {
93
            var $result = $( '<span class="subfield-widget fixed-widget"></span>' );
94
95
            return $result[0];
96
        },
97
        postCreate: function() {
98
            // Clear the length and directory start fields; these are unnecessary for MARCXML and will be filled in upon USMARC export
99
            this.setFixed( 0, 5, '     ' );
100
            this.setFixed( 9, 17, 'a22     ' );
101
            this.setFixed( 20, 24, '4500' );
102
103
            this.insertTemplate( '#widget-leader' );
104
105
            this.bindFixed( '[name=f5]', 5, 6 );
106
            this.bindFixed( '[name=f6]', 6, 7 );
107
            this.bindFixed( '[name=f7]', 7, 8 );
108
            this.bindFixed( '[name=f8]', 8, 9 );
109
            this.bindFixed( '[name=f17]', 17, 18 );
110
            this.bindFixed( '[name=f18]', 18, 19 );
111
            this.bindFixed( '[name=f19]', 19, 20 );
112
        },
113
    } );
114
115
    Widget.Register( '005@', {
116
        init: function() {
117
            var $result = $( '<span class="subfield-widget fixed-widget">Updated: </span>' );
118
119
            return $result[0];
120
        },
121
        postCreate: function( node, mark ) {
122
            var parts = this.text.match( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d)/ );
123
124
            if ( parts ) {
125
                var dateVal = new Date(
126
                    parseInt( parts[1] ), // Year
127
                    parseInt( parts[2] ) - 1, // Month (0-11)
128
                    parseInt( parts[3] ), // Day
129
                    parseInt( parts[4] ), // Hour
130
                    parseInt( parts[5] ), // Minute
131
                    parseInt( parts[6] ), // Second
132
                    parseInt( parts[7] ) * 100 // Millisecond
133
                );
134
135
                $( this.node ).append( dateVal.toLocaleString() );
136
            } else {
137
                $( this.node ).append( '<span class="hint">unset</span>' );
138
            }
139
        }
140
    } );
141
142
    Widget.Register( '008@', {
143
        makeTemplate: function() {
144
            var now = new Date();
145
            return Widget.PadNum( now.getYear() % 100, 2 ) + Widget.PadNum( now.getMonth() + 1, 2 ) + Widget.PadNum( now.getDate(), 2 ) + "b        xxu||||| |||| 00| 0 [% DefaultLanguageField008 %] d";
146
        },
147
        init: function() {
148
            var $result = $( '<span class="subfield-widget fixed-widget">Fixed data:<span class="hint widget-loading">Loading...</span></span>' );
149
150
            return $result[0];
151
        },
152
        postCreate: function( node, mark ) {
153
            this.createFromXML( 'marc21/xml/008' );
154
        }
155
    } );
156
} );
157
158
</script>
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbiblio.tt (-1 / +21 lines)
Lines 100-106 Link Here
100
            redirect("just_save", tab);
100
            redirect("just_save", tab);
101
            return false;
101
            return false;
102
        });
102
        });
103
    });
103
104
        $( '#switcheditor' ).click( function() {
105
            var breedingid = [% breedingid || "null" %];
106
107
            if ( !confirm( breedingid ? _("This record cannot be transferred to the advanced editor. Continue?") : _("Any changes will not be saved. Continue?") ) ) return false;
108
109
            $.cookie( 'catalogue_editor_[% USER_INFO.0.borrowernumber %]', 'advanced', { expires: 365, path: '/' } );
110
111
            var biblionumber = [% biblionumber || "null" %];
112
113
            if ( biblionumber ) {
114
                window.location = '/cgi-bin/koha/cataloguing/editor.pl#catalog:' + biblionumber;
115
            } else {
116
                window.location = '/cgi-bin/koha/cataloguing/editor.pl';
117
            }
118
119
            return false;
120
        } );
121
122
	});
104
123
105
function redirect(dest){
124
function redirect(dest){
106
    $("#redirect").attr("value",dest);
125
    $("#redirect").attr("value",dest);
Lines 457-462 function Changefwk(FwkList) { Link Here
457
476
458
    [% UNLESS (circborrowernumber) %][%# Hide in fast cataloging %]
477
    [% UNLESS (circborrowernumber) %][%# Hide in fast cataloging %]
459
        <div class="btn-group"><a class="btn btn-small" href="#" id="z3950search"><i class="icon-search"></i> Z39.50 search</a></div>
478
        <div class="btn-group"><a class="btn btn-small" href="#" id="z3950search"><i class="icon-search"></i> Z39.50 search</a></div>
479
        <div class="btn-group"><a href="#" id="switcheditor" class="btn btn-small">Switch to advanced editor</a></div>
460
        [% IF (biblionumber) %]
480
        [% IF (biblionumber) %]
461
            [% IF ( BiblioDefaultViewmarc ) %]
481
            [% IF ( BiblioDefaultViewmarc ) %]
462
                <div class="btn-group">
482
                <div class="btn-group">
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbooks.tt (+6 lines)
Lines 15-20 Link Here
15
            PopupZ3950($(this).prop('id'));
15
            PopupZ3950($(this).prop('id'));
16
            return false;
16
            return false;
17
        });
17
        });
18
19
        $("#useadvanced").click(function(){
20
            $.cookie( 'catalogue_editor_[% USER_INFO.0.borrowernumber %]', 'advanced', { expires: 365, path: '/' } );
21
            return true;
22
        });
18
     });
23
     });
19
24
20
    /* this function open a popup to search on z3950 server.  */
25
    /* this function open a popup to search on z3950 server.  */
Lines 48-53 Link Here
48
53
49
[% IF ( CAN_user_editcatalogue_edit_catalogue ) %]
54
[% IF ( CAN_user_editcatalogue_edit_catalogue ) %]
50
  <div id="toolbar" class="btn-toolbar">
55
  <div id="toolbar" class="btn-toolbar">
56
        <a id="useadvanced" href="/cgi-bin/koha/cataloguing/editor.pl" class="btn btn-small"><i class="icon-edit"></i> Advanced editor</a>
51
        <div class="btn-group">
57
        <div class="btn-group">
52
            <button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-plus"></i> New record <span class="caret"></span></button>
58
            <button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-plus"></i> New record <span class="caret"></span></button>
53
            <ul class="dropdown-menu">
59
            <ul class="dropdown-menu">
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/editor.tt (+213 lines)
Line 0 Link Here
1
[% INCLUDE 'doc-head-open.inc' %]
2
<title>Koha &rsaquo; Cataloging &rsaquo; Editor</title>
3
[% INCLUDE 'doc-head-close.inc' %]
4
<script type="text/javascript" src="[% themelang %]/lib/jquery/plugins/jquery.fixFloat.js"></script>
5
<link type="text/css" rel="stylesheet" href="[% themelang %]/css/cateditor.css" />
6
<link type="text/css" rel="stylesheet" href="/intranet-tmpl/lib/codemirror/codemirror.css" />
7
<link rel="stylesheet" type="text/css" href="[% themelang %]/css/humanmsg.css" />
8
<script src="[% interface %]/lib/jquery/plugins/humanmsg.js" type="text/javascript"></script>
9
[% IF ( bidi ) %]
10
   <link rel="stylesheet" type="text/css" href="[% themelang %]/css/right-to-left.css" />
11
[% END %]
12
</head>
13
<body id="cat_addbiblio" class="cat">
14
15
   <div id="loading">
16
       <div>Loading, please wait...</div>
17
   </div>
18
19
[% INCLUDE 'header.inc' %]
20
21
<div id="breadcrumbs"><a href="/cgi-bin/koha/mainpage.pl">Home</a> &rsaquo; <a href="/cgi-bin/koha/cataloguing/addbooks.pl">Cataloging</a> &rsaquo; Editor</div>
22
23
<div id="doc3" class="yui-t2">
24
<div id="bd">
25
26
<h1 id="title">Cataloging editor</h1>
27
28
<div id="yui-main"><div class="yui-b">
29
30
<div id="editor">
31
    <input id="import-records-input" type="file" style="display: none">
32
    <div id="toolbar" class="btn-toolbar">
33
        <div class="btn-group">
34
            <button class="btn btn-small" id="save-record" title="Save current record (Ctrl-S)"><i class="icon-hdd"></i> <span>Save</span></button>
35
            <button class="btn btn-small dropdown-toggle" data-toggle="dropdown">
36
            <span class="caret"></span>
37
            </button>
38
            <ul class="dropdown-menu" id="save-dropdown">
39
            </ul>
40
        </div>
41
        <button class="btn btn-small" id="import-records" title="Import an ISO2709 or MARCXML record"><i class="icon-upload"></i> <span>Import record...</span></button>
42
        <button class="btn btn-small" id="open-macros" title="Run and edit macros"><i class="icon-play"></i> <span>Macros...</span></button>
43
        <div class="btn-group">
44
            <button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-cog"></i> Settings <span class="caret"></span></button>
45
            <ul id="prefs-menu" class="dropdown-menu">
46
                <li><a id="switch-editor" href="#">Switch to basic editor</a></li>
47
                <li><a id="set-field-widgets" href="#"></a></li>
48
                <li class="divider"></li>
49
                <li><a class="set-fontSize" style="font-size: .92em" href="#">Small text</a></li>
50
                <li><a class="set-fontSize" style="font-size: 1em" href="#">Normal text</a></li>
51
                <li><a class="set-fontSize" style="font-size: 1.08em" href="#">Large text</a></li>
52
                <li><a class="set-fontSize" style="font-size: 1.18em" href="#">Huge text</a></li>
53
                <li class="divider"></li>
54
                <li><a class="set-font" style="font-family: monospace" href="#">Default font</a></li>
55
                <li><a class="set-font" style="font-family: 'Courier New'" href="#">Courier New</a></li>
56
                <li><a class="set-font" style="font-family: peep" href="#">peep</a></li>
57
            </ul>
58
        </div>
59
        <button class="btn btn-small" id="show-alerts" title="Previous alerts"><i class="icon-info-sign"></i> Alerts <span class="caret"></span></button>
60
    </div>
61
    [%# CodeMirror instance will be inserted here %]
62
    <div id="statusbar">
63
        <div id="status-tag-info">
64
        </div>
65
        <div id="status-subfield-info">
66
        </div>
67
    </div>
68
</div>
69
70
</div></div>
71
72
<div class="yui-b" id="sidebar">
73
74
<h3>Search</h3>
75
<form id="quicksearch">
76
    <fieldset class="brief">
77
    <ol>
78
        <li><label for="search-by-keywords">Keywords:</label></li>
79
        <li><input class="search-box" data-qualifier="term=" id="search-by-keywords" placeholder="(Ctrl-Alt-K)" /></li>
80
        <li><label for="search-by-author">Author:</label></li>
81
        <li><input class="search-box" data-qualifier="Author-name=" id="search-by-author" placeholder="(Ctrl-Alt-A)" /></li>
82
        <li><label for="search-by-isbn">ISBN:</label></li>
83
        <li><input class="search-box" data-qualifier="Identifier-ISBN=" id="search-by-isbn" placeholder="(Ctrl-Alt-I)" /></li>
84
        <li><label for="search-by-title">Title:</label></li>
85
        <li><input class="search-box" data-qualifier="Title=" id="search-by-title" placeholder="(Ctrl-Alt-T)" /></li>
86
        <li><a href="#" id="show-advanced-search" title="Show advanced search (Ctrl-Alt-S)">Advanced &raquo;</a></li>
87
    </fieldset>
88
</form>
89
90
</div>
91
92
</div>
93
</div>
94
95
<div id="advanced-search-ui" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="advanced-search-title" aria-hidden="true">
96
97
<div class="modal-header">
98
    <button type="button" class="closebtn" data-dismiss="modal" aria-hidden="true">×</button>
99
    <h3 id="advanced-search-title">Advanced search</h3>
100
</div>
101
102
<form id="advanced-search" class="modal-body">
103
    <div id="toolbar" class="btn-toolbar">
104
        <button class="btn btn-small" type="submit"><i class="icon-search"></i> <span>Search</span></button>
105
        <button class="btn btn-small" type="reset"><i class="icon-remove"></i> <span>Clear</span></button>
106
    </div>
107
    <ul id="advanced-search-fields">
108
        <li>
109
            <label for="advanced-search-by-author">Author:</label>
110
            <input class="search-box" data-qualifier="Author-name=" id="advanced-search-by-author" />
111
        </li>
112
        <li>
113
            <label for="advanced-search-by-control-number">Control number:</label>
114
            <input class="search-box" data-qualifier="Local-number=" id="advanced-search-by-control-number" />
115
        </li>
116
        <li>
117
            <label for="advanced-search-by-dewey">Dewey number:</label>
118
            <input class="search-box" data-qualifier="Classification-Dewey=" id="advanced-search-by-dewey" />
119
        </li>
120
        <li>
121
            <label for="advanced-search-by-isbn">ISBN:</label>
122
            <input class="search-box" data-qualifier="Identifier-ISBN=" id="advanced-search-by-isbn" />
123
        </li>
124
        <li>
125
            <label for="advanced-search-by-issn">ISSN:</label>
126
            <input class="search-box" data-qualifier="Identifier-ISSN=" id="advanced-search-by-issn" />
127
        </li>
128
        <li>
129
            <label for="advanced-search-by-lccn">LCCN:</label>
130
            <input class="search-box" data-qualifier="LC-card-number=" id="advanced-search-by-lccn" />
131
        </li>
132
        <li>
133
            <label for="advanced-search-by-lc-number">LC call number:</label>
134
            <input class="search-box" data-qualifier="Classification-LC=" id="advanced-search-by-lc-number" />
135
        </li>
136
        <li>
137
            <label for="advanced-search-by-publisher-number">Publisher number:</label>
138
            <input class="search-box" data-qualifier="Identifier-publisher-for-music=" id="advanced-search-by-publisher-number" />
139
        </li>
140
        <li>
141
            <label for="advanced-search-by-standard-number">Standard number:</label>
142
            <input class="search-box" data-qualifier="Identifier-standard=" id="advanced-search-by-standard-number" />
143
        </li>
144
        <li>
145
            <label for="advanced-search-by-subject">Subject:</label>
146
            <input class="search-box" data-qualifier="Subject=" id="advanced-search-by-subject" />
147
        </li>
148
        <li>
149
            <label for="advanced-search-by-publication-date">Publication date:</label>
150
            <input class="search-box" data-qualifier="Date=" id="advanced-search-by-publication-date" />
151
        </li>
152
        <li>
153
            <label for="advanced-search-by-title">Title:</label>
154
            <input class="search-box" data-qualifier="Title=" id="advanced-search-by-title" />
155
        </li>
156
    </ul>
157
</form>
158
159
</div>
160
161
<div id="search-results-ui" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="search-results-title" aria-hidden="true">
162
163
<div class="modal-header">
164
    <button type="button" class="closebtn" data-dismiss="modal" aria-hidden="true">×</button>
165
    <h3 id="search-results-title">Results</h3>
166
</div>
167
168
<div class="modal-body row-fluid">
169
    <div class="span3">
170
        <div id="search-facets">
171
            <ul>
172
                <li>Targets:<ul id="search-targetsinfo"></ul></li>
173
            </ul>
174
        </div>
175
    </div>
176
    <div class="span9">
177
        <div id="searchresults">
178
            <table>
179
                <thead>
180
                    <tr></tr>
181
                </thead>
182
                <tbody></tbody>
183
            </table>
184
            <div id="search-overlay"><span>Loading...</span><div class="progress progress-striped active"><div class="bar" style="width: 0"></div></div></div>
185
        </div>
186
    </div>
187
</div>
188
189
</div>
190
191
<div id="macro-ui" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="macro-title" aria-hidden="true">
192
193
<div class="modal-header">
194
    <button type="button" class="closebtn" data-dismiss="modal" aria-hidden="true">×</button>
195
    <h3 id="macro-title">Macros</h3>
196
</div>
197
198
<div class="modal-body row-fluid">
199
    <div class="span3"><ul id="macro-list"></ul></div>
200
    <div class="span9" id="macro-editor">
201
        <div id="macro-toolbar" class="btn-toolbar">
202
            <button class="btn btn-small" id="run-macro"itle="Run and edit macros"><i class="icon-play"></i> Run macro</button>
203
            <button class="btn btn-small" id="delete-macro" title="Delete macro"><i class="icon-remove"></i> Delete macro</button>
204
            <div id="macro-save-message"></div>
205
        </div>
206
    </div>
207
</div>
208
209
</div>
210
211
[% PROCESS 'cateditor-ui.inc' %]
212
213
[% INCLUDE 'intranet-bottom.inc' %]
(-)a/svc/cataloguing/framework (-1 / +73 lines)
Line 0 Link Here
0
- 
1
#!/usr/bin/perl
2
3
use Modern::Perl '2009';
4
5
use CGI;
6
use C4::Branch;
7
use C4::ClassSource;
8
use C4::Context;
9
use C4::Biblio;
10
use C4::Service;
11
12
my ( $query, $response ) = C4::Service->init( editcatalogue => 'edit_catalogue' );
13
14
my $frameworkcode = $query->param( 'frameworkcode' ) // '';
15
16
my $tagslib = GetMarcStructure( 1, $frameworkcode );
17
18
my @tags;
19
20
foreach my $tag ( sort keys %$tagslib ) {
21
    my $taglib = $tagslib->{$tag};
22
    my $taginfo = { map { $_, $taglib->{$_} } grep { length $_ > 1 } keys %$taglib };
23
    $taginfo->{subfields} = [ map { [ $_, $taglib->{$_} ] } grep { length $_ == 1 } sort keys %$taglib ];
24
25
    push @tags, [ $tag, $taginfo ];
26
}
27
28
my $dbh = C4::Context->dbh;
29
my $authorised_values = {};
30
31
$authorised_values->{branches} = [];
32
my $onlymine=C4::Context->preference('IndependentBranches') &&
33
        C4::Context->userenv &&
34
        C4::Context->userenv->{flags} % 2 == 0 &&
35
        C4::Context->userenv->{branch};
36
my $branches = GetBranches($onlymine);
37
foreach my $thisbranch ( sort keys %$branches ) {
38
    push @{ $authorised_values->{branches} }, { value => $thisbranch, lib => $branches->{$thisbranch}->{'branchname'} };
39
}
40
41
$authorised_values->{itemtypes} = $dbh->selectall_arrayref( q{
42
    SELECT itemtype AS value, description AS lib FROM itemtypes ORDER BY description
43
}, { Slice => {} } );
44
45
my $class_sources = GetClassSources();
46
47
my $default_source = C4::Context->preference("DefaultClassificationSource");
48
49
foreach my $class_source (sort keys %$class_sources) {
50
    next unless $class_sources->{$class_source}->{'used'} or
51
                ($class_source eq $default_source);
52
    push @{ $authorised_values->{cn_source} }, { value => $class_source, lib => $class_sources->{$class_source}->{'description'} };
53
}
54
55
my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
56
my $auth_query = "SELECT category, authorised_value, lib
57
            FROM authorised_values";
58
$auth_query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit;
59
$auth_query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
60
$auth_query .= " GROUP BY lib ORDER BY lib, lib_opac";
61
my $authorised_values_sth = $dbh->prepare( $auth_query );
62
$authorised_values_sth->execute(
63
    $branch_limit ? $branch_limit : (),
64
);
65
66
while ( my ( $category, $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
67
    $authorised_values->{$category} ||= [];
68
    push @{ $authorised_values->{$category} }, { value => $lib, lib => $lib };
69
}
70
71
$response->param( framework => \@tags, authorised_values => $authorised_values );
72
73
C4::Service->return_success( $response );

Return to bug 11559