diff --git a/code/__DEFINES/misc.dm b/code/__DEFINES/misc.dm index 6de010d5f60..3c97d39a9c2 100644 --- a/code/__DEFINES/misc.dm +++ b/code/__DEFINES/misc.dm @@ -167,4 +167,6 @@ #define POLLTYPE_OPTION "OPTION" #define POLLTYPE_TEXT "TEXT" #define POLLTYPE_RATING "NUMVAL" -#define POLLTYPE_MULTI "MULTICHOICE" \ No newline at end of file +#define POLLTYPE_MULTI "MULTICHOICE" + +#define MIDNIGHT_ROLLOVER 864000 //number of deciseconds in a day \ No newline at end of file diff --git a/code/game/machinery/telecomms/traffic_control.dm b/code/game/machinery/telecomms/traffic_control.dm index fe9d7c04f51..f883d9e87e4 100644 --- a/code/game/machinery/telecomms/traffic_control.dm +++ b/code/game/machinery/telecomms/traffic_control.dm @@ -5,9 +5,10 @@ var/list/servers = list() // the servers located by the computer var/mob/editingcode var/mob/lasteditor - var/list/viewingcode = list() var/obj/machinery/telecomms/server/SelectedServer + var/compiling_errors = "" + var/network = "NULL" // the network to probe var/temp = "" // temporary feedback messages @@ -18,192 +19,262 @@ req_access = list(access_tcomsat) circuit = "/obj/item/weapon/circuitboard/comm_traffic" +/obj/machinery/computer/telecomms/traffic/attack_hand(mob/user) + interact(user) - proc/update_ide() +/obj/machinery/computer/telecomms/traffic/interact(mob/user) + if(stat & (BROKEN|NOPOWER)) + return 0 - // loop if there's someone manning the keyboard - while(editingcode) - if(!editingcode.client) - editingcode = null - break + user.set_machine(src) - // For the typer, the input is enabled. Buffer the typed text - if(editingcode) - storedcode = "[winget(editingcode, "tcscode", "text")]" - if(editingcode) // double if's to work around a runtime error - winset(editingcode, "tcscode", "is-disabled=false") + if(!editingcode || editingcode && editingcode.machine != src) + editingcode = user + lasteditor = user - // If the player's not manning the keyboard anymore, adjust everything - if( (!(editingcode in range(1, src)) && !issilicon(editingcode)) || (editingcode.machine != src && !issilicon(editingcode))) - if(editingcode) - winshow(editingcode, "Telecomms IDE", 0) // hide the window! - editingcode = null - break + var/dat = "
Telecommunications Traffic Control
" - // For other people viewing the typer type code, the input is disabled and they can only view the code - // (this is put in place so that there's not any magical shenanigans with 50 people inputting different code all at once) - - if(length(viewingcode)) - // This piece of code is very important - it escapes quotation marks so string aren't cut off by the input element - var/showcode = replacetext(storedcode, "\\\"", "\\\\\"") - showcode = replacetext(storedcode, "\"", "\\\"") - - for(var/mob/M in viewingcode) - - if( (M.machine == src && M in view(1, src) ) || issilicon(M)) - winset(M, "tcscode", "is-disabled=true") - winset(M, "tcscode", "text=\"[showcode]\"") - else - viewingcode.Remove(M) - winshow(M, "Telecomms IDE", 0) // hide the window! - - sleep(5) - - if(length(viewingcode) > 0) - editingcode = pick(viewingcode) - viewingcode.Remove(editingcode) - update_ide() - - - - req_access = list(access_tcomsat) - - attack_hand(mob/user as mob) - if(stat & (BROKEN|NOPOWER)) - return - user.set_machine(src) - var/dat = "Telecommunication Traffic Control
Telecommunications Traffic Control
" - - switch(screen) - - - // --- Main Menu --- - - if(0) - dat += "
[temp]
" - dat += "
Current Network: [network]
" - if(servers.len) - dat += "
Detected Telecommunication Servers:" - dat += "
\[Flush Buffer\]" - - else - dat += "
No servers detected. Scan for servers: \[Scan\]" - - - // --- Viewing Server --- - - if(1) - dat += "
[temp]
" - dat += "
\[Main Menu\] \[Refresh\]
" - dat += "
Current Network: [network]" - dat += "
Selected Server: [SelectedServer.id]

" - dat += "
\[Edit Code\]" - dat += "
Signal Execution: " - if(SelectedServer.autoruncode) - dat += "ALWAYS" - else - dat += "NEVER" - - - user << browse(dat, "window=traffic_control;size=575x400") - onclose(user, "server_control") - - temp = "" - return - - - Topic(href, href_list) - if(..()) - return - - - add_fingerprint(usr) - usr.set_machine(src) - if(!src.allowed(usr) && !emagged) - usr << "\red ACCESS DENIED." - return - - if(href_list["viewserver"]) - screen = 1 + if(screen == 0) //main menu + dat += "
[temp]
" + dat += "
Current Network: [network]
" + if(servers.len) + dat += "
Detected Telecommunication Servers:" - if(href_list["operation"]) - switch(href_list["operation"]) + dat += "
\[Flush Buffer\]" - if("release") - servers = list() - screen = 0 + else + dat += "
No servers detected. Scan for servers: \[Scan\]" - if("mainmenu") - screen = 0 + if(screen == 1) //server menu + dat += "
[temp]
" + dat += "
\[Main Menu\] \[Refresh\]
" + dat += "
Current Network: [network]" + dat += "
Selected Server: [SelectedServer.id]

" + dat += "
\[Edit Code\]" + dat += "
Signal Execution: " + if(SelectedServer.autoruncode) + dat += "ALWAYS" + else + dat += "NEVER" + + if(screen == 2) //code editor + if(editingcode == user) + dat += {"
[temp]
+
+ \[Back\] + \[Main Menu\] + \[Refresh\] +
+ + + +
+ + + + + +
+ + +
+
+ +
+ [compiling_errors] +
+ "} + else + dat += {"
[temp]
+
\[Refresh\]
+
+ + +
+
+ [compiling_errors] +
+ "} //anything typed will be overridden anyways by the one who is editing the code + + var/datum/browser/popup = new(user, "traffic_control", "Telecommunication Traffic Control", 700, 500) + //codemirror + popup.add_script("codemirror-compressed", 'nano/js/codemirror-compressed.js') // A custom compressed JS file of codemirror, with CSS highlighting + popup.add_stylesheet("codemirror", 'nano/css/codemirror.css') // this CSS sheet is common to all UIs, so all UIs can use codemirror + popup.add_stylesheet("lesser-dark", 'nano/css/lesser-dark.css') //CSS styling for codemirror, dark theme + + popup.set_content(dat) + popup.open() + + temp = "" + + +/obj/machinery/computer/telecomms/traffic/Topic(href, href_list) + if(..()) + return 1 + + var/mob/user = usr + if(!istype(user) || !user.client) + return 0 + + if(user != editingcode) + return 0 + + var/code = href_list["cMirror"] + if(code) + storedcode = code + + add_fingerprint(user) + user.set_machine(src) + + if(!allowed(user) && !emagged) + user << "Access Denied." + return 0 + + switch(href_list["choice"]) + if("Compile") + if(!code) + return 0 + if(user != editingcode) + return 0 //only one editor + + if(SelectedServer) + var/obj/machinery/telecomms/server/Server = SelectedServer + Server.setcode(code) + + spawn(0) + // Output all the compile-time errors + compiling_errors = "Please wait, compiling..." + updateUsrDialog() + + var/list/compileerrors = Server.compile(user) // then compile the code! + if(!telecomms_check(user)) + return + + if(compileerrors.len) + compiling_errors = "Compile Errors
" + for(var/datum/scriptError/e in compileerrors) + compiling_errors += "\t>[e.message]
" + compiling_errors += "([compileerrors.len] errors)" - if("scan") - if(servers.len > 0) - temp = "- FAILED: CANNOT PROBE WHEN BUFFER FULL -" else - for(var/obj/machinery/telecomms/server/T in range(25, src)) - if(T.network == network) - servers.Add(T) + compiling_errors = "TCS compilation successful!
" + compiling_errors += "(0 errors)" - if(!servers.len) - temp = "- FAILED: UNABLE TO LOCATE SERVERS IN \[[network]\] -" - else - temp = "- [servers.len] SERVERS PROBED & BUFFERED -" + updateUsrDialog() - screen = 0 + if("Clear") + if(!telecomms_check(user) || user != editingcode) + return 0 - if("editcode") - if(editingcode == usr) return - if(usr in viewingcode) return + if(SelectedServer) + var/obj/machinery/telecomms/server/Server = SelectedServer + Server.memory = list() // clear the memory - if(!editingcode) - lasteditor = usr - editingcode = usr - winshow(editingcode, "Telecomms IDE", 1) // show the IDE - winset(editingcode, "tcscode", "is-disabled=false") - winset(editingcode, "tcscode", "text=\"\"") - var/showcode = replacetext(storedcode, "\\\"", "\\\\\"") - showcode = replacetext(storedcode, "\"", "\\\"") - winset(editingcode, "tcscode", "text=\"[showcode]\"") - spawn() - update_ide() + compiling_errors = "Server Memory Cleared!" + updateUsrDialog() - else - viewingcode.Add(usr) - winshow(usr, "Telecomms IDE", 1) // show the IDE - winset(usr, "tcscode", "is-disabled=true") - winset(editingcode, "tcscode", "text=\"\"") - var/showcode = replacetext(storedcode, "\"", "\\\"") - winset(usr, "tcscode", "text=\"[showcode]\"") + if(href_list["viewserver"]) + screen = 1 + for(var/obj/machinery/telecomms/T in servers) + if(T.id == href_list["viewserver"]) + SelectedServer = T + break - if("togglerun") - SelectedServer.autoruncode = !(SelectedServer.autoruncode) + if(href_list["operation"]) + switch(href_list["operation"]) - if(href_list["network"]) + if("release") + servers = list() + screen = 0 - var/newnet = input(usr, "Which network do you want to view?", "Comm Monitor", network) as null|text + if("mainmenu") + screen = 0 - if(newnet && canAccess(usr)) - if(length(newnet) > 15) - temp = "- FAILED: NETWORK TAG STRING TOO LENGHTLY -" + if("codeback") + if(SelectedServer) + screen = 1 + + if("scan") + if(servers.len > 0) + temp = "- FAILED: CANNOT PROBE WHEN BUFFER FULL -" else + for(var/obj/machinery/telecomms/server/T in range(25, src)) + if(T.network == network) + servers.Add(T) + + if(!servers.len) + temp = "- FAILED: UNABLE TO LOCATE SERVERS IN \[[network]\] -" + else + temp = "- [servers.len] SERVERS PROBED & BUFFERED -" - network = newnet screen = 0 - servers = list() - temp = "- NEW NETWORK TAG SET IN ADDRESS \[[network]\] -" - updateUsrDialog() - return + if("editcode") + screen = 2 + if("togglerun") + SelectedServer.autoruncode = !(SelectedServer.autoruncode) + + if(href_list["network"]) + + var/newnet = input(user, "Which network do you want to view?", "Comm Monitor", network) as null|text + + if(newnet && canAccess(user)) + if(length(newnet) > 15) + temp = "- FAILED: NETWORK TAG STRING TOO LENGHTLY -" + + else + + network = newnet + screen = 0 + servers = list() + temp = "- NEW NETWORK TAG SET IN ADDRESS \[[network]\] -" + + updateUsrDialog() /obj/machinery/computer/telecomms/traffic/attackby(var/obj/item/weapon/D as obj, var/mob/user as mob, params) if(istype(D, /obj/item/weapon/screwdriver)) @@ -245,3 +316,9 @@ if(issilicon(user) || in_range(user, src)) return 1 return 0 + +/obj/machinery/computer/telecomms/traffic/proc/telecomms_check(var/mob/mob) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/telecomms_check() called tick#: [world.time]") + if(mob && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && in_range(mob.machine, mob) || issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic)) + return 1 + return 0 \ No newline at end of file diff --git a/code/modules/client/client procs.dm b/code/modules/client/client procs.dm index 74ac0534b62..896fac535aa 100644 --- a/code/modules/client/client procs.dm +++ b/code/modules/client/client procs.dm @@ -1,6 +1,9 @@ //////////// //SECURITY// //////////// +//debugging, uncomment for viewing topic calls +// #define TOPIC_DEBUGGING 1 + #define TOPIC_SPAM_DELAY 2 //2 ticks is about 2/10ths of a second; it was 4 ticks, but that caused too many clicks to be lost due to lag #define UPLOAD_LIMIT 10485760 //Restricts client uploads to the server to 10MB //Boosted this thing. What's the worst that can happen? #define MIN_CLIENT_VERSION 0 //Just an ambiguously low version for now, I don't want to suddenly stop people playing. @@ -24,6 +27,11 @@ if(!usr || usr != mob) //stops us calling Topic for somebody else's client. Also helps prevent usr=null return + #if defined(TOPIC_DEBUGGING) + world << "[src]'s Topic: [href] destined for [hsrc]." + #endif + + //Reduces spamming of links by dropping calls that happen during the delay period if(next_allowed_topic_time > world.time) return @@ -282,20 +290,20 @@ winset(src, null, "command=\".configure graphics-hwmode on\"") log_client_to_db() - + if (ckey in clientmessages) for (var/message in clientmessages[ckey]) src << message clientmessages.Remove(ckey) if (config && config.autoconvert_notes) - convert_notes_sql(ckey) - + convert_notes_sql(ckey) + send_resources() - + if(!void) void = new() - + screen += void ////////////// diff --git a/code/modules/nano/nanoui.dm b/code/modules/nano/nanoui.dm index 150f45e9518..4ec2f48fed8 100644 --- a/code/modules/nano/nanoui.dm +++ b/code/modules/nano/nanoui.dm @@ -113,6 +113,11 @@ nanoui is used to open and update nano browser uis add_stylesheet("shared.css") // this CSS sheet is common to all UIs add_stylesheet("icons.css") // this CSS sheet is common to all UIs + //codemirror + add_script("codemirror-compressed.js") // A custom compressed JS file of codemirror, with CSS highlighting + add_stylesheet("codemirror.css") // this CSS sheet is common to all UIs, so all UIs can use codemirror + add_stylesheet("lesser-dark.css") //CSS styling for codemirror, dark theme + /** * Set the current status (also known as visibility) of this ui. * diff --git a/code/modules/scripting/AST/AST Nodes.dm b/code/modules/scripting/AST/AST Nodes.dm index 6853697ebf9..c8bb3ba9f78 100644 --- a/code/modules/scripting/AST/AST Nodes.dm +++ b/code/modules/scripting/AST/AST Nodes.dm @@ -12,128 +12,118 @@ Articles: - */ -var - const /* Constants: Operator Precedence OOP_OR - Logical or OOP_AND - Logical and OOP_BIT - Bitwise operations OOP_EQUAL - Equality checks - OOP_COMPARE - Greater than, less then, etc + OOP_COMPARE - Greater than, less then, etc OOP_ADD - Addition and subtraction - OOP_MULTIPLY - Multiplication and division + OOP_MULTIPLY - Multiplication and division OOP_POW - Exponents OOP_UNARY - Unary Operators OOP_GROUP - Parentheses */ - OOP_OR = 1 //|| - OOP_AND = OOP_OR + 1 //&& - OOP_BIT = OOP_AND + 1 //&, | - OOP_EQUAL = OOP_BIT + 1 //==, != - OOP_COMPARE = OOP_EQUAL + 1 //>, <, >=, <= - OOP_ADD = OOP_COMPARE + 1 //+, - - OOP_MULTIPLY= OOP_ADD + 1 //*, /, % - OOP_POW = OOP_MULTIPLY+ 1 //^ - OOP_UNARY = OOP_POW + 1 //! - OOP_GROUP = OOP_UNARY + 1 //() +/var/const/OOP_OR = 1 //|| +/var/const/OOP_AND = OOP_OR + 1 //&& +/var/const/OOP_BIT = OOP_AND + 1 //&, | +/var/const/OOP_EQUAL = OOP_BIT + 1 //==, != +/var/const/OOP_COMPARE = OOP_EQUAL + 1 //>, <, >=, <= +/var/const/OOP_ADD = OOP_COMPARE + 1 //+, - +/var/const/OOP_MULTIPLY= OOP_ADD + 1 //*, /, % +/var/const/OOP_POW = OOP_MULTIPLY + 1 //^ +/var/const/OOP_UNARY = OOP_POW + 1 //! +/var/const/OOP_GROUP = OOP_UNARY + 1 //() /* Class: node */ -/node - proc - ToString() - return "[src.type]" +/datum/node/proc/ToString() + return "[src.type]" /* Class: identifier */ -/node/identifier - var - id_name +/datum/node/identifier + var/id_name - New(id) - .=..() - src.id_name=id +/datum/node/identifier/New(id) + . = ..() + src.id_name = id - ToString() - return id_name +/datum/node/identifier/ToString() + return id_name /* Class: expression */ -/node/expression +/datum/node/expression /* Class: operator See and for subtypes. */ -/node/expression/operator - var - node/expression/exp - tmp - name - precedence +/datum/node/expression/operator + var/datum/node/expression/exp + var/token = "" // Used when giving type mismatches. + var/tmp/name + var/tmp/precedence - New() - .=..() - if(!src.name) src.name="[src.type]" +/datum/node/expression/operator/New() + .=..() + if(!src.name) + src.name = "[src.type]" - ToString() - return "operator: [name]" +/datum/node/expression/operator/ToString() + return "operator: [name]" /* Class: FunctionCall */ -/node/expression/FunctionCall +/datum/node/expression/FunctionCall //Function calls can also be expressions or statements. - var - func_name - node/identifier/object - list/parameters=new + var/func_name + var/datum/node/identifier/object + var/list/parameters = list() /* Class: literal */ -/node/expression/value/literal - var - value +/datum/node/expression/value/literal + var/value - New(value) - .=..() - src.value=value +/datum/node/expression/value/literal/New(value) + . = ..() + src.value = value - ToString() - return src.value +/datum/node/expression/value/literal/ToString() + return src.value /* Class: variable */ -/node/expression/value/variable - var - node - object //Either a node/identifier or another node/expression/value/variable which points to the object - node/identifier - id +/datum/node/expression/value/variable + var/datum/node/object //Either a node/identifier or another node/expression/value/variable which points to the object + var/datum/node/identifier/id - New(ident) - .=..() - id=ident - if(istext(id))id=new(id) +/datum/node/expression/value/variable/New(ident) + . = ..() + id = ident + if(istext(id)) + id = new(id) - ToString() - return src.id.ToString() +/datum/node/expression/value/variable/ToString() + return src.id.ToString() /* Class: reference */ -/node/expression/value/reference - var - datum/value +/datum/node/expression/value/reference + var/datum/value - New(value) - .=..() - src.value=value +/datum/node/expression/value/reference/New(value) + . = ..() + src.value = value - ToString() - return "ref: [src.value] ([src.value.type])" \ No newline at end of file +/datum/node/expression/value/reference/ToString() + return "ref: [src.value] ([src.value.type])" \ No newline at end of file diff --git a/code/modules/scripting/AST/Blocks.dm b/code/modules/scripting/AST/Blocks.dm index 18f408f1f1b..331e49c16fe 100644 --- a/code/modules/scripting/AST/Blocks.dm +++ b/code/modules/scripting/AST/Blocks.dm @@ -8,13 +8,11 @@ it is possible to have a function definition inside of any type of block (such as in an if statement or another function), and not just in the global scope as in many languages. */ -/node/BlockDefinition - var/list - statements = new - functions = new - initial_variables = new +/datum/node/BlockDefinition + var/list/statements = new + var/list/functions = new + var/list/initial_variables = new - proc /* Proc: SetVar Defines a permanent variable. The variable will not be deleted when it goes out of scope. @@ -26,8 +24,8 @@ See Also: - */ - SetVar(name, value) - initial_variables[name]=value +/datum/node/BlockDefinition/proc/SetVar(name, value) + initial_variables[name] = value /* @@ -35,14 +33,13 @@ A block object representing the global scope. */ // - GlobalBlock - New() - initial_variables["null"]=null - return ..() +/datum/node/BlockDefinition/GlobalBlock/New() + initial_variables["null"] = null + return ..() /* Class: FunctionBlock A block representing a function body. */ // - FunctionBlock \ No newline at end of file +/datum/node/BlockDefinition/FunctionBlock \ No newline at end of file diff --git a/code/modules/scripting/AST/Operators/Binary Operators.dm b/code/modules/scripting/AST/Operators/Binary Operators.dm index 8df19879cf1..ccbccc53323 100644 --- a/code/modules/scripting/AST/Operators/Binary Operators.dm +++ b/code/modules/scripting/AST/Operators/Binary Operators.dm @@ -7,8 +7,8 @@ Class: binary Represents a binary operator in the AST. A binary operator takes two operands (ie x and y) and returns a value. */ -/node/expression/operator/binary - var/node/expression/exp2 +/datum/node/expression/operator/binary + var/datum/node/expression/exp2 ////////// Comparison Operators ////////// /* @@ -16,159 +16,176 @@ Returns true if x = y. */ // - Equal - precedence=OOP_EQUAL +/datum/node/expression/operator/binary/Equal + token = "==" + precedence = OOP_EQUAL /* - Class: NotEqual - Returns true if x and y aren't equal. +Class: NotEqual +Returns true if x and y aren't equal. */ // - NotEqual - precedence=OOP_EQUAL +/datum/node/expression/operator/binary/NotEqual + token = "!=" + precedence = OOP_EQUAL /* - Class: Greater - Returns true if x > y. +Class: Greater +Returns true if x > y. */ // - Greater - precedence=OOP_COMPARE +/datum/node/expression/operator/binary/Greater + token = ">" + precedence = OOP_COMPARE /* - Class: Less - Returns true if x < y. +Class: Less +Returns true if x < y. */ // - Less - precedence=OOP_COMPARE +/datum/node/expression/operator/binary/Less + token = "<" + precedence = OOP_COMPARE /* - Class: GreaterOrEqual - Returns true if x >= y. +Class: GreaterOrEqual +Returns true if x >= y. */ // - GreaterOrEqual - precedence=OOP_COMPARE +/datum/node/expression/operator/binary/GreaterOrEqual + token = ">=" + precedence = OOP_COMPARE /* - Class: LessOrEqual - Returns true if x <= y. +Class: LessOrEqual +Returns true if x <= y. */ // - LessOrEqual - precedence=OOP_COMPARE +/datum/node/expression/operator/binary/LessOrEqual + token = "<=" + precedence = OOP_COMPARE ////////// Logical Operators ////////// /* - Class: LogicalAnd - Returns true if x and y are true. +Class: LogicalAnd +Returns true if x and y are true. */ // - LogicalAnd - precedence=OOP_AND +/datum/node/expression/operator/binary/LogicalAnd + token = "&&" + precedence = OOP_AND /* - Class: LogicalOr - Returns true if x, y, or both are true. +Class: LogicalOr +Returns true if x, y, or both are true. */ // - LogicalOr - precedence=OOP_OR +/datum/node/expression/operator/binary/LogicalOr + token = "||" + precedence = OOP_OR /* - Class: LogicalXor - Returns true if either x or y but not both are true. +Class: LogicalXor +Returns true if either x or y but not both are true. */ // - LogicalXor //Not implemented in nS - precedence=OOP_OR +/datum/node/expression/operator/binary/LogicalXor //Not implemented in nS + precedence = OOP_OR ////////// Bitwise Operators ////////// /* - Class: BitwiseAnd - Performs a bitwise and operation. +Class: BitwiseAnd +Performs a bitwise and operation. - Example: - 011 & 110 = 010 +Example: +011 & 110 = 010 */ // - BitwiseAnd - precedence=OOP_BIT +/datum/node/expression/operator/binary/BitwiseAnd + token = "&" + precedence = OOP_BIT /* - Class: BitwiseOr - Performs a bitwise or operation. +Class: BitwiseOr +Performs a bitwise or operation. - Example: - 011 | 110 = 111 +Example: +011 | 110 = 111 */ // - BitwiseOr - precedence=OOP_BIT +/datum/node/expression/operator/binary/BitwiseOr + token = "|" + precedence = OOP_BIT /* - Class: BitwiseXor - Performs a bitwise exclusive or operation. +Class: BitwiseXor +Performs a bitwise exclusive or operation. - Example: - 011 xor 110 = 101 +Example: +011 xor 110 = 101 */ // - BitwiseXor - precedence=OOP_BIT +/datum/node/expression/operator/binary/BitwiseXor + token = "`" + precedence = OOP_BIT ////////// Arithmetic Operators ////////// /* - Class: Add - Returns the sum of x and y. +Class: Add +Returns the sum of x and y. */ // - Add - precedence=OOP_ADD +/datum/node/expression/operator/binary/Add + token = "+" + precedence = OOP_ADD /* - Class: Subtract - Returns the difference of x and y. +Class: Subtract +Returns the difference of x and y. */ // - Subtract - precedence=OOP_ADD +/datum/node/expression/operator/binary/Subtract + token = "-" + precedence = OOP_ADD /* - Class: Multiply - Returns the product of x and y. +Class: Multiply +Returns the product of x and y. */ // - Multiply - precedence=OOP_MULTIPLY +/datum/node/expression/operator/binary/Multiply + token = "*" + precedence = OOP_MULTIPLY /* - Class: Divide - Returns the quotient of x and y. +Class: Divide +Returns the quotient of x and y. */ // - Divide - precedence=OOP_MULTIPLY +/datum/node/expression/operator/binary/Divide + token = "/" + precedence = OOP_MULTIPLY /* - Class: Power - Returns x raised to the power of y. +Class: Power +Returns x raised to the power of y. */ // - Power - precedence=OOP_POW +/datum/node/expression/operator/binary/Power + token = "^" + precedence = OOP_POW /* - Class: Modulo - Returns the remainder of x / y. +Class: Modulo +Returns the remainder of x / y. */ // - Modulo - precedence=OOP_MULTIPLY +/datum/node/expression/operator/binary/Modulo + token = "%" + precedence = OOP_MULTIPLY diff --git a/code/modules/scripting/AST/Operators/Unary Operators.dm b/code/modules/scripting/AST/Operators/Unary Operators.dm index 3a5f3ffb963..e7cd4b8489a 100644 --- a/code/modules/scripting/AST/Operators/Unary Operators.dm +++ b/code/modules/scripting/AST/Operators/Unary Operators.dm @@ -5,8 +5,8 @@ Class: unary Represents a unary operator in the AST. Unary operators take a single operand (referred to as x below) and return a value. */ -/node/expression/operator/unary - precedence=OOP_UNARY +/datum/node/expression/operator/unary + precedence = OOP_UNARY /* Class: LogicalNot @@ -16,8 +16,8 @@ !true = false and !false = true */ // - LogicalNot - name="logical not" +/datum/node/expression/operator/unary/LogicalNot + name = "logical not" /* Class: BitwiseNot @@ -27,25 +27,25 @@ ~10 (decimal 2) = 01 (decimal 1). */ // - BitwiseNot - name="bitwise not" +/datum/node/expression/operator/unary/BitwiseNot + name = "bitwise not" /* Class: Minus Returns -x. */ // - Minus - name="minus" +/datum/node/expression/operator/unary/Minus + name = "minus" /* Class: group A special unary operator representing a value in parentheses. */ // - group - precedence=OOP_GROUP +/datum/node/expression/operator/unary/group + precedence = OOP_GROUP - New(node/expression/exp) - src.exp=exp - return ..() +/datum/node/expression/operator/unary/New(var/datum/node/expression/exp) + src.exp = exp + return ..() diff --git a/code/modules/scripting/AST/Statements.dm b/code/modules/scripting/AST/Statements.dm index e60fcb389c5..bae9f3de68c 100644 --- a/code/modules/scripting/AST/Statements.dm +++ b/code/modules/scripting/AST/Statements.dm @@ -5,118 +5,106 @@ Class: statement An object representing a single instruction run by an interpreter. */ -/node/statement +/datum/node/statement /* Class: FunctionCall Represents a call to a function. */ // - FunctionCall - var - func_name - node/identifier/object - list/parameters=new +/datum/node/statement/FunctionCall + var/func_name + var/datum/node/identifier/object + var/list/parameters = new /* - Class: FunctionDefinition - Defines a function. +Class: FunctionDefinition +Defines a function. */ // - FunctionDefinition - var - func_name - list/parameters=new - node/BlockDefinition/FunctionBlock/block +/datum/node/statement/FunctionDefinition + var/func_name + var/list/parameters = new + var/datum/node/BlockDefinition/FunctionBlock/block /* - Class: VariableAssignment - Sets a variable in an accessible scope to the given value if one exists, otherwise initializes a new local variable to the given value. +Class: VariableAssignment +Sets a variable in an accessible scope to the given value if one exists, otherwise initializes a new local variable to the given value. - Notes: - If a variable with the same name exists in a higher block, the value will be assigned to it. If not, - a new variable is created in the current block. To force creation of a new variable, use . +Notes: +If a variable with the same name exists in a higher block, the value will be assigned to it. If not, +a new variable is created in the current block. To force creation of a new variable, use . - See Also: - - +See Also: +- */ // - VariableAssignment - var - node - identifier - object - var_name - expression/value +/datum/node/statement/VariableAssignment + var/datum/node/identifier/object + var/datum/node/identifier/var_name + var/datum/node/expression/value /* - Class: VariableDeclaration - Intializes a local variable to a null value. +Class: VariableDeclaration +Intializes a local variable to a null value. - See Also: - - +See Also: +- */ // - VariableDeclaration - var - node - identifier - object - var_name +/datum/node/statement/VariableDeclaration + var/datum/node/identifier/object + var/datum/node/identifier/var_name /* - Class: IfStatement +Class: IfStatement */ // - IfStatement - var - node - BlockDefinition - block - else_block //may be null - expression/cond +/datum/node/statement/IfStatement + var/skip = 0 + var/datum/node/BlockDefinition/block + var/datum/node/BlockDefinition/else_block //may be null + var/datum/node/expression/cond + var/datum/node/statement/else_if + +/datum/node/statement/IfStatement/ElseIf /* - Class: WhileLoop - Loops while a given condition is true. +Class: WhileLoop +Loops while a given condition is true. */ // - WhileLoop - var - node - BlockDefinition/block - expression/cond +/datum/node/statement/WhileLoop + var/datum/node/BlockDefinition/block + var/datum/node/expression/cond /* - Class: ForLoop - Loops while test is true, initializing a variable, increasing the variable +Class: ForLoop +Loops while test is true, initializing a variable, increasing the variable */ - ForLoop - var - node - BlockDefinition/block - expression/test - expression/init - expression/increment +/datum/node/statement/ForLoop + var/datum/node/BlockDefinition/block + var/datum/node/expression/test + var/datum/node/expression/init + var/datum/node/expression/increment /* - Class: BreakStatement - Ends a loop. +Class: BreakStatement +Ends a loop. */ // - BreakStatement +/datum/node/statement/BreakStatement /* - Class: ContinueStatement - Skips to the next iteration of a loop. +Class: ContinueStatement +Skips to the next iteration of a loop. */ // - ContinueStatement +/datum/node/statement/ContinueStatement /* - Class: ReturnStatement - Ends the function and returns a value. +Class: ReturnStatement +Ends the function and returns a value. */ // - ReturnStatement - var - node/expression/value \ No newline at end of file +/datum/node/statement/ReturnStatement + var/datum/node/expression/value \ No newline at end of file diff --git a/code/modules/scripting/Errors.dm b/code/modules/scripting/Errors.dm index 5b722d007c5..63538c3f18f 100644 --- a/code/modules/scripting/Errors.dm +++ b/code/modules/scripting/Errors.dm @@ -5,128 +5,165 @@ Class: scriptError An error scanning or parsing the source code. */ -/scriptError - var +/datum/scriptError /* Var: message A message describing the problem. */ - message - New(msg=null) - if(msg)message=msg + var/message - BadToken - message="Unexpected token: " - var/token/token - New(token/t) - token=t - if(t&&t.line) message="[t.line]: [message]" - if(istype(t))message+="[t.value]" - else message+="[t]" +/datum/scriptError/New(msg = null) + if(msg)message = msg - InvalidID - parent_type=/scriptError/BadToken - message="Invalid identifier name: " +/datum/scriptError/BadToken + message = "Unexpected token: " + var/datum/token/token - ReservedWord - parent_type=/scriptError/BadToken - message="Identifer using reserved word: " +/datum/scriptError/BadToken/New(datum/token/t) + token = t + if(t && t.line) + message = "[t.line]: [message]" - BadNumber - parent_type=/scriptError/BadToken - message = "Bad number: " + if(istype(t)) + message += "[t.value]" - BadReturn - var/token/token - message = "Unexpected return statement outside of a function." - New(token/t) - src.token=t + else + message += "[t]" - EndOfFile - message = "Unexpected end of file." +/datum/scriptError/InvalidID + parent_type = /datum/scriptError/BadToken + message = "Invalid identifier name: " - ExpectedToken - message="Expected: '" - New(id, token/T) - if(T && T.line) message="[T.line]: [message]" - message+="[id]'. " - if(T)message+="Found '[T.value]'." +/datum/scriptError/ReservedWord + parent_type = /datum/scriptError/BadToken + message = "Identifer using reserved word: " + +/datum/scriptError/BadNumber + parent_type = /datum/scriptError/BadToken + message = "Bad number: " + +/datum/scriptError/BadReturn + var/datum/token/token + message = "Unexpected return statement outside of a function." + +/datum/scriptError/BadReturn/New(datum/token/t) + src.token = t + +/datum/scriptError/EndOfFile + message = "Unexpected end of file." + +/datum/scriptError/ExpectedToken + message = "Expected: '" + +/datum/scriptError/ExpectedToken/New(id, datum/token/T) + if(T && T.line) + message = "[T.line]: [message]" + + message += "[id]'. " + + if(T) + message += "Found '[T.value]'." - UnterminatedComment - message="Unterminated multi-line comment statement: expected */" +/datum/scriptError/UnterminatedComment + message = "Unterminated multi-line comment statement: expected */" - DuplicateFunction - New(name, token/t) - message="Function '[name]' defined twice." +/datum/scriptError/DuplicateFunction/New(name, datum/token/t) + message = "Function '[name]' defined twice." + +/datum/scriptError/ParameterFunction + message = "You cannot use a function inside a parameter." + +/datum/scriptError/ParameterFunction/New(datum/token/t) + var/line = "?" + if(t) + line = t.line + message = "[line]: [message]" /* Class: runtimeError An error thrown by the interpreter in running the script. */ -/runtimeError - var - name +/datum/runtimeError + var/name /* Var: message A basic description as to what went wrong. */ - message - stack/stack - - proc + var/message + var/datum/stack/stack /* Proc: ToString Returns a description of the error suitable for showing to the user. */ - ToString() - . = "[name]: [message]" - if(!stack.Top()) return - .+="\nStack:" - while(stack.Top()) - var/node/statement/FunctionCall/stmt=stack.Pop() - . += "\n\t [stmt.func_name]()" +/datum/runtimeError/proc/ToString() + . = "[name]: [message]" + if(!stack.Top()) + return - TypeMismatch - name="TypeMismatchError" - New(op, a, b) - message="Type mismatch: '[a]' [op] '[b]'" + . += "\nStack:" + while(stack.Top()) + var/datum/node/statement/FunctionCall/stmt = stack.Pop() + . += "\n\t [stmt.func_name]()" - UnexpectedReturn - name="UnexpectedReturnError" - message="Unexpected return statement." +/datum/runtimeError/TypeMismatch + name = "TypeMismatchError" - UnknownInstruction - name="UnknownInstructionError" - message="Unknown instruction type. This may be due to incompatible compiler and interpreter versions or a lack of implementation." +/datum/runtimeError/TypeMismatch/New(op, a, b) + message = "Type mismatch: '[a]' [op] '[b]'" - UndefinedVariable - name="UndefinedVariableError" - New(variable) - message="Variable '[variable]' has not been declared." +/datum/runtimeError/TypeMismatch/unary/New(op, a) + message = "Type mismatch: [op]'[a]'" - UndefinedFunction - name="UndefinedFunctionError" - New(function) - message="Function '[function]()' has not been defined." +/datum/runtimeError/TypeMismatch/New(op, a, b) + message = "Type mismatch: '[a]' [op] '[b]'" - DuplicateVariableDeclaration - name="DuplicateVariableError" - New(variable) - message="Variable '[variable]' was already declared." +/datum/runtimeError/UnexpectedReturn + name = "UnexpectedReturnError" + message = "Unexpected return statement." - IterationLimitReached - name="MaxIterationError" - message="A loop has reached its maximum number of iterations." +/datum/runtimeError/UnknownInstruction + name = "UnknownInstructionError" + message = "Unknown instruction type. This may be due to incompatible compiler and interpreter versions or a lack of implementation." - RecursionLimitReached - name="MaxRecursionError" - message="The maximum amount of recursion has been reached." +/datum/runtimeError/UndefinedVariable + name = "UndefinedVariableError" - DivisionByZero - name="DivideByZeroError" - message="Division by zero attempted." +/datum/runtimeError/UndefinedVariable/New(variable) + message = "Variable '[variable]' has not been declared." - MaxCPU - name="MaxComputationalUse" - message="Maximum amount of computational cycles reached (>= 1000)." \ No newline at end of file +/datum/runtimeError/UndefinedFunction + name = "UndefinedFunctionError" + +/datum/runtimeError/UndefinedFunction/New(function) + message = "Function '[function]()' has not been defined." + +/datum/runtimeError/DuplicateVariableDeclaration + name = "DuplicateVariableError" + +/datum/runtimeError/DuplicateVariableDeclaration/New(variable) + message="Variable '[variable]' was already declared." + +/datum/runtimeError/IterationLimitReached + name = "MaxIterationError" + message = "A loop has reached its maximum number of iterations." + +/datum/runtimeError/RecursionLimitReached + name = "MaxRecursionError" + message = "The maximum amount of recursion has been reached." + +/datum/runtimeError/DivisionByZero + name = "DivideByZeroError" + message = "Division by zero attempted." + +/datum/runtimeError/MaxCPU + name = "MaxComputationalUse" + message = "Maximum amount of computational cycles reached (>= 1000)." + +/datum/runtimeError/VectorLimit + name = "VectorSizeOverflow" + message = "Maximum vector size reached" + +/datum/runtimeError/StringLimit + name = "StringSizeOverflow" + message = "Maximum string size reached" diff --git a/code/modules/scripting/IDE.dm b/code/modules/scripting/IDE.dm index 1733895a91f..6fbe19ba918 100644 --- a/code/modules/scripting/IDE.dm +++ b/code/modules/scripting/IDE.dm @@ -1,16 +1,15 @@ -client/verb/tcssave() +/client/verb/tcssave() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/tcssave() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || issilicon(mob)) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode != mob) return if(Machine.SelectedServer) var/obj/machinery/telecomms/server/Server = Machine.SelectedServer - var/tcscode=winget(src, "tcscode", "text") - var/msg="[mob.name] is adding script to server [Server]: [tcscode]" - diary << msg + var/tcscode = winget(src, "tcscode", "text") Server.setcode( tcscode ) // this actually saves the code from input to the server src << output(null, "tcserror") // clear the errors else @@ -24,10 +23,11 @@ client/verb/tcssave() src << output("Failed to save: Unable to locate machine. (Back up your code before exiting the window!)", "tcserror") -client/verb/tcscompile() +/client/verb/tcscompile() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/tcscompile() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || (issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) )) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode != mob) return @@ -35,35 +35,40 @@ client/verb/tcscompile() if(Machine.SelectedServer) var/obj/machinery/telecomms/server/Server = Machine.SelectedServer Server.setcode( winget(src, "tcscode", "text") ) // save code first - var/list/compileerrors = Server.compile(usr) // then compile the code! - // Output all the compile-time errors - src << output(null, "tcserror") + spawn(0) + // Output all the compile-time errors + src << output(null, "tcserror") + src << output("Please wait, compiling...", "tcserror") - if(compileerrors.len) - src << output("Compile Errors", "tcserror") - for(var/scriptError/e in compileerrors) - src << output("\t>[e.message]", "tcserror") - src << output("([compileerrors.len] errors)", "tcserror") + var/list/compileerrors = Server.compile(mob) // then compile the code! + if(!telecomms_check(mob)) + return - // Output compile errors to all other people viewing the code too - for(var/mob/M in Machine.viewingcode) - if(M.client) - M << output(null, "tcserror") - M << output("Compile Errors", "tcserror") - for(var/scriptError/e in compileerrors) - M << output("\t>[e.message]", "tcserror") - M << output("([compileerrors.len] errors)", "tcserror") + if(compileerrors.len) + src << output("Compile Errors", "tcserror") + for(var/datum/scriptError/e in compileerrors) + src << output("\t>[e.message]", "tcserror") + src << output("([compileerrors.len] errors)", "tcserror") + + // Output compile errors to all other people viewing the code too + for(var/mob/M in Machine.viewingcode) + if(M.client) + M << output(null, "tcserror") + M << output("Compile Errors", "tcserror") + for(var/datum/scriptError/e in compileerrors) + M << output("\t>[e.message]", "tcserror") + M << output("([compileerrors.len] errors)", "tcserror") - else - src << output("TCS compilation successful!", "tcserror") - src << output("(0 errors)", "tcserror") + else + src << output("TCS compilation successful!", "tcserror") + src << output("(0 errors)", "tcserror") - for(var/mob/M in Machine.viewingcode) - if(M.client) - M << output("TCS compilation successful!", "tcserror") - M << output("(0 errors)", "tcserror") + for(var/mob/M in Machine.viewingcode) + if(M.client) + M << output("TCS compilation successful!", "tcserror") + M << output("(0 errors)", "tcserror") else src << output(null, "tcserror") @@ -75,59 +80,30 @@ client/verb/tcscompile() src << output(null, "tcserror") src << output("Failed to compile: Unable to locate machine. (Back up your code before exiting the window!)", "tcserror") -client/verb/tcsrun() +/client/verb/tcsrun() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/tcsrun() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || (issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) )) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode != mob) return if(Machine.SelectedServer) var/obj/machinery/telecomms/server/Server = Machine.SelectedServer - Server.setcode( winget(src, "tcscode", "text") ) // save code first - var/list/compileerrors = Server.compile() // then compile the code! - - // Output all the compile-time errors - src << output(null, "tcserror") - - if(compileerrors.len) - src << output("Compile Errors", "tcserror") - for(var/scriptError/e in compileerrors) - src << output("\t>[e.message]", "tcserror") - src << output("([compileerrors.len] errors)", "tcserror") - - // Output compile errors to all other people viewing the code too - for(var/mob/M in Machine.viewingcode) - if(M.client) - M << output(null, "tcserror") - M << output("Compile Errors", "tcserror") - for(var/scriptError/e in compileerrors) - M << output("\t>[e.message]", "tcserror") - M << output("([compileerrors.len] errors)", "tcserror") + var/datum/signal/signal = new + signal.data["message"] = "" + if(Server.freq_listening.len > 0) + signal.frequency = Server.freq_listening[1] else - // Finally, we run the code! - src << output("TCS compilation successful! Code executed.", "tcserror") - src << output("(0 errors)", "tcserror") + signal.frequency = 1459 + signal.data["name"] = "" + signal.data["job"] = "" + signal.data["reject"] = 0 + signal.data["server"] = Server - for(var/mob/M in Machine.viewingcode) - if(M.client) - M << output("TCS compilation successful!", "tcserror") - M << output("(0 errors)", "tcserror") - - var/datum/signal/signal = new() - signal.data["message"] = "" - if(Server.freq_listening.len > 0) - signal.frequency = Server.freq_listening[1] - else - signal.frequency = 1459 - signal.data["name"] = "" - signal.data["job"] = "" - signal.data["reject"] = 0 - signal.data["server"] = Server - - Server.Compiler.Run(signal) + Server.Compiler.Run(signal) else @@ -141,10 +117,11 @@ client/verb/tcsrun() src << output("Failed to run: Unable to locate machine. (Back up your code before exiting the window!)", "tcserror") -client/verb/exittcs() +/client/verb/exittcs() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/exittcs() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || (issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) )) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode == mob) Machine.storedcode = "[winget(mob, "tcscode", "text")]" @@ -153,10 +130,11 @@ client/verb/exittcs() if(mob in Machine.viewingcode) Machine.viewingcode.Remove(mob) -client/verb/tcsrevert() +/client/verb/tcsrevert() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/tcsrevert() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || (issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) )) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode != mob) return @@ -182,10 +160,11 @@ client/verb/tcsrevert() src << output("Failed to revert: Unable to locate machine.", "tcserror") -client/verb/tcsclearmem() +/client/verb/tcsclearmem() set hidden = 1 + //writepanic("[__FILE__].[__LINE__] ([src.type])([usr ? usr.ckey : ""]) \\client/verb/tcsclearmem() called tick#: [world.time]") if(mob.machine || issilicon(mob)) - if((istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && mob.machine in view(1, mob)) || (issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) )) + if(telecomms_check(mob)) var/obj/machinery/computer/telecomms/traffic/Machine = mob.machine if(Machine.editingcode != mob) return @@ -207,4 +186,10 @@ client/verb/tcsclearmem() src << output("Failed to clear memory: Unable to locate machine.", "tcserror") else src << output(null, "tcserror") - src << output("Failed to clear memory: Unable to locate machine.", "tcserror") \ No newline at end of file + src << output("Failed to clear memory: Unable to locate machine.", "tcserror") + +/proc/telecomms_check(var/mob/mob) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/telecomms_check() called tick#: [world.time]") + if(mob && istype(mob.machine, /obj/machinery/computer/telecomms/traffic) && in_range(mob.machine, mob) || issilicon(mob) && istype(mob.machine, /obj/machinery/computer/telecomms/traffic)) + return 1 + return 0 \ No newline at end of file diff --git a/code/modules/scripting/Implementations/Telecomms.dm b/code/modules/scripting/Implementations/Telecomms.dm index 1b23a6effae..eadc1d398c4 100644 --- a/code/modules/scripting/Implementations/Telecomms.dm +++ b/code/modules/scripting/Implementations/Telecomms.dm @@ -4,253 +4,312 @@ /* --- Traffic Control Scripting Language --- */ // Nanotrasen TCS Language - Made by Doohl -/n_Interpreter/TCS_Interpreter +/datum/n_Interpreter/TCS_Interpreter var/datum/TCS_Compiler/Compiler - HandleError(runtimeError/e) - Compiler.Holder.add_entry(e.ToString(), "Execution Error") +/datum/n_Interpreter/TCS_Interpreter/HandleError(datum/runtimeError/e) + Compiler.Holder.add_entry(e.ToString(), "Execution Error") + +/datum/n_Interpreter/TCS_Interpreter/GC() + ..() + Compiler = null /datum/TCS_Compiler - var/n_Interpreter/TCS_Interpreter/interpreter + var/datum/n_Interpreter/TCS_Interpreter/interpreter var/obj/machinery/telecomms/server/Holder // the server that is running the code var/ready = 1 // 1 if ready to run code + /* -- Set ourselves to Garbage Collect -- */ + +/datum/TCS_Compiler/proc/GC() + Holder = null + if(interpreter) + interpreter.GC() + + /* -- Compile a raw block of text -- */ - proc/Compile(code as message) - var/n_scriptOptions/nS_Options/options = new() - var/n_Scanner/nS_Scanner/scanner = new(code, options) - var/list/tokens = scanner.Scan() - var/n_Parser/nS_Parser/parser = new(tokens, options) - var/node/BlockDefinition/GlobalBlock/program = parser.Parse() +/datum/TCS_Compiler/proc/Compile(code as message) + var/datum/n_scriptOptions/nS_Options/options = new() + var/datum/n_Scanner/nS_Scanner/scanner = new(code, options) + var/list/tokens = scanner.Scan() + var/datum/n_Parser/nS_Parser/parser = new(tokens, options) + var/datum/node/BlockDefinition/GlobalBlock/program = parser.Parse() - var/list/returnerrors = list() + var/list/returnerrors = list() - returnerrors += scanner.errors - returnerrors += parser.errors - - if(returnerrors.len) - return returnerrors - - interpreter = new(program) - interpreter.persist = 1 - interpreter.Compiler= src + returnerrors += scanner.errors + returnerrors += parser.errors + if(returnerrors.len) return returnerrors - /* -- Execute the compiled code -- */ + interpreter = new(program) + interpreter.persist = 1 + interpreter.Compiler= src - proc/Run(var/datum/signal/signal) + return returnerrors - if(!ready) - return +/* -- Execute the compiled code -- */ - if(!interpreter) - return +/datum/TCS_Compiler/proc/Run(var/datum/signal/signal) + if(!ready) + return - interpreter.container = src + if(!interpreter) + return - interpreter.SetVar("PI" , 3.141592653) // value of pi - interpreter.SetVar("E" , 2.718281828) // value of e - interpreter.SetVar("SQURT2" , 1.414213562) // value of the square root of 2 - interpreter.SetVar("FALSE" , 0) // boolean shortcut to 0 - interpreter.SetVar("TRUE" , 1) // boolean shortcut to 1 + interpreter.container = src - interpreter.SetVar("NORTH" , NORTH) // NORTH (1) - interpreter.SetVar("SOUTH" , SOUTH) // SOUTH (2) - interpreter.SetVar("EAST" , EAST) // EAST (4) - interpreter.SetVar("WEST" , WEST) // WEST (8) + interpreter.SetVar("PI", 3.141592653) // value of pi + interpreter.SetVar("E", 2.718281828) // value of e + interpreter.SetVar("SQURT2", 1.414213562) // value of the square root of 2 + interpreter.SetVar("FALSE", 0) // boolean shortcut to 0 + interpreter.SetVar("false", 0) // boolean shortcut to 0 + interpreter.SetVar("TRUE", 1) // boolean shortcut to 1 + interpreter.SetVar("true", 1) // boolean shortcut to 1 - // Channel macros - interpreter.SetVar("$common", PUB_FREQ) - interpreter.SetVar("$science", SCI_FREQ) - interpreter.SetVar("$command", COMM_FREQ) - interpreter.SetVar("$medical", MED_FREQ) - interpreter.SetVar("$engineering", ENG_FREQ) - interpreter.SetVar("$security", SEC_FREQ) - interpreter.SetVar("$supply", SUP_FREQ) - interpreter.SetVar("$service", SRV_FREQ) - - // Signal data + interpreter.SetVar("NORTH", NORTH) // NORTH (1) + interpreter.SetVar("SOUTH", SOUTH) // SOUTH (2) + interpreter.SetVar("EAST", EAST) // EAST (4) + interpreter.SetVar("WEST", WEST) // WEST (8) - interpreter.SetVar("$content", signal.data["message"]) - interpreter.SetVar("$freq" , signal.frequency) - interpreter.SetVar("$source" , signal.data["name"]) - interpreter.SetVar("$job" , signal.data["job"]) - interpreter.SetVar("$sign" , signal) - interpreter.SetVar("$pass" , !(signal.data["reject"])) // if the signal isn't rejected, pass = 1; if the signal IS rejected, pass = 0 - - var/datum/language/speaking = signal.data["language"] - if(speaking) - interpreter.SetVar("$language", speaking.name) - else - interpreter.SetVar("$language", "Unknown") + // Channel macros + interpreter.SetVar("$common", PUB_FREQ) + interpreter.SetVar("$science", SCI_FREQ) + interpreter.SetVar("$command", COMM_FREQ) + interpreter.SetVar("$medical", MED_FREQ) + interpreter.SetVar("$engineering", ENG_FREQ) + interpreter.SetVar("$security", SEC_FREQ) + interpreter.SetVar("$supply", SUP_FREQ) + interpreter.SetVar("$service", SRV_FREQ) - // Set up the script procs + // Signal data - /* - -> Send another signal to a server - @format: broadcast(content, frequency, source, job) + interpreter.SetVar("$content", signal.data["message"]) + interpreter.SetVar("$freq", signal.frequency) + interpreter.SetVar("$source", signal.data["name"]) + interpreter.SetVar("$job", signal.data["job"]) + interpreter.SetVar("$sign", signal) + interpreter.SetVar("$pass", !(signal.data["reject"])) // if the signal isn't rejected, pass = 1; if the signal IS rejected, pass = 0 - @param content: Message to broadcast - @param frequency: Frequency to broadcast to - @param source: The name of the source you wish to imitate. Must be stored in stored_names list. - @param job: The name of the job. - */ - interpreter.SetProc("broadcast", "tcombroadcast", signal, list("message", "freq", "source", "job")) + var/datum/language/speaking = signal.data["language"] + if(speaking) + interpreter.SetVar("$language", speaking.name) + else + interpreter.SetVar("$language", "Unknown") - /* - -> Store a value permanently to the server machine (not the actual game hosting machine, the ingame machine) - @format: mem(address, value) + // Set up the script procs - @param address: The memory address (string index) to store a value to - @param value: The value to store to the memory address - */ - interpreter.SetProc("mem", "mem", signal, list("address", "value")) + /* + -> Send another signal to a server + @format: broadcast(content, frequency, source, job) - /* -- Clone functions, carried from default BYOND procs --- */ - - // Vector - interpreter.SetProc("vector", /proc/n_list) - interpreter.SetProc("at", /proc/n_listpos) - interpreter.SetProc("copy", /proc/n_listcopy) - interpreter.SetProc("push_back", /proc/n_listadd) - interpreter.SetProc("remove", /proc/n_listremove) - interpreter.SetProc("cut", /proc/n_listcut) - interpreter.SetProc("swap", /proc/n_listswap) - interpreter.SetProc("insert", /proc/n_listinsert) - interpreter.SetProc("pick", /proc/n_pick) - interpreter.SetProc("prob", /proc/n_prob) - interpreter.SetProc("substr", /proc/n_substr) - interpreter.SetProc("find", /proc/n_smartfind) - interpreter.SetProc("length", /proc/n_smartlength) + @param content: Message to broadcast + @param frequency: Frequency to broadcast to + @param source: The name of the source you wish to imitate. Must be stored in stored_names list. + @param job: The name of the job. + */ + interpreter.SetProc("broadcast", "tcombroadcast", signal, list("message", "freq", "source", "job")) - // Strings - interpreter.SetProc("lower", /proc/n_lower) - interpreter.SetProc("upper", /proc/n_upper) - interpreter.SetProc("explode", /proc/n_explode) - interpreter.SetProc("implode", /proc/n_implode) - interpreter.SetProc("repeat", /proc/n_repeat) - interpreter.SetProc("reverse", /proc/n_reverse) - interpreter.SetProc("tonum", /proc/n_str2num) - interpreter.SetProc("replace", /proc/n_replace) - interpreter.SetProc("proper", /proc/n_proper) + /* + -> Store a value permanently to the server machine (not the actual game hosting machine, the ingame machine) + @format: mem(address, value) - // Numbers - interpreter.SetProc("tostring", /proc/n_num2str) - interpreter.SetProc("sqrt", /proc/n_sqrt) - interpreter.SetProc("abs", /proc/n_abs) - interpreter.SetProc("floor", /proc/n_floor) - interpreter.SetProc("ceil", /proc/n_ceil) - interpreter.SetProc("round", /proc/n_round) - interpreter.SetProc("clamp", /proc/n_clamp) - interpreter.SetProc("inrange", /proc/n_inrange) - interpreter.SetProc("rand", /proc/n_rand) - interpreter.SetProc("randseed", /proc/n_randseed) - interpreter.SetProc("min", /proc/n_min) - interpreter.SetProc("max", /proc/n_max) - interpreter.SetProc("sin", /proc/n_sin) - interpreter.SetProc("cos", /proc/n_cos) - interpreter.SetProc("asin", /proc/n_asin) - interpreter.SetProc("acos", /proc/n_acos) - interpreter.SetProc("log", /proc/n_log) + @param address: The memory address (string index) to store a value to + @param value: The value to store to the memory address + */ + interpreter.SetProc("mem", "mem", signal, list("address", "value")) - // Time - interpreter.SetProc("time", /proc/n_time) - interpreter.SetProc("sleep", /proc/n_delay) - interpreter.SetProc("timestamp", /proc/gameTimestamp) + /* + -> Delay code for a given amount of deciseconds + @format: sleep(time) - // Run the compiled code - interpreter.Run() + @param time: time to sleep in deciseconds (1/10th second) + */ + interpreter.SetProc("sleep", /proc/delay) - // Backwards-apply variables onto signal data - /* sanitize EVERYTHING. fucking players can't be trusted with SHIT */ + /* + -> Replaces a string with another string + @format: replace(string, substring, replacestring) - signal.data["message"] = interpreter.GetVar("$content") - signal.frequency = interpreter.GetVar("$freq") + @param string: the string to search for substrings (best used with $content$ constant) + @param substring: the substring to search for + @param replacestring: the string to replace the substring with - var/setname = "" - var/obj/machinery/telecomms/server/S = signal.data["server"] - if(interpreter.GetVar("$source") in S.stored_names) - setname = interpreter.GetVar("$source") - else - setname = "[interpreter.GetVar("$source")]" + */ + interpreter.SetProc("replace", /proc/replacetext) - if(signal.data["name"] != setname) - signal.data["realname"] = setname - signal.data["name"] = setname - signal.data["job"] = interpreter.GetVar("$job") - signal.data["reject"] = !(interpreter.GetVar("$pass")) // set reject to the opposite of $pass + /* + -> Locates an element/substring inside of a list or string + @format: find(haystack, needle, start = 1, end = 0) - // If the message is invalid, just don't broadcast it! - if(signal.data["message"] == "" || !signal.data["message"]) - signal.data["reject"] = 1 + @param haystack: the container to search + @param needle: the element to search for + @param start: the position to start in + @param end: the position to end in + + */ + interpreter.SetProc("find", /proc/smartfind) + + /* + -> Finds the length of a string or list + @format: length(container) + + @param container: the list or container to measure + + */ + interpreter.SetProc("length", /proc/smartlength) + + /* -- Clone functions, carried from default BYOND procs --- */ + + // vector namespace + interpreter.SetProc("vector", /proc/n_list) + interpreter.SetProc("at", /proc/n_listpos) + interpreter.SetProc("copy", /proc/n_listcopy) + interpreter.SetProc("push_back", /proc/n_listadd) + interpreter.SetProc("remove", /proc/n_listremove) + interpreter.SetProc("cut", /proc/n_listcut) + interpreter.SetProc("swap", /proc/n_listswap) + interpreter.SetProc("insert", /proc/n_listinsert) + + interpreter.SetProc("pick", /proc/n_pick) + interpreter.SetProc("prob", /proc/prob_chance) + interpreter.SetProc("substr", /proc/docopytext) + + interpreter.SetProc("shuffle", /proc/shuffle) + interpreter.SetProc("uniquevector", /proc/uniquelist) + + interpreter.SetProc("text2vector", /proc/text2list) + interpreter.SetProc("text2vectorEx",/proc/text2listEx) + interpreter.SetProc("vector2text", /proc/list2text) + + // Donkie~ + // Strings + interpreter.SetProc("lower", /proc/n_lower) + interpreter.SetProc("upper", /proc/n_upper) + interpreter.SetProc("explode", /proc/string_explode) + interpreter.SetProc("implode", /proc/list2text) + interpreter.SetProc("repeat", /proc/n_repeat) + interpreter.SetProc("reverse", /proc/reverse_text) + interpreter.SetProc("tonum", /proc/n_str2num) + interpreter.SetProc("capitalize", /proc/capitalize) + interpreter.SetProc("replacetextEx",/proc/replacetextEx) + + // Numbers + interpreter.SetProc("tostring", /proc/n_num2str) + interpreter.SetProc("sqrt", /proc/n_sqrt) + interpreter.SetProc("abs", /proc/n_abs) + interpreter.SetProc("floor", /proc/Floor) + interpreter.SetProc("ceil", /proc/Ceiling) + interpreter.SetProc("round", /proc/n_round) + interpreter.SetProc("clamp", /proc/n_clamp) + interpreter.SetProc("inrange", /proc/IsInRange) + interpreter.SetProc("rand", /proc/rand_chance) + interpreter.SetProc("arctan", /proc/Atan2) + interpreter.SetProc("lcm", /proc/Lcm) + interpreter.SetProc("gcd", /proc/Gcd) + interpreter.SetProc("mean", /proc/Mean) + interpreter.SetProc("root", /proc/Root) + interpreter.SetProc("sin", /proc/n_sin) + interpreter.SetProc("cos", /proc/n_cos) + interpreter.SetProc("arcsin", /proc/n_asin) + interpreter.SetProc("arccos", /proc/n_acos) + interpreter.SetProc("tan", /proc/Tan) + interpreter.SetProc("csc", /proc/Csc) + interpreter.SetProc("cot", /proc/Cot) + interpreter.SetProc("sec", /proc/Sec) + interpreter.SetProc("todegrees", /proc/ToDegrees) + interpreter.SetProc("toradians", /proc/ToRadians) + interpreter.SetProc("lerp", /proc/Lerp) + interpreter.SetProc("max", /proc/n_max) + interpreter.SetProc("min", /proc/n_min) + + // End of Donkie~ + + // Time + interpreter.SetProc("time", /proc/time) + interpreter.SetProc("timestamp", /proc/timestamp) + + // Run the compiled code + interpreter.Run() + + // Backwards-apply variables onto signal data + /* sanitize EVERYTHING. fucking players can't be trusted with SHIT */ + + /* Okay, so, the original 'sanitizing' code... did fucking nothing. Then PJB fixed it, which means no HTML. + But I like HTML, so back to no sanitizing.*/ + + signal.data["message"] = interpreter.GetVar("$content", signal.data["message"]) + signal.frequency = interpreter.GetCleanVar("$freq", signal.frequency) + + var/setname = interpreter.GetVar("$source", signal.data["name"]) + + if(signal.data["name"] != setname) + signal.data["realname"] = setname + signal.data["name"] = setname + signal.data["job"] = interpreter.GetVar("$job", signal.data["job"]) + signal.data["reject"] = !(interpreter.GetCleanVar("$pass")) // set reject to the opposite of $pass + + // If the message is invalid, just don't broadcast it! + if(signal.data["message"] == "" || !signal.data["message"]) + signal.data["reject"] = 1 /* -- Actual language proc code -- */ - -datum/signal - - proc/mem(var/address, var/value) - - if(istext(address)) - var/obj/machinery/telecomms/server/S = data["server"] - - if(!value && value != 0) - return S.memory[address] - - else - S.memory[address] = value - - - proc/tcombroadcast(var/message, var/freq, var/source, var/job) - - var/datum/signal/newsign = new +/datum/signal/proc/mem(var/address, var/value) + if(istext(address)) var/obj/machinery/telecomms/server/S = data["server"] - var/obj/item/device/radio/hradio = S.server_radio - if(!hradio) - error("[src] has no radio.") - return + if(!value && value != 0) + return S.memory[address] - if((!message || message == "") && message != 0) - message = "*beep*" - if(!source) - source = "[html_encode(uppertext(S.id))]" - hradio = new // sets the hradio as a radio intercom - if(!freq) - freq = 1459 - if(findtext(num2text(freq), ".")) // if the frequency has been set as a decimal - freq *= 10 // shift the decimal one place - - if(!job) - job = "?" - - newsign.data["mob"] = null - newsign.data["mobtype"] = /mob/living/carbon/human - if(source in S.stored_names) - newsign.data["name"] = source else - newsign.data["name"] = "[html_encode(uppertext(source))]" - newsign.data["realname"] = newsign.data["name"] - newsign.data["job"] = job - newsign.data["compression"] = 0 - newsign.data["message"] = message - newsign.data["type"] = 2 // artificial broadcast - if(!isnum(freq)) - freq = text2num(freq) - newsign.frequency = freq + S.memory[address] = value - var/datum/radio_frequency/connection = radio_controller.return_frequency(freq) - newsign.data["connection"] = connection +/datum/signal/proc/tcombroadcast(var/message, var/freq, var/source, var/job) + var/datum/signal/newsign = new + var/obj/machinery/telecomms/server/S = data["server"] + var/obj/item/device/radio/hradio = S.server_radio + + if(!hradio) + error("[src] has no radio.") + return + + if((!message || message == "") && message != 0) + message = "*beep*" + if(!source) + source = "[html_encode(uppertext(S.id))]" + hradio = new // sets the hradio as a radio intercom + if(!freq || (!isnum(freq) && text2num(freq) == null)) + freq = 1459 + if(findtext(num2text(freq), ".")) // if the frequency has been set as a decimal + freq *= 10 // shift the decimal one place + + if(!job) + job = "?" + + newsign.data["mob"] = null + newsign.data["mobtype"] = /mob/living/carbon/human + newsign.data["name"] = source + newsign.data["realname"] = newsign.data["name"] + newsign.data["job"] = "[job]" + newsign.data["compression"] = 0 + newsign.data["message"] = message + newsign.data["type"] = 2 // artificial broadcast + if(!isnum(freq)) + freq = text2num(freq) + newsign.frequency = freq + + var/datum/radio_frequency/connection = radio_controller.return_frequency(freq) + newsign.data["connection"] = connection - newsign.data["radio"] = hradio - newsign.data["vmessage"] = message - newsign.data["vname"] = source - newsign.data["vmask"] = 0 - newsign.data["level"] = list() - - var/pass = S.relay_information(newsign, "/obj/machinery/telecomms/hub") - if(!pass) - S.relay_information(newsign, "/obj/machinery/telecomms/broadcaster") // send this simple message to broadcasters + newsign.data["radio"] = hradio + newsign.data["vmessage"] = message + newsign.data["vname"] = source + newsign.data["vmask"] = 0 + newsign.data["level"] = data["level"] + var/pass = S.relay_information(newsign, "/obj/machinery/telecomms/hub") + if(!pass) + S.relay_information(newsign, "/obj/machinery/telecomms/broadcaster") // send this simple message to broadcasters \ No newline at end of file diff --git a/code/modules/scripting/Implementations/_Logic.dm b/code/modules/scripting/Implementations/_Logic.dm index 4034315aab3..c71839eaad9 100644 --- a/code/modules/scripting/Implementations/_Logic.dm +++ b/code/modules/scripting/Implementations/_Logic.dm @@ -1,17 +1,18 @@ // Script -> BYOND code procs #define SCRIPT_MAX_REPLACEMENTS_ALLOWED 200 - // --- List operations (lists known as vectors in n_script) --- -// Creates a list out of all the arguments +// Clone of list() /proc/n_list() + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_list() called tick#: [world.time]") var/list/returnlist = list() for(var/e in args) returnlist.Add(e) return returnlist -// Picks one random item from the list +// Clone of pick() /proc/n_pick() + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_pick() called tick#: [world.time]") var/list/finalpick = list() for(var/e in args) if(isobject(e)) @@ -24,15 +25,16 @@ return pick(finalpick) -// Gets/Sets a value at a key in the list +// Clone of list[] /proc/n_listpos(var/list/L, var/pos, var/value) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listpos() called tick#: [world.time]") if(!istype(L, /list)) return if(isnum(pos)) if(!value) - if(L.len >= pos) + if(L.len >= pos && !(pos > L.len)) return L[pos] else - if(L.len >= pos) + if(L.len >= pos && !(pos > L.len)) L[pos] = value else if(istext(pos)) if(!value) @@ -40,13 +42,15 @@ else L[pos] = value -// Copies the list into a new one +// Clone of list.Copy() /proc/n_listcopy(var/list/L, var/start, var/end) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listcopy() called tick#: [world.time]") if(!istype(L, /list)) return return L.Copy(start, end) -// Adds arg 2,3,4,5... to the end of list at arg 1 +// Clone of list.Add() /proc/n_listadd() + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listadd() called tick#: [world.time]") var/list/chosenlist var/i = 1 for(var/e in args) @@ -59,8 +63,9 @@ if(chosenlist) chosenlist.Add(e) -// Removes arg 2,3,4,5... from list at arg 1 +// Clone of list.Remove() /proc/n_listremove() + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listremove() called tick#: [world.time]") var/list/chosenlist var/i = 1 for(var/e in args) @@ -73,26 +78,45 @@ if(chosenlist) chosenlist.Remove(e) -// Cuts out a copy of a list +// Clone of list.len = 0 /proc/n_listcut(var/list/L, var/start, var/end) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listcut() called tick#: [world.time]") if(!istype(L, /list)) return return L.Cut(start, end) -// Swaps two values in the list +// Clone of list.Swap() /proc/n_listswap(var/list/L, var/firstindex, var/secondindex) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listswap() called tick#: [world.time]") if(!istype(L, /list)) return if(L.len >= secondindex && L.len >= firstindex) return L.Swap(firstindex, secondindex) -// Inserts a value into the list +// Clone of list.Insert() /proc/n_listinsert(var/list/L, var/index, var/element) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_listinsert() called tick#: [world.time]") if(!istype(L, /list)) return return L.Insert(index, element) -// --- String methods --- +// --- Miscellaneous functions --- -//If list, finds a value in it, if text, finds a substring in it -/proc/n_smartfind(var/haystack, var/needle, var/start = 1, var/end = 0) +// Clone of sleep() +/proc/delay(var/time) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/delay() called tick#: [world.time]") + sleep(time) + +// Clone of rand() +/proc/rand_chance(var/low = 0, var/high) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/rand_chance() called tick#: [world.time]") + return rand(low, high) + +// Clone of prob() +/proc/prob_chance(var/chance) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/prob_chance() called tick#: [world.time]") + return prob(chance) + +// Merge of list.Find() and findtext() +/proc/smartfind(var/haystack, var/needle, var/start = 1, var/end = 0) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/smartfind() called tick#: [world.time]") if(haystack && needle) if(isobject(haystack)) if(istype(haystack, /list)) @@ -104,41 +128,54 @@ if(istext(haystack)) if(length(haystack) >= end && start > 0) return findtext(haystack, needle, start, end) - -//Returns a substring of the string -/proc/n_substr(var/string, var/start = 1, var/end = 0) + +// Clone of copytext() +/proc/docopytext(var/string, var/start = 1, var/end = 0) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/docopytext() called tick#: [world.time]") if(istext(string) && isnum(start) && isnum(end)) if(start > 0) return copytext(string, start, end) -//Returns the length of the string or list -/proc/n_smartlength(var/container) +// Clone of length() +/proc/smartlength(var/container) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/smartlength() called tick#: [world.time]") if(container) if(istype(container, /list) || istext(container)) return length(container) + return 0 -//Lowercase all characters +// BY DONKIE~ +// String stuff /proc/n_lower(var/string) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_lower() called tick#: [world.time]") if(istext(string)) return lowertext(string) -//Uppercase all characters /proc/n_upper(var/string) + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/n_upper() called tick#: [world.time]") if(istext(string)) return uppertext(string) -//Converts a string to a list -/proc/n_explode(var/string, var/separator = "") +/proc/time() + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/time() called tick#: [world.time]") + return world.time + (12 HOURS) + +/proc/timestamp(var/format = "hh:mm:ss") // Get the game time in text + //writepanic("[__FILE__].[__LINE__] (no type)([usr ? usr.ckey : ""]) \\/proc/timestamp() called tick#: [world.time]") + return time2text(world.time + (10 HOURS), format) // Yes, 10, not 12 hours, for some reason time2text() is being moronic (T-thanks BYOND), and it's adding 2 hours to this, I don't even know either. + +proc/string_explode(var/string, var/separator = "") + //writepanic("[__FILE__].[__LINE__] \\/proc/string_explode() called tick#: [world.time]") if(istext(string) && (istext(separator) || isnull(separator))) return text2list(string, separator) //Converts a list to a string -/proc/n_implode(var/list/li, var/separator) +/proc/list_implode(var/list/li, var/separator) if(istype(li) && (istext(separator) || isnull(separator))) return list2text(li, separator) -//Repeats the string x times -/proc/n_repeat(var/string, var/amount) +proc/n_repeat(var/string, var/amount) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_repeat() called tick#: [world.time]") if(istext(string) && isnum(amount)) var/i var/newstring = "" @@ -151,166 +188,76 @@ return newstring -//Reverses the order of the string. "Clown" becomes "nwolC" -/proc/n_reverse(var/string) - if(istext(string)) - var/newstring = "" - var/i - for(i=lentext(string), i>0, i--) - if(i>=1000) - break - newstring = newstring + copytext(string, i, i+1) - - return newstring - -// String -> Number -/proc/n_str2num(var/string) +// I don't know if it's neccesary to make my own proc, but I think I have to to be able to check for istext. +proc/n_str2num(var/string) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_str2num() called tick#: [world.time]") if(istext(string)) return text2num(string) -/proc/n_proper(var/string) - if(!istext(string)) - return "" +// Clamps N between min and max +/proc/n_clamp(var/num, var/min = 0, var/max = 1) + if(isnum(num) && isnum(min) && isnum(max)) + return Clamp(num, min, max) - return text("[][]", uppertext(copytext(string, 1, 2)), lowertext(copytext(string, 2))) - - -// --- Number methods --- - -//Returns the highest value of the arguments -//Need custom functions here cause byond's min and max runtimes if you give them a string or list. -/proc/n_max() - if(args.len == 0) - return 0 - - var/max = args[1] - for(var/e in args) - if(isnum(e) && e > max) - max = e - - return max - -//Returns the lowest value of the arguments -/proc/n_min() - if(args.len == 0) - return 0 - - var/min = args[1] - for(var/e in args) - if(isnum(e) && e < min) - min = e - - return min - -/proc/n_prob(var/chance) - return prob(chance) - -/proc/n_randseed(var/seed) - rand_seed(seed) - return 0 - -/proc/n_rand(var/low, var/high) - if(isnull(low) && isnull(high)) - return rand() - - return rand(low, high) - // Number shit -/proc/n_num2str(var/num) +proc/n_num2str(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_num2str() called tick#: [world.time]") if(isnum(num)) return num2text(num) // Squareroot -/proc/n_sqrt(var/num) +proc/n_sqrt(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_sqrt() called tick#: [world.time]") if(isnum(num)) return sqrt(num) // Magnitude of num -/proc/n_abs(var/num) +proc/n_abs(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_abs() called tick#: [world.time]") if(isnum(num)) return abs(num) // Round down -/proc/n_floor(var/num) +proc/n_floor(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_floor() called tick#: [world.time]") if(isnum(num)) return round(num) // Round up -/proc/n_ceil(var/num) +proc/n_ceil(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_ceil() called tick#: [world.time]") if(isnum(num)) return round(num)+1 // Round to nearest integer -/proc/n_round(var/num) +proc/n_round(var/num) + //writepanic("[__FILE__].[__LINE__] \\/proc/n_round() called tick#: [world.time]") if(isnum(num)) if(num-round(num)<0.5) return round(num) - return n_ceil(num) + return n_ceil(num)\ -// Clamps N between min and max -/proc/n_clamp(var/num, var/min=-1, var/max=1) - if(isnum(num)&&isnum(min)&&isnum(max)) - if(num<=min) - return min - if(num>=max) - return max - return num +// END OF BY DONKIE :( -// Returns 1 if N is inbetween Min and Max -/proc/n_inrange(var/num, var/min=-1, var/max=1) - if(isnum(num)&&isnum(min)&&isnum(max)) - return ((min <= num) && (num <= max)) +/proc/n_sin(var/const/x) + return sin(x) -// Returns the sine of num -/proc/n_sin(var/num) - if(isnum(num)) - return sin(num) +/proc/n_cos(var/const/x) + return cos(x) -// Returns the cosine of num -/proc/n_cos(var/num) - if(isnum(num)) - return cos(num) +/proc/n_asin(var/const/x) + return arcsin(x) -// Returns the arcsine of num -/proc/n_asin(var/num) - if(isnum(num)&&-1<=num&&num<=1) - return arcsin(num) +/proc/n_acos(var/const/x) + return arccos(x) -// Returns the arccosine of num -/proc/n_acos(var/num) - if(isnum(num)&&-1<=num&&num<=1) - return arccos(num) -// Returns the natural log of num +/proc/n_max(...) + return max(arglist(args)) + +/proc/n_min(...) + return min(arglist(args)) + /proc/n_log(var/num) - if(isnum(num)&&0 SCRIPT_MAX_REPLACEMENTS_ALLOWED) - break - var/found = findtext(text, find, last_found, 0) - . += copytext(text, last_found, found) - if(found) - . += replacement - last_found = found + find_len - continue - return - -// --- Miscellaneous functions --- - -/proc/n_time() - return world.timeofday - -// Clone of sleep() -/proc/n_delay(var/time) - sleep(time) \ No newline at end of file + if(isnum(num) && 0 < num) + return log(num) \ No newline at end of file diff --git a/code/modules/scripting/Interpreter/Evaluation.dm b/code/modules/scripting/Interpreter/Evaluation.dm index 0b612608e7f..84c255fe9ad 100644 --- a/code/modules/scripting/Interpreter/Evaluation.dm +++ b/code/modules/scripting/Interpreter/Evaluation.dm @@ -1,169 +1,203 @@ /proc/isobject(x) - return (istype(x, /datum) || istype(x, /list) || istype(x, /savefile) || istype(x, /client) || (x==world)) + return (istype(x, /datum) || istype(x, /list) || istype(x, /savefile) || istype(x, /client) || (x == world)) + +/datum/n_Interpreter/proc/Eval(datum/node/expression/exp) + if(istype(exp, /datum/node/expression/FunctionCall)) + return RunFunction(exp) + + else if(istype(exp, /datum/node/expression/operator)) + return EvalOperator(exp) + + else if(istype(exp, /datum/node/expression/value/literal)) + var/datum/node/expression/value/literal/lit = exp + return lit.value + + else if(istype(exp, /datum/node/expression/value/reference)) + var/datum/node/expression/value/reference/ref = exp + return ref.value + + else if(istype(exp, /datum/node/expression/value/variable)) + var/datum/node/expression/value/variable/v = exp + if(!v.object) + return Eval(GetVariable(v.id.id_name)) + else + var/datum/D + if(istype(v.object, /datum/node/identifier)) + D = GetVariable(v.object:id_name) + else + D = v.object + + D = Eval(D) + if(!isobject(D)) + return null + + if(!D.vars.Find(v.id.id_name)) + RaiseError(new/datum/runtimeError/UndefinedVariable("[v.object.ToString()].[v.id.id_name]")) + return null + + return Eval(D.vars[v.id.id_name]) + + else if(istype(exp, /datum/node/expression)) + RaiseError(new/datum/runtimeError/UnknownInstruction()) + + else + return exp + +/datum/n_Interpreter/proc/EvalOperator(datum/node/expression/operator/exp) + if(istype(exp, /datum/node/expression/operator/binary)) + var/datum/node/expression/operator/binary/bin = exp + try // This way we can forgo sanity in the actual evaluation (other than divide by 0). + switch(bin.type) + if(/datum/node/expression/operator/binary/Equal) + return Equal(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/NotEqual) + return NotEqual(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Greater) + return Greater(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Less) + return Less(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/GreaterOrEqual) + return GreaterOrEqual(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/LessOrEqual) + return LessOrEqual(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/LogicalAnd) + return LogicalAnd(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/LogicalOr) + return LogicalOr(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/LogicalXor) + return LogicalXor(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/BitwiseAnd) + return BitwiseAnd(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/BitwiseOr) + return BitwiseOr(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/BitwiseXor) + return BitwiseXor(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Add) + return Add(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Subtract) + return Subtract(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Multiply) + return Multiply(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Divide) + return Divide(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Power) + return Power(Eval(bin.exp), Eval(bin.exp2)) + + if(/datum/node/expression/operator/binary/Modulo) + return Modulo(Eval(bin.exp), Eval(bin.exp2)) -/n_Interpreter - proc - Eval(node/expression/exp) - if(istype(exp, /node/expression/FunctionCall)) - return RunFunction(exp) - else if(istype(exp, /node/expression/operator)) - return EvalOperator(exp) - else if(istype(exp, /node/expression/value/literal)) - var/node/expression/value/literal/lit=exp - return lit.value - else if(istype(exp, /node/expression/value/reference)) - var/node/expression/value/reference/ref=exp - return ref.value - else if(istype(exp, /node/expression/value/variable)) - var/node/expression/value/variable/v=exp - if(!v.object) - return Eval(GetVariable(v.id.id_name)) else - var/datum/D - if(istype(v.object, /node/identifier)) - D=GetVariable(v.object:id_name) - else - D=v.object - D=Eval(D) - if(!isobject(D)) - return null - if(!D.vars.Find(v.id.id_name)) - RaiseError(new/runtimeError/UndefinedVariable("[v.object.ToString()].[v.id.id_name]")) - return null - return Eval(D.vars[v.id.id_name]) - else if(istype(exp, /node/expression)) - RaiseError(new/runtimeError/UnknownInstruction()) - else - return exp + RaiseError(new/datum/runtimeError/UnknownInstruction()) - EvalOperator(node/expression/operator/exp) - if(istype(exp, /node/expression/operator/binary)) - var/node/expression/operator/binary/bin=exp - switch(bin.type) - if(/node/expression/operator/binary/Equal) - return Equal(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/NotEqual) - return NotEqual(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Greater) - return Greater(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Less) - return Less(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/GreaterOrEqual) - return GreaterOrEqual(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/LessOrEqual) - return LessOrEqual(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/LogicalAnd) - return LogicalAnd(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/LogicalOr) - return LogicalOr(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/LogicalXor) - return LogicalXor(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/BitwiseAnd) - return BitwiseAnd(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/BitwiseOr) - return BitwiseOr(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/BitwiseXor) - return BitwiseXor(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Add) - return Add(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Subtract) - return Subtract(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Multiply) - return Multiply(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Divide) - return Divide(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Power) - return Power(Eval(bin.exp), Eval(bin.exp2)) - if(/node/expression/operator/binary/Modulo) - return Modulo(Eval(bin.exp), Eval(bin.exp2)) - else - RaiseError(new/runtimeError/UnknownInstruction()) - else - switch(exp.type) - if(/node/expression/operator/unary/Minus) - return Minus(Eval(exp.exp)) - if(/node/expression/operator/unary/LogicalNot) - return LogicalNot(Eval(exp.exp)) - if(/node/expression/operator/unary/BitwiseNot) - return BitwiseNot(Eval(exp.exp)) - if(/node/expression/operator/unary/group) - return Eval(exp.exp) - else - RaiseError(new/runtimeError/UnknownInstruction()) + catch + RaiseError(new/datum/runtimeError/TypeMismatch(bin.token, Eval(bin.exp), Eval(bin.exp2))) + else + try + switch(exp.type) + if(/datum/node/expression/operator/unary/Minus) + return Minus(Eval(exp.exp)) - //Binary// - //Comparison operators - Equal(a, b) return a==b - NotEqual(a, b) return a!=b //LogicalNot(Equal(a, b)) - Greater(a, b) return a>b - Less(a, b) return a=b - LessOrEqual(a, b) return a<=b - //Logical Operators - LogicalAnd(a, b) return a&&b - LogicalOr(a, b) return a||b - LogicalXor(a, b) return (a||b) && !(a&&b) - //Bitwise Operators - BitwiseAnd(a, b) return a&b - BitwiseOr(a, b) return a|b - BitwiseXor(a, b) return a^b - //Arithmetic Operators - Add(a, b) - if(istext(a)&&!istext(b)) b="[b]" - else if(istext(b)&&!istext(a)) a="[a]" - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("+", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("+", a, b)) - return null - return a+b - Subtract(a, b) - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("-", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("-", a, b)) - return null - return a-b - Divide(a, b) - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("/", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("/", a, b)) - return null - if(b==0 || b==null) - RaiseError(new/runtimeError/DivisionByZero()) - return null - return a/b - Multiply(a, b) - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("*", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("*", a, b)) - return null - return a*b - Modulo(a, b) - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("%", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("%", a, b)) - return null - return a%b - Power(a, b) - if(isobject(a) && !isobject(b)) - RaiseError(new/runtimeError/TypeMismatch("**", a, b)) - return null - else if(isobject(b) && !isobject(a)) - RaiseError(new/runtimeError/TypeMismatch("**", a, b)) - return null - return a**b + if(/datum/node/expression/operator/unary/LogicalNot) + return LogicalNot(Eval(exp.exp)) - //Unary// - Minus(a) return -a - LogicalNot(a) return !a - BitwiseNot(a) return ~a \ No newline at end of file + if(/datum/node/expression/operator/unary/BitwiseNot) + return BitwiseNot(Eval(exp.exp)) + + if(/datum/node/expression/operator/unary/group) + return Eval(exp.exp) + + else + RaiseError(new/datum/runtimeError/UnknownInstruction()) + catch + RaiseError(new/datum/runtimeError/TypeMismatch/unary(exp.token, Eval(exp.exp))) + +//Binary// +//Comparison operators +/datum/n_Interpreter/proc/Equal(a, b) + return a == b + +/datum/n_Interpreter/proc/NotEqual(a, b) + return a != b //LogicalNot(Equal(a, b)) + +/datum/n_Interpreter/proc/Greater(a, b) + return a > b + +/datum/n_Interpreter/proc/Less(a, b) + return a < b + +/datum/n_Interpreter/proc/GreaterOrEqual(a, b) + return a >= b + +/datum/n_Interpreter/proc/LessOrEqual(a, b) + return a <= b + +//Logical Operators +/datum/n_Interpreter/proc/LogicalAnd(a, b) + return a && b + +/datum/n_Interpreter/proc/LogicalOr(a, b) + return a || b + +/datum/n_Interpreter/proc/LogicalXor(a, b) + return (a || b) && !(a && b) + +//Bitwise Operators +/datum/n_Interpreter/proc/BitwiseAnd(a, b) + return a & b + +/datum/n_Interpreter/proc/BitwiseOr(a, b) + return a | b + +/datum/n_Interpreter/proc/BitwiseXor(a, b) + return a ^ b + +//Arithmetic Operators +/datum/n_Interpreter/proc/Add(a, b) + return a + b + +/datum/n_Interpreter/proc/Subtract(a, b) + return a - b + +/datum/n_Interpreter/proc/Divide(a, b) + if(b == 0) + RaiseError(new/datum/runtimeError/DivisionByZero()) + return null + + return a / b + +/datum/n_Interpreter/proc/Multiply(a, b) + return a * b + +/datum/n_Interpreter/proc/Modulo(a, b) + + return a % b + +/datum/n_Interpreter/proc/Power(a, b) + return a ** b + +//Unary// +/datum/n_Interpreter/proc/Minus(a) + return -a + +/datum/n_Interpreter/proc/LogicalNot(a) + return !a + +/datum/n_Interpreter/proc/BitwiseNot(a) + return ~a diff --git a/code/modules/scripting/Interpreter/Interaction.dm b/code/modules/scripting/Interpreter/Interaction.dm index f0b7c988d2a..ffcf8f716d8 100644 --- a/code/modules/scripting/Interpreter/Interaction.dm +++ b/code/modules/scripting/Interpreter/Interaction.dm @@ -7,9 +7,6 @@ Procedures allowing for interaction with the script that is being run by the interpreter object. */ -/n_Interpreter - proc - /* Proc: Load Loads a 'compiled' script into memory. @@ -17,126 +14,144 @@ Parameters: program - A object which represents the script's global scope. */ - Load(node/BlockDefinition/GlobalBlock/program) - ASSERT(program) - src.program = program - CreateGlobalScope() +/datum/n_Interpreter/proc/Load(var/datum/node/BlockDefinition/GlobalBlock/program) + ASSERT(program) + src.program = program + CreateGlobalScope() + alertadmins = 0 // reset admin alerts /* - Proc: Run - Runs the script. +Proc: Run +Runs the script. */ - Run() - cur_recursion = 0 // reset recursion - cur_statements = 0 // reset CPU tracking - alertadmins = 0 +/datum/n_Interpreter/proc/Run() + cur_recursion = 0 // reset recursion + cur_statements = 0 // reset CPU tracking - ASSERT(src.program) - RunBlock(src.program) + ASSERT(src.program) + RunBlock(src.program) /* - Proc: SetVar - Defines a global variable for the duration of the next execution of a script. +Proc: SetVar +Defines a global variable for the duration of the next execution of a script. - Notes: - This differs from in that variables set using this procedure only last for the session, - while those defined from the block object persist if it is ran multiple times. +Notes: +This differs from in that variables set using this procedure only last for the session, +while those defined from the block object persist if it is ran multiple times. - See Also: - - +See Also: +- */ - SetVar(name, value) - if(!istext(name)) - //CRASH("Invalid variable name") - return - AssignVariable(name, value) +/datum/n_Interpreter/proc/SetVar(name, value) + if(!istext(name)) + //CRASH("Invalid variable name") + return + + AssignVariable(name, value) /* - Proc: SetProc - Defines a procedure to be available to the script. +Proc: SetProc +Defines a procedure to be available to the script. - Parameters: - name - The name of the procedure as exposed to the script. - path - The typepath of a proc to be called when the function call is read by the interpreter, or, if object is specified, a string representing the procedure's name. - object - (Optional) An object which will the be target of a function call. - params - Only required if object is not null, a list of the names of parameters the proc takes. +Parameters: +name - The name of the procedure as exposed to the script. +path - The typepath of a proc to be called when the function call is read by the interpreter, or, if object is specified, a string representing the procedure's name. +object - (Optional) An object which will the be target of a function call. +params - Only required if object is not null, a list of the names of parameters the proc takes. */ - SetProc(name, path, object=null, list/params=null) - if(!istext(name)) - //CRASH("Invalid function name") - return - if(!object) - globalScope.functions[name] = path - else - var/node/statement/FunctionDefinition/S = new() - S.func_name = name - S.parameters = params - S.block = new() - S.block.SetVar("src", object) - var/node/expression/FunctionCall/C = new() - C.func_name = path - C.object = new("src") - for(var/p in params) - C.parameters += new/node/expression/value/variable(p) - var/node/statement/ReturnStatement/R=new() - R.value=C - S.block.statements += R - globalScope.functions[name] = S +/datum/n_Interpreter/proc/SetProc(name, path, object = null, list/params = null) + if(!istext(name)) + //CRASH("Invalid function name") + return + + if(!object) + globalScope.functions[name] = path + + else + var/datum/node/statement/FunctionDefinition/S = new() + S.func_name = name + S.parameters = params + S.block = new() + S.block.SetVar("src", object) + var/datum/node/expression/FunctionCall/C = new() + C.func_name = path + C.object = new("src") + for(var/p in params) + C.parameters += new/datum/node/expression/value/variable(p) + + var/datum/node/statement/ReturnStatement/R = new() + R.value = C + S.block.statements += R + globalScope.functions[name] = S /* - Proc: VarExists - Checks whether a global variable with the specified name exists. +Proc: VarExists +Checks whether a global variable with the specified name exists. */ - VarExists(name) - return globalScope.variables.Find(name) //convert to 1/0 first? +/datum/n_Interpreter/proc/VarExists(name) + return globalScope.variables.Find(name) //convert to 1/0 first? /* - Proc: ProcExists - Checks whether a global function with the specified name exists. +Proc: ProcExists +Checks whether a global function with the specified name exists. */ - ProcExists(name) - return globalScope.functions.Find(name) +/datum/n_Interpreter/proc/ProcExists(name) + return globalScope.functions.Find(name) /* - Proc: GetVar - Returns the value of a global variable in the script. Remember to ensure that the variable exists before calling this procedure. +Proc: GetVar +Returns the value of a global variable in the script. Remember to ensure that the variable exists before calling this procedure. - See Also: - - +See Also: +- */ - GetVar(name) - if(!VarExists(name)) - //CRASH("No variable named '[name]'.") - return - var/x = globalScope.variables[name] - return Eval(x) +/datum/n_Interpreter/proc/GetVar(name) + if(!VarExists(name)) + //CRASH("No variable named '[name]'.") + return + var/x = globalScope.variables[name] + return Eval(x) /* - Proc: CallProc - Calls a global function defined in the script and, amazingly enough, returns its return value. Remember to ensure that the function - exists before calling this procedure. - - See Also: - - +Proc: GetCleanVar +Returns the value of a global variable in the script and cleans it (sanitizes). */ - CallProc(name, params[]=null) - if(!ProcExists(name)) - //CRASH("No function named '[name]'.") - return - var/node/statement/FunctionDefinition/func = globalScope.functions[name] - if(istype(func)) - var/node/statement/FunctionCall/stmt = new - stmt.func_name = func.func_name - stmt.parameters = params - return RunFunction(stmt) - else - return call(func)(arglist(params)) - //CRASH("Unknown function type '[name]'.") + +/datum/n_Interpreter/proc/GetCleanVar(name, compare) + var/x = GetVar(name) + if(istext(x) && compare && x != compare) // Was changed + x = sanitize(x) + return x /* - Event: HandleError - Called when the interpreter throws a runtime error. +Proc: CallProc +Calls a global function defined in the script and, amazingly enough, returns its return value. Remember to ensure that the function +exists before calling this procedure. - See Also: - - +See Also: +- */ - HandleError(runtimeError/e) \ No newline at end of file +/datum/n_Interpreter/proc/CallProc(name, params[]=null) + if(!ProcExists(name)) + //CRASH("No function named '[name]'.") + return + + var/datum/node/statement/FunctionDefinition/func = globalScope.functions[name] + + if(istype(func)) + var/datum/node/statement/FunctionCall/stmt = new + stmt.func_name = func.func_name + stmt.parameters = params + return RunFunction(stmt) + + else + return call(func)(arglist(params)) + //CRASH("Unknown function type '[name]'.") + +/* +Event: HandleError +Called when the interpreter throws a runtime error. + +See Also: +- +*/ +/datum/n_Interpreter/proc/HandleError(var/datum/runtimeError/e) diff --git a/code/modules/scripting/Interpreter/Interpreter.dm b/code/modules/scripting/Interpreter/Interpreter.dm index 70849ffa157..79802ff2fa5 100644 --- a/code/modules/scripting/Interpreter/Interpreter.dm +++ b/code/modules/scripting/Interpreter/Interpreter.dm @@ -13,302 +13,366 @@ #define RETURNING 1 #define BREAKING 2 #define CONTINUING 4 -/n_Interpreter - var - scope - curScope - globalScope - node - BlockDefinition/program - statement/FunctionDefinition/curFunction - stack - scopes = new() - functions = new() - datum/container // associated container for interpeter +/datum/n_Interpreter + var/datum/scope/curScope + var/datum/scope/globalScope + + var/datum/node/BlockDefinition/program + var/datum/node/statement/FunctionDefinition/curFunction + var/datum/stack/scopes = new() + var/datum/stack/functions = new() + + var/datum/container // associated container for interpeter /* Var: status A variable indicating that the rest of the current block should be skipped. This may be set to any combination of . */ - status=0 - returnVal + var/status = 0 + var/returnVal - max_statements=1000 // maximum amount of statements that can be called in one execution. this is to prevent massive crashes and exploitation - cur_statements=0 // current amount of statements called - alertadmins=0 // set to 1 if the admins shouldn't be notified of anymore issues - max_iterations=100 // max number of uninterrupted loops possible - max_recursion=50 // max recursions without returning anything (or completing the code block) - cur_recursion=0 // current amount of recursion + var/max_statements = 900 // maximum amount of statements that can be called in one execution. this is to prevent massive crashes and exploitation + var/cur_statements = 0 // current amount of statements called + var/alertadmins = 0 // set to 1 if the admins shouldn't be notified of anymore issues + var/max_iterations = 100 // max number of uninterrupted loops possible + var/max_recursion = 10 // max recursions without returning anything (or completing the code block) + var/cur_recursion = 0 // current amount of recursion /* Var: persist If 0, global variables will be reset after Run() finishes. */ - persist=1 - paused=0 + var/persist = 1 + var/paused = 0 /* Constructor: New Calls with the given parameters. */ - New(node/BlockDefinition/GlobalBlock/program=null) - .=..() - if(program)Load(program) +/datum/n_Interpreter/New(datum/node/BlockDefinition/GlobalBlock/program = null) + . = ..() + if(program) + Load(program) + +/* + Set ourselves to Garbage Collect +*/ +/datum/n_Interpreter/proc/GC() + ..() + container = null - proc /* Proc: RaiseError Raises a runtime error. */ - RaiseError(runtimeError/e) - e.stack=functions.Copy() - e.stack.Push(curFunction) - src.HandleError(e) +/datum/n_Interpreter/proc/RaiseError(datum/runtimeError/e) + e.stack = functions.Copy() + e.stack.Push(curFunction) + src.HandleError(e) - CreateScope(node/BlockDefinition/B) - var/scope/S = new(B, curScope) - scopes.Push(curScope) - curScope = S - return S +/datum/n_Interpreter/proc/CreateScope(datum/node/BlockDefinition/B) + var/datum/scope/S = new(B, curScope) + scopes.Push(curScope) + curScope = S + return S - CreateGlobalScope() - scopes.Clear() - var/scope/S = new(program, null) - globalScope = S - return S +/datum/n_Interpreter/proc/CreateGlobalScope() + scopes.Clear() + var/datum/scope/S = new(program, null) + globalScope = S + return S /* - Proc: RunBlock - Runs each statement in a block of code. +Proc: AlertAdmins +Alerts the admins of a script that is bad. */ - RunBlock(node/BlockDefinition/Block, scope/scope = null) - var/is_global = istype(Block, /node/BlockDefinition/GlobalBlock) - if(!is_global) - if(scope) - curScope = scope +/datum/n_Interpreter/proc/AlertAdmins() + if(container && !alertadmins) + if(istype(container, /datum/TCS_Compiler)) + var/datum/TCS_Compiler/Compiler = container + var/obj/machinery/telecomms/server/Holder = Compiler.Holder + var/message = "Potential crash-inducing NTSL script detected at telecommunications server [Compiler.Holder] ([Holder.x], [Holder.y], [Holder.z])." + + alertadmins = 1 + message_admins(message, 1) +/* +Proc: RunBlock +Runs each statement in a block of code. +*/ +/datum/n_Interpreter/proc/RunBlock(var/datum/node/BlockDefinition/Block, var/datum/scope/scope = null) + var/is_global = istype(Block, /datum/node/BlockDefinition/GlobalBlock) + if(!is_global) + if(scope) + curScope = scope + else + CreateScope(Block) + else + if(!persist) + CreateGlobalScope() + + curScope = globalScope + + if(cur_statements < max_statements) + for(var/datum/node/statement/S in Block.statements) + while(paused) sleep(10) + + cur_statements++ + if(cur_statements >= max_statements) + RaiseError(new/datum/runtimeError/MaxCPU()) + AlertAdmins() + break + + if(istype(S, /datum/node/statement/VariableAssignment)) + var/datum/node/statement/VariableAssignment/stmt = S + var/name = stmt.var_name.id_name + + if(!stmt.object) + // Below we assign the variable first to null if it doesn't already exist. + // This is necessary for assignments like +=, and when the variable is used in a function + // If the variable already exists in a different block, then AssignVariable will automatically use that one. + if(!IsVariableAccessible(name)) + AssignVariable(name, null) + + AssignVariable(name, Eval(stmt.value)) else - CreateScope(Block) - else - if(!persist) - CreateGlobalScope() - curScope = globalScope - - if(cur_statements < max_statements) - - for(var/node/statement/S in Block.statements) - while(paused) sleep(10) - - cur_statements++ - if(cur_statements >= max_statements) - RaiseError(new/runtimeError/MaxCPU()) - - if(container && !alertadmins) - if(istype(container, /datum/TCS_Compiler)) - var/datum/TCS_Compiler/Compiler = container - var/obj/machinery/telecomms/server/Holder = Compiler.Holder - var/message = "Potential crash-inducing NTSL script detected at telecommunications server [Compiler.Holder] ([Holder.x], [Holder.y], [Holder.z])." - - alertadmins = 1 - message_admins(message, 1) - break - - if(istype(S, /node/statement/VariableAssignment)) - var/node/statement/VariableAssignment/stmt = S - var/name = stmt.var_name.id_name - if(!stmt.object) - // Below we assign the variable first to null if it doesn't already exist. - // This is necessary for assignments like +=, and when the variable is used in a function - // If the variable already exists in a different block, then AssignVariable will automatically use that one. - if(!IsVariableAccessible(name)) - AssignVariable(name, null) - AssignVariable(name, Eval(stmt.value)) - else - var/datum/D = Eval(GetVariable(stmt.object.id_name)) - if(!D) return - D.vars[stmt.var_name.id_name] = Eval(stmt.value) - else if(istype(S, /node/statement/VariableDeclaration)) - //VariableDeclaration nodes are used to forcibly declare a local variable so that one in a higher scope isn't used by default. - var/node/statement/VariableDeclaration/dec=S - if(!dec.object) - AssignVariable(dec.var_name.id_name, null, curScope) - else - var/datum/D = Eval(GetVariable(dec.object.id_name)) - if(!D) return - D.vars[dec.var_name.id_name] = null - else if(istype(S, /node/statement/FunctionCall)) - RunFunction(S) - else if(istype(S, /node/statement/FunctionDefinition)) - //do nothing - else if(istype(S, /node/statement/WhileLoop)) - RunWhile(S) - else if(istype(S, /node/statement/IfStatement)) - RunIf(S) - else if(istype(S, /node/statement/ReturnStatement)) - if(!curFunction) - RaiseError(new/runtimeError/UnexpectedReturn()) - continue - status |= RETURNING - returnVal=Eval(S:value) - break - else if(istype(S, /node/statement/BreakStatement)) - status |= BREAKING - break - else if(istype(S, /node/statement/ContinueStatement)) - status |= CONTINUING - break - else - RaiseError(new/runtimeError/UnknownInstruction()) - if(status) - break - - curScope = scopes.Pop() - -/* - Proc: RunFunction - Runs a function block or a proc with the arguments specified in the script. -*/ - RunFunction(node/statement/FunctionCall/stmt) - //Note that anywhere /node/statement/FunctionCall/stmt is used so may /node/expression/FunctionCall - - // If recursion gets too high (max 50 nested functions) throw an error - if(cur_recursion >= max_recursion) - RaiseError(new/runtimeError/RecursionLimitReached()) - return 0 - - var/node/statement/FunctionDefinition/def - if(!stmt.object) //A scope's function is being called, stmt.object is null - def = GetFunction(stmt.func_name) - else if(istype(stmt.object)) //A method of an object exposed as a variable is being called, stmt.object is a /node/identifier - var/O = GetVariable(stmt.object.id_name) //Gets a reference to the object which is the target of the function call. - if(!O) return //Error already thrown in GetVariable() - def = Eval(O) - - if(!def) return - - cur_recursion++ // add recursion - if(istype(def)) - if(curFunction) functions.Push(curFunction) - var/scope/S = CreateScope(def.block) - for(var/i=1 to def.parameters.len) - var/val - if(stmt.parameters.len>=i) - val = stmt.parameters[i] - //else - // unspecified param - AssignVariable(def.parameters[i], new/node/expression/value/literal(Eval(val)), S) - curFunction=stmt - RunBlock(def.block, S) - //Handle return value - . = returnVal - status &= ~RETURNING - returnVal=null - curFunction=functions.Pop() - cur_recursion-- - else - cur_recursion-- - var/list/params=new - for(var/node/expression/P in stmt.parameters) - params+=list(Eval(P)) - if(isobject(def)) //def is an object which is the target of a function call - if( !hascall(def, stmt.func_name) ) - RaiseError(new/runtimeError/UndefinedFunction("[stmt.object.id_name].[stmt.func_name]")) + var/datum/D = Eval(GetVariable(stmt.object.id_name)) + if(!D) return - return call(def, stmt.func_name)(arglist(params)) - else //def is a path to a global proc - return call(def)(arglist(params)) + + D.vars[stmt.var_name.id_name] = Eval(stmt.value) + + else if(istype(S, /datum/node/statement/VariableDeclaration)) + //VariableDeclaration nodes are used to forcibly declare a local variable so that one in a higher scope isn't used by default. + var/datum/node/statement/VariableDeclaration/dec=S + if(!dec.object) + AssignVariable(dec.var_name.id_name, null, curScope) + else + var/datum/D = Eval(GetVariable(dec.object.id_name)) + if(!D) + return + + D.vars[dec.var_name.id_name] = null + + else if(istype(S, /datum/node/statement/FunctionCall)) + RunFunction(S) + + else if(istype(S, /datum/node/statement/FunctionDefinition)) + //do nothing + + else if(istype(S, /datum/node/statement/WhileLoop)) + RunWhile(S) + + else if(istype(S, /datum/node/statement/IfStatement)) + RunIf(S) + + else if(istype(S, /datum/node/statement/ReturnStatement)) + if(!curFunction) + RaiseError(new/datum/runtimeError/UnexpectedReturn()) + continue + + status |= RETURNING + returnVal = Eval(S:value) + break + + else if(istype(S, /datum/node/statement/BreakStatement)) + status |= BREAKING + break + + else if(istype(S, /datum/node/statement/ContinueStatement)) + status |= CONTINUING + break + + else + RaiseError(new/datum/runtimeError/UnknownInstruction()) + + if(status) + break + + curScope = scopes.Pop() + +/* +Proc: RunFunction +Runs a function block or a proc with the arguments specified in the script. +*/ +/datum/n_Interpreter/proc/RunFunction(var/datum/node/statement/FunctionCall/stmt) + //Note that anywhere /datum/node/statement/FunctionCall/stmt is used so may /datum/node/expression/FunctionCall + + // If recursion gets too high (max 50 nested functions) throw an error + if(cur_recursion >= max_recursion) + AlertAdmins() + RaiseError(new/datum/runtimeError/RecursionLimitReached()) + return 0 + + var/datum/node/statement/FunctionDefinition/def + if(!stmt.object) //A scope's function is being called, stmt.object is null + def = GetFunction(stmt.func_name) + + else if(istype(stmt.object)) //A method of an object exposed as a variable is being called, stmt.object is a /node/identifier + var/O = GetVariable(stmt.object.id_name) //Gets a reference to the object which is the target of the function call. + if(!O) return //Error already thrown in GetVariable() + def = Eval(O) + + if(!def) + return + + cur_recursion++ // add recursion + if(istype(def)) + if(curFunction) functions.Push(curFunction) + var/datum/scope/S = CreateScope(def.block) + + for(var/i = 1 to def.parameters.len) + var/val + if(stmt.parameters.len >= i) + val = stmt.parameters[i] //else - // RaiseError(new/runtimeError/UnknownInstruction()) + // unspecified param + AssignVariable(def.parameters[i], new/datum/node/expression/value/literal(Eval(val)), S) + + curFunction = stmt + RunBlock(def.block, S) + + //Handle return value + . = returnVal + status &= ~RETURNING + returnVal = null + curFunction = functions.Pop() + cur_recursion-- + + else + cur_recursion-- + var/list/params = new + for(var/datum/node/expression/P in stmt.parameters) + params += list(Eval(P)) + + if(isobject(def)) //def is an object which is the target of a function call + if(!hascall(def, stmt.func_name)) + RaiseError(new/datum/runtimeError/UndefinedFunction("[stmt.object.id_name].[stmt.func_name]")) + return + + return call(def, stmt.func_name)(arglist(params)) + + else //def is a path to a global proc + return call(def)(arglist(params)) + //else + // RaiseError(new/runtimeError/UnknownInstruction()) /* - Proc: RunIf - Checks a condition and runs either the if block or else block. +Proc: RunIf +Checks a condition and runs either the if block or else block. */ - RunIf(node/statement/IfStatement/stmt) - if(Eval(stmt.cond)) - RunBlock(stmt.block) - else if(stmt.else_block) - RunBlock(stmt.else_block) +/datum/n_Interpreter/proc/RunIf(var/datum/node/statement/IfStatement/stmt) + if(!stmt.skip) + if(Eval(stmt.cond)) + RunBlock(stmt.block) + // Loop through the if else chain and tell them to be skipped. + var/datum/node/statement/IfStatement/i = stmt.else_if + var/fail_safe = 800 + + while(i && fail_safe) + fail_safe -= 1 + i.skip = 1 + i = i.else_if + + else if(stmt.else_block) + RunBlock(stmt.else_block) + + // We don't need to skip you anymore. + stmt.skip = 0 /* - Proc: RunWhile - Runs a while loop. +Proc: RunWhile +Runs a while loop. */ - RunWhile(node/statement/WhileLoop/stmt) - var/i=1 - while(Eval(stmt.cond) && Iterate(stmt.block, i++)) - continue - status &= ~BREAKING + +/datum/n_Interpreter/proc/RunWhile(var/datum/node/statement/WhileLoop/stmt) + var/i = 1 + while(Eval(stmt.cond) && Iterate(stmt.block, i++)) + continue + + status &= ~BREAKING /* - Proc:Iterate - Runs a single iteration of a loop. Returns a value indicating whether or not to continue looping. +Proc:Iterate +Runs a single iteration of a loop. Returns a value indicating whether or not to continue looping. */ - Iterate(node/BlockDefinition/block, count) - RunBlock(block) - if(max_iterations > 0 && count >= max_iterations) - RaiseError(new/runtimeError/IterationLimitReached()) - return 0 - if(status & (BREAKING|RETURNING)) - return 0 - status &= ~CONTINUING - return 1 + +/datum/n_Interpreter/proc/Iterate(var/datum/node/BlockDefinition/block, count) + RunBlock(block) + if(max_iterations > 0 && count >= max_iterations) + RaiseError(new/datum/runtimeError/IterationLimitReached()) + return 0 + + if(status & (BREAKING|RETURNING)) + return 0 + + status &= ~CONTINUING + return 1 /* - Proc: GetFunction - Finds a function in an accessible scope with the given name. Returns a . +Proc: GetFunction +Finds a function in an accessible scope with the given name. Returns a . */ - GetFunction(name) - var/scope/S = curScope - while(S) - if(S.functions.Find(name)) - return S.functions[name] - S = S.parent - RaiseError(new/runtimeError/UndefinedFunction(name)) + +/datum/n_Interpreter/proc/GetFunction(name) + var/datum/scope/S = curScope + while(S) + if(S.functions.Find(name)) + return S.functions[name] + S = S.parent + + RaiseError(new/datum/runtimeError/UndefinedFunction(name)) /* - Proc: GetVariable - Finds a variable in an accessible scope and returns its value. +Proc: GetVariable +Finds a variable in an accessible scope and returns its value. */ - GetVariable(name) - var/scope/S = curScope - while(S) - if(S.variables.Find(name)) - return S.variables[name] - S = S.parent - RaiseError(new/runtimeError/UndefinedVariable(name)) - GetVariableScope(name) //needed for when you reassign a variable in a higher scope - var/scope/S = curScope - while(S) - if(S.variables.Find(name)) - return S - S = S.parent +/datum/n_Interpreter/proc/GetVariable(name) + var/datum/scope/S = curScope + while(S) + if(S.variables.Find(name)) + return S.variables[name] + S = S.parent + + RaiseError(new/datum/runtimeError/UndefinedVariable(name)) + +/datum/n_Interpreter/proc/GetVariableScope(name) //needed for when you reassign a variable in a higher scope + var/datum/scope/S = curScope + while(S) + if(S.variables.Find(name)) + return S + + S = S.parent - IsVariableAccessible(name) - var/scope/S = curScope - while(S) - if(S.variables.Find(name)) - return TRUE - S = S.parent - return FALSE +/datum/n_Interpreter/proc/IsVariableAccessible(name) + var/datum/scope/S = curScope + while(S) + if(S.variables.Find(name)) + return TRUE + S = S.parent + + return FALSE /* - Proc: AssignVariable - Assigns a value to a variable in a specific block. +Proc: AssignVariable +Assigns a value to a variable in a specific block. - Parameters: - name - The name of the variable to assign. - value - The value to assign to it. - S - The scope the variable resides in. If it is null, a scope with the variable already existing is found. If no scopes have a variable of the given name, the current scope is used. +Parameters: +name - The name of the variable to assign. +value - The value to assign to it. +S - The scope the variable resides in. If it is null, a scope with the variable already existing is found. If no scopes have a variable of the given name, the current scope is used. */ - AssignVariable(name, node/expression/value, scope/S=null) - if(!S) S = GetVariableScope(name) - if(!S) S = curScope - if(!S) S = globalScope - ASSERT(istype(S)) - if(istext(value) || isnum(value) || isnull(value)) value = new/node/expression/value/literal(value) - else if(!istype(value) && isobject(value)) value = new/node/expression/value/reference(value) - //TODO: check for invalid name - S.variables["[name]"] = value + +/datum/n_Interpreter/proc/AssignVariable(name, datum/node/expression/value, var/datum/scope/S = null) + if(!S) S = GetVariableScope(name) + if(!S) S = curScope + if(!S) S = globalScope + + ASSERT(istype(S)) + if(istext(value) || isnum(value) || isnull(value)) value = new/datum/node/expression/value/literal(value) + else if(!istype(value) && isobject(value)) value = new/datum/node/expression/value/reference(value) + //TODO: check for invalid name + S.variables["[name]"] = value + diff --git a/code/modules/scripting/Interpreter/Scope.dm b/code/modules/scripting/Interpreter/Scope.dm index 50da8047079..24b3fbf727d 100644 --- a/code/modules/scripting/Interpreter/Scope.dm +++ b/code/modules/scripting/Interpreter/Scope.dm @@ -2,17 +2,15 @@ Class: scope A runtime instance of a block. Used internally by the interpreter. */ -scope - var - scope/parent = null - node/BlockDefinition/block - list - functions - variables +/datum/scope + var/datum/scope/parent = null + var/datum/node/BlockDefinition/block + var/list/functions + var/list/variables - New(node/BlockDefinition/B, scope/parent) - src.block = B - src.parent = parent - src.variables = B.initial_variables.Copy() - src.functions = B.functions.Copy() - .=..() \ No newline at end of file +/datum/scope/New(var/datum/node/BlockDefinition/B, var/datum/scope/parent) + src.block = B + src.parent = parent + src.variables = B.initial_variables.Copy() + src.functions = B.functions.Copy() + . = ..() diff --git a/code/modules/scripting/Options.dm b/code/modules/scripting/Options.dm index 22774455dc4..b27acff91d3 100644 --- a/code/modules/scripting/Options.dm +++ b/code/modules/scripting/Options.dm @@ -1,82 +1,121 @@ /* File: Options */ -var/const //Ascii values of characters - ascii_A =65 - ascii_Z =90 - ascii_a =97 - ascii_z =122 - ascii_DOLLAR = 36 // $ - ascii_ZERO=48 - ascii_NINE=57 - ascii_UNDERSCORE=95 // _ +// Ascii values of characters +/var/const/ascii_A = 65 +/var/const/ascii_Z = 90 +/var/const/ascii_a = 97 +/var/const/ascii_z = 122 +/var/const/ascii_DOLLAR = 36 // $ +/var/const/ascii_ZERO = 48 +/var/const/ascii_NINE = 57 +/var/const/ascii_UNDERSCORE = 95 // _ /* Class: n_scriptOptions */ -n_scriptOptions - proc - CanStartID(char) //returns true if the character can start a variable, function, or keyword name (by default letters or an underscore) - if(!isnum(char))char=text2ascii(char) - return (char in ascii_A to ascii_Z) || (char in ascii_a to ascii_z) || char==ascii_UNDERSCORE || char==ascii_DOLLAR +/datum/n_scriptOptions/proc/CanStartID(char) //returns true if the character can start a variable, function, or keyword name (by default letters or an underscore) + if(!isnum(char)) + char = text2ascii(char) - IsValidIDChar(char) //returns true if the character can be in the body of a variable, function, or keyword name (by default letters, numbers, and underscore) - if(!isnum(char))char=text2ascii(char) - return CanStartID(char) || IsDigit(char) + return (char in ascii_A to ascii_Z) || (char in ascii_a to ascii_z) || char == ascii_UNDERSCORE || char == ascii_DOLLAR - IsDigit(char) - if(!isnum(char))char=text2ascii(char) - return char in ascii_ZERO to ascii_NINE +/datum/n_scriptOptions/proc/IsValidIDChar(char) //returns true if the character can be in the body of a variable, function, or keyword name (by default letters, numbers, and underscore) + if(!isnum(char)) + char = text2ascii(char) - IsValidID(id) //returns true if all the characters in the string are okay to be in an identifier name - if(!CanStartID(id)) //don't need to grab first char in id, since text2ascii does it automatically - return 0 - if(lentext(id)==1) return 1 - for(var/i=2 to lentext(id)) - if(!IsValidIDChar(copytext(id, i, i+1))) - return 0 - return 1 + return CanStartID(char) || IsDigit(char) + +/datum/n_scriptOptions/proc/IsDigit(char) + if(!isnum(char)) + char = text2ascii(char) + + return char in ascii_ZERO to ascii_NINE + +/datum/n_scriptOptions/proc/IsValidID(id) //returns true if all the characters in the string are okay to be in an identifier name + if(!CanStartID(id)) //don't need to grab first char in id, since text2ascii does it automatically + return 0 + + if(length(id) == 1) + return 1 + + for(var/i=2 to length(id)) + if(!IsValidIDChar(copytext(id, i, i + 1))) + return 0 + return 1 /* Class: nS_Options An implementation of for the n_Script language. */ - nS_Options - var - list - symbols = list("(", ")", "\[", "]", ";", ",", "{", "}") //scanner - Characters that can be in symbols +/datum/n_scriptOptions/nS_Options + var/list/symbols = list( + "(", + ")", + "\[", + "]", + ";", + ",", + "{", + "}" + ) //scanner - Characters that can be in symbols /* - Var: keywords - An associative list used by the parser to parse keywords. Indices are strings which will trigger the keyword when parsed and the - associated values are types of which the proc will be called. +Var: keywords +An associative list used by the parser to parse keywords. Indices are strings which will trigger the keyword when parsed and the +associated values are types of which the proc will be called. */ - keywords = list("if" = /n_Keyword/nS_Keyword/kwIf, "else" = /n_Keyword/nS_Keyword/kwElse, \ - "while" = /n_Keyword/nS_Keyword/kwWhile, "break" = /n_Keyword/nS_Keyword/kwBreak, \ - "continue" = /n_Keyword/nS_Keyword/kwContinue, \ - "return" = /n_Keyword/nS_Keyword/kwReturn, "def" = /n_Keyword/nS_Keyword/kwDef) + var/list/keywords = list( + "if" = /datum/n_Keyword/nS_Keyword/kwIf, + "else" = /datum/n_Keyword/nS_Keyword/kwElse, + "elseif" = /datum/n_Keyword/nS_Keyword/kwElseIf, + "while" = /datum/n_Keyword/nS_Keyword/kwWhile, + "break" = /datum/n_Keyword/nS_Keyword/kwBreak, + "continue" = /datum/n_Keyword/nS_Keyword/kwContinue, + "return" = /datum/n_Keyword/nS_Keyword/kwReturn, + "def" = /datum/n_Keyword/nS_Keyword/kwDef + ) - list - assign_operators=list("=" = null, "&=" = "&", - "|=" = "|", "`=" = "`", - "+=" = "+", "-=" = "-", - "*=" = "*", "/=" = "/", - "^=" = "^", - "%=" = "%") + var/list/assign_operators = list( + "=" = null, + "&=" = "&", + "|=" = "|", + "`=" = "`", + "+=" = "+", + "-=" = "-", + "*=" = "*", + "/=" = "/", + "^=" = "^", + "%=" = "%" + ) - unary_operators =list("!" = /node/expression/operator/unary/LogicalNot, "~" = /node/expression/operator/unary/BitwiseNot, - "-" = /node/expression/operator/unary/Minus) + var/list/unary_operators = list( + "!" = /datum/node/expression/operator/unary/LogicalNot, + "~" = /datum/node/expression/operator/unary/BitwiseNot, + "-" = /datum/node/expression/operator/unary/Minus + ) - binary_operators=list("==" = /node/expression/operator/binary/Equal, "!=" = /node/expression/operator/binary/NotEqual, - ">" = /node/expression/operator/binary/Greater, "<" = /node/expression/operator/binary/Less, - ">=" = /node/expression/operator/binary/GreaterOrEqual,"<=" = /node/expression/operator/binary/LessOrEqual, - "&&" = /node/expression/operator/binary/LogicalAnd, "||" = /node/expression/operator/binary/LogicalOr, - "&" = /node/expression/operator/binary/BitwiseAnd, "|" = /node/expression/operator/binary/BitwiseOr, - "`" = /node/expression/operator/binary/BitwiseXor, "+" = /node/expression/operator/binary/Add, - "-" = /node/expression/operator/binary/Subtract, "*" = /node/expression/operator/binary/Multiply, - "/" = /node/expression/operator/binary/Divide, "^" = /node/expression/operator/binary/Power, - "%" = /node/expression/operator/binary/Modulo) + var/list/binary_operators = list( + "==" = /datum/node/expression/operator/binary/Equal, + "!=" = /datum/node/expression/operator/binary/NotEqual, + ">" = /datum/node/expression/operator/binary/Greater, + "<" = /datum/node/expression/operator/binary/Less, + ">=" = /datum/node/expression/operator/binary/GreaterOrEqual, + "<=" = /datum/node/expression/operator/binary/LessOrEqual, + "&&" = /datum/node/expression/operator/binary/LogicalAnd, + "||" = /datum/node/expression/operator/binary/LogicalOr, + "&" = /datum/node/expression/operator/binary/BitwiseAnd, + "|" = /datum/node/expression/operator/binary/BitwiseOr, + "`" = /datum/node/expression/operator/binary/BitwiseXor, + "+" = /datum/node/expression/operator/binary/Add, + "-" = /datum/node/expression/operator/binary/Subtract, + "*" = /datum/node/expression/operator/binary/Multiply, + "/" = /datum/node/expression/operator/binary/Divide, + "^" = /datum/node/expression/operator/binary/Power, + "%" = /datum/node/expression/operator/binary/Modulo + ) - New() - .=..() - for(var/O in assign_operators+binary_operators+unary_operators) - if(!symbols.Find(O)) symbols+=O \ No newline at end of file +/datum/n_scriptOptions/nS_Options/New() + . = ..() + for(var/O in assign_operators + binary_operators + unary_operators) + if(!symbols.Find(O)) + symbols += O \ No newline at end of file diff --git a/code/modules/scripting/Parser/Expressions.dm b/code/modules/scripting/Parser/Expressions.dm index f27a30d3ad3..f0712fc5aa6 100644 --- a/code/modules/scripting/Parser/Expressions.dm +++ b/code/modules/scripting/Parser/Expressions.dm @@ -5,10 +5,10 @@ /* Macros: Expression Macros - OPERATOR - A value indicating the parser currently expects a binary operator. - VALUE - A value indicating the parser currently expects a value. - SHIFT - Tells the parser to push the current operator onto the stack. - REDUCE - Tells the parser to reduce the stack. + OPERATOR - A value indicating the parser currently expects a binary operator. + VALUE - A value indicating the parser currently expects a value. + SHIFT - Tells the parser to push the current operator onto the stack. + REDUCE - Tells the parser to reduce the stack. */ #define OPERATOR 1 #define VALUE 2 @@ -18,63 +18,71 @@ /* Class: nS_Parser */ -/n_Parser/nS_Parser - var +/datum/n_Parser/nS_Parser /* Var: expecting A variable which keeps track of whether an operator or value is expected. It should be either or . See for more information. */ - expecting=VALUE + var/expecting = VALUE - proc /* Proc: Precedence Compares two operators, decides which is higher in the order of operations, and returns or . */ - Precedence(node/expression/operator/top, node/expression/operator/input) - if(istype(top)) - top=top.precedence - if(istype(input)) - input=input:precedence - if(top>=input) - return REDUCE - return SHIFT +/datum/n_Parser/nS_Parser/proc/Precedence(var/datum/node/expression/operator/top, var/datum/node/expression/operator/input) + if(istype(top)) + top = top.precedence + + if(istype(input)) + + input = input:precedence + + if(top >= input) + return REDUCE + + return SHIFT /* Proc: GetExpression Takes a token expected to represent a value and returns an node. */ - GetExpression(token/T) - if(!T) return - if(istype(T, /node/expression)) - return T - switch(T.type) - if(/token/word) - return new/node/expression/value/variable(T.value) - if(/token/accessor) - var - token/accessor/A=T - node/expression/value/variable/E//=new(A.member) - stack/S=new() - while(istype(A.object, /token/accessor)) - S.Push(A) - A=A.object - ASSERT(istext(A.object)) +/datum/n_Parser/nS_Parser/proc/GetExpression(var/datum/token/T) + if(!T) + return - while(A) - var/node/expression/value/variable/V=new() - V.id=new(A.member) - if(E) - V.object=E - else - V.object=new/node/identifier(A.object) - E=V - A=S.Pop() - return E + if(istype(T, /datum/node/expression)) + return T - if(/token/number, /token/string) - return new/node/expression/value/literal(T.value) + switch(T.type) + if(/datum/token/word) + return new/datum/node/expression/value/variable(T.value) + + if(/datum/token/accessor) + var/datum/token/accessor/A = T + var/datum/node/expression/value/variable/E// = new(A.member) + var/datum/stack/S = new() + + while(istype(A.object, /datum/token/accessor)) + S.Push(A) + A = A.object + + ASSERT(istext(A.object)) + + while(A) + var/datum/node/expression/value/variable/V = new() + V.id = new(A.member) + if(E) + V.object = E + else + V.object = new/datum/node/identifier(A.object) + + E = V + A = S.Pop() + return E + + if(/datum/token/number, /datum/token/string) + return new/datum/node/expression/value/literal(T.value) /* Proc: GetOperator @@ -91,15 +99,26 @@ - - */ - GetOperator(O, type=/node/expression/operator, L[]) - if(istype(O, type)) return O //O is already the desired type - if(istype(O, /token)) O=O:value //sets O to text - if(istext(O)) //sets O to path - if(L.Find(O)) O=L[O] - else return null - if(ispath(O))O=new O //catches path from last check - else return null //Unknown type - return O +/datum/n_Parser/nS_Parser/proc/GetOperator(O, type = /datum/node/expression/operator, L[]) + if(istype(O, type)) + return O //O is already the desired type + + if(istype(O, /datum/token)) + O = O:value //sets O to text + + if(istext(O)) //sets O to path + if(L.Find(O)) + O = L[O] + else + return null + + if(ispath(O)) + O = new O //catches path from last check + + else + return null //Unknown type + + return O /* Proc: GetBinaryOperator @@ -110,8 +129,8 @@ - - */ - GetBinaryOperator(O) - return GetOperator(O, /node/expression/operator/binary, options.binary_operators) +/datum/n_Parser/nS_Parser/proc/GetBinaryOperator(O) + return GetOperator(O, /datum/node/expression/operator/binary, options.binary_operators) /* Proc: GetUnaryOperator @@ -122,30 +141,34 @@ - - */ - GetUnaryOperator(O) - return GetOperator(O, /node/expression/operator/unary, options.unary_operators) +/datum/n_Parser/nS_Parser/proc/GetUnaryOperator(O) + return GetOperator(O, /datum/node/expression/operator/unary, options.unary_operators) /* Proc: Reduce Takes the operator on top of the opr stack and assigns its operand(s). Then this proc pushes the value of that operation to the top of the val stack. */ - Reduce(stack/opr, stack/val) - var/node/expression/operator/O=opr.Pop() - if(!O) return - if(!istype(O)) - errors+=new/scriptError("Error reducing expression - invalid operator.") - return - //Take O and assign its operands, popping one or two values from the val stack - //depending on whether O is a binary or unary operator. - if(istype(O, /node/expression/operator/binary)) - var/node/expression/operator/binary/B=O - B.exp2=val.Pop() - B.exp =val.Pop() - val.Push(B) - else - O.exp=val.Pop() - val.Push(O) +/datum/n_Parser/nS_Parser/proc/Reduce(var/datum/stack/opr, var/datum/stack/val) + var/datum/node/expression/operator/O = opr.Pop() + if(!O) + return + + if(!istype(O)) + errors += new/datum/scriptError("Error reducing expression - invalid operator.") + return + + //Take O and assign its operands, popping one or two values from the val stack + //depending on whether O is a binary or unary operator. + if(istype(O, /datum/node/expression/operator/binary)) + var/datum/node/expression/operator/binary/B=O + B.exp2 = val.Pop() + B.exp = val.Pop() + val.Push(B) + + else + O.exp=val.Pop() + val.Push(O) /* Proc: EndOfExpression @@ -154,14 +177,14 @@ Parameters: end - A list of values to compare the current token to. */ - EndOfExpression(end[]) - if(!curToken) - return 1 - if(istype(curToken, /token/symbol) && end.Find(curToken.value)) - return 1 - if(istype(curToken, /token/end) && end.Find(/token/end)) - return 1 - return 0 +/datum/n_Parser/nS_Parser/proc/EndOfExpression(end[]) + if(!curToken) + return 1 + if(istype(curToken, /datum/token/symbol) && end.Find(curToken.value)) + return 1 + if(istype(curToken, /datum/token/end) && end.Find(/datum/token/end)) + return 1 + return 0 /* Proc: ParseExpression @@ -180,89 +203,114 @@ - - */ - ParseExpression(list/end=list(/token/end), list/ErrChars=list("{", "}")) - var/stack - opr=new - val=new - src.expecting=VALUE - for() - if(EndOfExpression(end)) - break - if(istype(curToken, /token/symbol) && ErrChars.Find(curToken.value)) - errors+=new/scriptError/BadToken(curToken) - break +/datum/n_Parser/nS_Parser/proc/ParseExpression(var/list/end = list(/datum/token/end), list/ErrChars = list("{", "}"), check_functions = 0) + var/datum/stack/opr = new + var/datum/stack/val = new + src.expecting = VALUE + var/loop = 0 + for() + loop++ + if(loop > 800) + errors += new/datum/scriptError("Too many nested tokens.") + return - if(index>tokens.len) //End of File - errors+=new/scriptError/EndOfFile() - break - var/token/ntok - if(index+1<=tokens.len) - ntok=tokens[index+1] + if(EndOfExpression(end)) + break - if(istype(curToken, /token/symbol) && curToken.value=="(") //Parse parentheses expression - if(expecting!=VALUE) - errors+=new/scriptError/ExpectedToken("operator", curToken) - NextToken() - continue - val.Push(ParseParenExpression()) - else if(istype(curToken, /token/symbol)) //Operator found. - var/node/expression/operator/curOperator //Figure out whether it is unary or binary and get a new instance. - if(src.expecting==OPERATOR) - curOperator=GetBinaryOperator(curToken) - if(!curOperator) - errors+=new/scriptError/ExpectedToken("operator", curToken) - NextToken() - continue - else - curOperator=GetUnaryOperator(curToken) - if(!curOperator) //given symbol isn't a unary operator - errors+=new/scriptError/ExpectedToken("expression", curToken) - NextToken() - continue + if(istype(curToken, /datum/token/symbol) && ErrChars.Find(curToken.value)) + errors += new/datum/scriptError/BadToken(curToken) + break - if(opr.Top() && Precedence(opr.Top(), curOperator)==REDUCE) //Check order of operations and reduce if necessary - Reduce(opr, val) - continue - opr.Push(curOperator) - src.expecting=VALUE - else if(ntok && ntok.value=="(" && istype(ntok, /token/symbol)\ - && istype(curToken, /token/word)) //Parse function call - var/token/preToken=curToken - var/old_expect=src.expecting - var/fex=ParseFunctionExpression() - if(old_expect!=VALUE) - errors+=new/scriptError/ExpectedToken("operator", preToken) - NextToken() - continue - val.Push(fex) - else if(istype(curToken, /token/keyword)) //inline keywords - var/n_Keyword/kw=options.keywords[curToken.value] - kw=new kw(inline=1) - if(kw) - if(!kw.Parse(src)) - return - else - errors+=new/scriptError/BadToken(curToken) - else if(istype(curToken, /token/end)) //semicolon found where it wasn't expected - errors+=new/scriptError/BadToken(curToken) + if(index > tokens.len) //End of File + errors += new/datum/scriptError/EndOfFile() + break + + var/datum/token/ntok + if(index + 1 <= tokens.len) + ntok = tokens[index + 1] + + if(istype(curToken, /datum/token/symbol) && curToken.value == "(") //Parse parentheses expression + if(expecting != VALUE) + errors += new/datum/scriptError/ExpectedToken("operator", curToken) + NextToken() + continue + + val.Push(ParseParenExpression()) + + else if(istype(curToken, /datum/token/symbol)) //Operator found. + var/datum/node/expression/operator/curOperator //Figure out whether it is unary or binary and get a new instance. + if(src.expecting == OPERATOR) + curOperator = GetBinaryOperator(curToken) + if(!curOperator) + errors += new/datum/scriptError/ExpectedToken("operator", curToken) + NextToken() + continue + else + curOperator = GetUnaryOperator(curToken) + if(!curOperator) //given symbol isn't a unary operator + errors += new/datum/scriptError/ExpectedToken("expression", curToken) NextToken() continue - else - if(expecting!=VALUE) - errors+=new/scriptError/ExpectedToken("operator", curToken) - NextToken() - continue - val.Push(GetExpression(curToken)) - src.expecting=OPERATOR - NextToken() - while(opr.Top()) Reduce(opr, val) //Reduce the value stack completely - .=val.Pop() //Return what should be the last value on the stack - if(val.Top()) // - var/node/N=val.Pop() - errors+=new/scriptError("Error parsing expression. Unexpected value left on stack: [N.ToString()].") - return null + if(opr.Top() && Precedence(opr.Top(), curOperator) == REDUCE) //Check order of operations and reduce if necessary + Reduce(opr, val) + continue + + opr.Push(curOperator) + src.expecting = VALUE + + else if(ntok && ntok.value == "(" && istype(ntok, /datum/token/symbol)\ + && istype(curToken, /datum/token/word)) //Parse function call + + if(!check_functions) + + var/datum/token/preToken = curToken + var/old_expect = src.expecting + var/fex = ParseFunctionExpression() + if(old_expect != VALUE) + errors += new/datum/scriptError/ExpectedToken("operator", preToken) + NextToken() + continue + + val.Push(fex) + else + errors += new/datum/scriptError/ParameterFunction(curToken) + break + + else if(istype(curToken, /datum/token/keyword)) //inline keywords + var/datum/n_Keyword/kw = options.keywords[curToken.value] + kw = new kw(inline=1) + if(kw) + if(!kw.Parse(src)) + return + else + errors += new/datum/scriptError/BadToken(curToken) + + else if(istype(curToken, /datum/token/end)) //semicolon found where it wasn't expected + errors += new/datum/scriptError/BadToken(curToken) + NextToken() + continue + else + if(expecting != VALUE) + errors += new/datum/scriptError/ExpectedToken("operator", curToken) + NextToken() + continue + + val.Push(GetExpression(curToken)) + src.expecting = OPERATOR + + NextToken() + + while(opr.Top()) + Reduce(opr, val) + //Reduce the value stack completely + . = val.Pop() //Return what should be the last value on the stack + + if(val.Top()) // + var/datum/node/N = val.Pop() + errors += new/datum/scriptError("Error parsing expression. Unexpected value left on stack: [N.ToString()].") + return null /* Proc: ParseFunctionExpression @@ -271,25 +319,33 @@ See Also: - */ - ParseFunctionExpression() - var/node/expression/FunctionCall/exp=new - exp.func_name=curToken.value - NextToken() //skip function name - NextToken() //skip open parenthesis, already found - var/loops = 0 - for() - loops++ - if(loops>=1000) - CRASH("Something TERRIBLE has gone wrong in ParseFunctionExpression ;__;") +/datum/n_Parser/nS_Parser/proc/ParseFunctionExpression() + var/datum/node/expression/FunctionCall/exp = new + exp.func_name = curToken.value + NextToken() //skip function name + NextToken() //skip open parenthesis, already found + var/loops = 0 - if(istype(curToken, /token/symbol) && curToken.value==")") - return exp - exp.parameters+=ParseParamExpression() - if(curToken.value==","&&istype(curToken, /token/symbol))NextToken() //skip comma - if(istype(curToken, /token/end)) //Prevents infinite loop... - errors+=new/scriptError/ExpectedToken(")") - return exp + for() + loops++ + if(loops >= 800) + errors += new/datum/scriptError("Too many nested expressions.") + break + //CRASH("Something TERRIBLE has gone wrong in ParseFunctionExpression ;__;") + + if(istype(curToken, /datum/token/symbol) && curToken.value == ")") + return exp + exp.parameters += ParseParamExpression() + if(errors.len) + return exp + + if(curToken.value == "," && istype(curToken, /datum/token/symbol)) + NextToken() //skip comma + + if(istype(curToken, /datum/token/end)) //Prevents infinite loop... + errors += new/datum/scriptError/ExpectedToken(")") + return exp /* Proc: ParseParenExpression @@ -298,10 +354,10 @@ See Also: - */ - ParseParenExpression() - if(!CheckToken("(", /token/symbol)) - return - return new/node/expression/operator/unary/group(ParseExpression(list(")"))) +/datum/n_Parser/nS_Parser/proc/ParseParenExpression() + if(!CheckToken("(", /datum/token/symbol)) + return + return new/datum/node/expression/operator/unary/group(ParseExpression(list(")"))) /* Proc: ParseParamExpression @@ -310,5 +366,6 @@ See Also: - */ - ParseParamExpression() - return ParseExpression(list(",", ")")) \ No newline at end of file +/datum/n_Parser/nS_Parser/proc/ParseParamExpression(var/check_functions = 0) + var/cf = check_functions + return ParseExpression(list(",", ")"), check_functions = cf) \ No newline at end of file diff --git a/code/modules/scripting/Parser/Keywords.dm b/code/modules/scripting/Parser/Keywords.dm index e39ee506857..a4470242f5e 100644 --- a/code/modules/scripting/Parser/Keywords.dm +++ b/code/modules/scripting/Parser/Keywords.dm @@ -12,17 +12,17 @@ var/const/KW_WARN = 3 //Warning var/const/Class: n_Keyword var/const/Represents a special statement in the code triggered by a keyword. */ -/n_Keyword - New(inline=0) - src.inline=inline - return ..() - +/datum/n_Keyword /* Var: inline 1 if the keyword is in an expression (e.g. the new keyword in many languages), 0 otherwise (such as the if and else keywords). */ var/inline +/datum/n_Keyword/New(inline = 0) + src.inline = inline + return ..() + /* Proc: Parse Called when the parser finds a keyword in the code. @@ -31,8 +31,8 @@ var/const/Represents a special statement in the code triggered by a keyword. parser - The parser that created this object. You can use the parameter to manipulate the parser in order to add statements and blocks to its AST. */ - proc/Parse(n_Parser/parser) - +/datum/n_Keyword/proc/Parse(var/datum/n_Parser/parser) + return /* Class: nS_Keyword A keyword in n_Script. By default these include return, if, else, while, and def. To enable or disable a keyword, change the @@ -42,125 +42,163 @@ var/const/Represents a special statement in the code triggered by a keyword. When a parser is expecting a new statement, and a keyword listed in is found, it will call the keyword's proc. */ -// - nS_Keyword - New(inline=0) - if(inline) - del(src) +/datum/n_Keyword/nS_Keyword/New(var/inline = 0) + if(inline) + del src - kwReturn - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - if(istype(parser.curBlock, /node/BlockDefinition/GlobalBlock)) - parser.errors+=new/scriptError/BadReturn(parser.curToken) - . = KW_WARN - var/node/statement/ReturnStatement/stmt=new - parser.NextToken() //skip 'return' token - stmt.value=parser.ParseExpression() - parser.curBlock.statements+=stmt +/datum/n_Keyword/nS_Keyword/kwReturn/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + if(istype(parser.curBlock, /datum/node/BlockDefinition/GlobalBlock)) // Exit out of the program by setting the tokens list size to the same as index. + parser.tokens.len = parser.index + return - kwIf - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - var/node/statement/IfStatement/stmt=new - parser.NextToken() //skip 'if' token - stmt.cond=parser.ParseParenExpression() - if(!parser.CheckToken(")", /token/symbol)) - return KW_FAIL - if(!parser.CheckToken("{", /token/symbol, skip=0)) //Token needs to be preserved for parse loop, so skip=0 - return KW_ERR - parser.curBlock.statements+=stmt - stmt.block=new - parser.AddBlock(stmt.block) + var/datum/node/statement/ReturnStatement/stmt = new + parser.NextToken() //skip 'return' token + stmt.value = parser.ParseExpression() + parser.curBlock.statements += stmt - kwElse - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - var/list/L=parser.curBlock.statements - var/node/statement/IfStatement/stmt - if(L&&L.len) stmt=L[L.len] //Get the last statement in the current block - if(!stmt || !istype(stmt) || stmt.else_block) //Ensure that it is an if statement - parser.errors+=new/scriptError/ExpectedToken("if statement",parser.curToken) - return KW_FAIL - parser.NextToken() //skip 'else' token - if(!parser.CheckToken("{", /token/symbol, skip=0)) - return KW_ERR - stmt.else_block=new() - parser.AddBlock(stmt.else_block) +/datum/n_Keyword/nS_Keyword/kwIf/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + var/datum/node/statement/IfStatement/stmt = new + parser.NextToken() //skip 'if' token + stmt.cond = parser.ParseParenExpression() + if(!parser.CheckToken(")", /datum/token/symbol)) + return KW_FAIL - kwWhile - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - var/node/statement/WhileLoop/stmt=new - parser.NextToken() //skip 'while' token - stmt.cond=parser.ParseParenExpression() - if(!parser.CheckToken(")", /token/symbol)) - return KW_FAIL - if(!parser.CheckToken("{", /token/symbol, skip=0)) - return KW_ERR - parser.curBlock.statements+=stmt - stmt.block=new - parser.AddBlock(stmt.block) + if(!parser.CheckToken("{", /datum/token/symbol, skip=0)) //Token needs to be preserved for parse loop, so skip=0 + return KW_ERR - kwBreak - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - if(istype(parser.curBlock, /node/BlockDefinition/GlobalBlock)) - parser.errors+=new/scriptError/BadToken(parser.curToken) - . = KW_WARN - var/node/statement/BreakStatement/stmt=new - parser.NextToken() //skip 'break' token - parser.curBlock.statements+=stmt + parser.curBlock.statements += stmt + stmt.block = new + parser.AddBlock(stmt.block) - kwContinue - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - if(istype(parser.curBlock, /node/BlockDefinition/GlobalBlock)) - parser.errors+=new/scriptError/BadToken(parser.curToken) - . = KW_WARN - var/node/statement/ContinueStatement/stmt=new - parser.NextToken() //skip 'break' token - parser.curBlock.statements+=stmt +/datum/n_Keyword/nS_Keyword/kwElseIf/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + var/list/L = parser.curBlock.statements + var/datum/node/statement/IfStatement/ifstmt - kwDef - Parse(n_Parser/nS_Parser/parser) - .=KW_PASS - var/node/statement/FunctionDefinition/def=new - parser.NextToken() //skip 'def' token - if(!parser.options.IsValidID(parser.curToken.value)) - parser.errors+=new/scriptError/InvalidID(parser.curToken) - return KW_FAIL - def.func_name=parser.curToken.value - parser.NextToken() - if(!parser.CheckToken("(", /token/symbol)) - return KW_FAIL - for() //for now parameters can be separated by whitespace - they don't need a comma in between - if(istype(parser.curToken, /token/symbol)) - switch(parser.curToken.value) - if(",") - parser.NextToken() - if(")") - break - else - parser.errors+=new/scriptError/BadToken(parser.curToken) - return KW_ERR + if(L && L.len) + ifstmt = L[L.len] //Get the last statement in the current block - else if(istype(parser.curToken, /token/word)) - def.parameters+=parser.curToken.value - parser.NextToken() - else - parser.errors+=new/scriptError/InvalidID(parser.curToken) - return KW_ERR - if(!parser.CheckToken(")", /token/symbol)) - return KW_FAIL + if(!ifstmt || !istype(ifstmt) || ifstmt.else_if) + usr << "NTSL: ELSE IF FAILED: [!ifstmt], [!istype(ifstmt)], [!istype(ifstmt) || ifstmt.else_if]" // Usr is unsafe as SHIT but JUST incase I forget this debug line like the fucking asset cache... + parser.errors += new/datum/scriptError/ExpectedToken("if statement", parser.curToken) + return KW_FAIL - if(istype(parser.curToken, /token/end)) //Function prototype - parser.curBlock.statements+=def - else if(parser.curToken.value=="{" && istype(parser.curToken, /token/symbol)) - def.block = new - parser.curBlock.statements+=def - parser.curBlock.functions[def.func_name]=def - parser.AddBlock(def.block) + var/datum/node/statement/IfStatement/ElseIf/stmt = new + parser.NextToken() //skip 'if' token + stmt.cond = parser.ParseParenExpression() + if(!parser.CheckToken(")", /datum/token/symbol)) + return KW_FAIL + + if(!parser.CheckToken("{", /datum/token/symbol, skip = 0)) //Token needs to be preserved for parse loop, so skip=0 + return KW_ERR + + parser.curBlock.statements += stmt + stmt.block = new + ifstmt.else_if = stmt + parser.AddBlock(stmt.block) + +/datum/n_Keyword/nS_Keyword/kwElse/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + var/list/L = parser.curBlock.statements + var/datum/node/statement/IfStatement/stmt + + if(L && L.len) + stmt = L[L.len] //Get the last statement in the current block + + if(!stmt || !istype(stmt) || stmt.else_block) //Ensure that it is an if statement + usr << "NTSL: ELSE IF FAILED: [!stmt], [!istype(stmt)], [!istype(stmt) || stmt.else_block]" // Usr is unsafe as SHIT but JUST incase I forget this debug line like the fucking asset cache... + parser.errors += new/datum/scriptError/ExpectedToken("if statement", parser.curToken) + return KW_FAIL + + parser.NextToken() //skip 'else' token + if(!parser.CheckToken("{", /datum/token/symbol, skip = 0)) + return KW_ERR + + stmt.else_block = new() + parser.AddBlock(stmt.else_block) + +/datum/n_Keyword/nS_Keyword/kwWhile/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + var/datum/node/statement/WhileLoop/stmt = new + parser.NextToken() //skip 'while' token + stmt.cond = parser.ParseParenExpression() + if(!parser.CheckToken(")", /datum/token/symbol)) + return KW_FAIL + + if(!parser.CheckToken("{", /datum/token/symbol, skip=0)) + return KW_ERR + + parser.curBlock.statements += stmt + stmt.block = new + parser.AddBlock(stmt.block) + +/datum/n_Keyword/nS_Keyword/kwBreak/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + if(istype(parser.curBlock, /datum/node/BlockDefinition/GlobalBlock)) + parser.errors += new/datum/scriptError/BadToken(parser.curToken) + . = KW_WARN + + var/datum/node/statement/BreakStatement/stmt = new + parser.NextToken() //skip 'break' token + parser.curBlock.statements += stmt + +/datum/n_Keyword/nS_Keyword/kwContinue/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + if(istype(parser.curBlock, /datum/node/BlockDefinition/GlobalBlock)) + parser.errors += new/datum/scriptError/BadToken(parser.curToken) + . = KW_WARN + + var/datum/node/statement/ContinueStatement/stmt = new + parser.NextToken() //skip 'break' token + parser.curBlock.statements += stmt + +/datum/n_Keyword/nS_Keyword/kwDef/Parse(var/datum/n_Parser/nS_Parser/parser) + . = KW_PASS + var/datum/node/statement/FunctionDefinition/def = new + parser.NextToken() //skip 'def' token + + if(!parser.options.IsValidID(parser.curToken.value)) + parser.errors += new/datum/scriptError/InvalidID(parser.curToken) + return KW_FAIL + + def.func_name = parser.curToken.value + parser.NextToken() + + if(!parser.CheckToken("(", /datum/token/symbol)) + return KW_FAIL + + for() //for now parameters can be separated by whitespace - they don't need a comma in between + if(istype(parser.curToken, /datum/token/symbol)) + switch(parser.curToken.value) + if(",") + parser.NextToken() + if(")") + break else - parser.errors+=new/scriptError/BadToken(parser.curToken) - return KW_FAIL + parser.errors += new/datum/scriptError/BadToken(parser.curToken) + return KW_ERR + + else if(istype(parser.curToken, /datum/token/word)) + def.parameters += parser.curToken.value + parser.NextToken() + + else + parser.errors += new/datum/scriptError/InvalidID(parser.curToken) + return KW_ERR + + if(!parser.CheckToken(")", /datum/token/symbol)) + return KW_FAIL + + if(istype(parser.curToken, /datum/token/end)) //Function prototype + parser.curBlock.statements += def + + else if(parser.curToken.value == "{" && istype(parser.curToken, /datum/token/symbol)) + def.block = new + parser.curBlock.statements += def + parser.curBlock.functions[def.func_name] = def + parser.AddBlock(def.block) + else + parser.errors += new/datum/scriptError/BadToken(parser.curToken) + return KW_FAIL diff --git a/code/modules/scripting/Parser/Parser.dm b/code/modules/scripting/Parser/Parser.dm index ad961c755f0..d9c737e7ea8 100644 --- a/code/modules/scripting/Parser/Parser.dm +++ b/code/modules/scripting/Parser/Parser.dm @@ -5,19 +5,17 @@ Class: n_Parser An object that reads tokens and produces an AST (abstract syntax tree). */ -/n_Parser - var +/datum/n_Parser /* Var: index The parser's current position in the token's list. */ - index = 1 - list + var/index = 1 /* Var: tokens A list of tokens in the source code generated by a scanner. */ - tokens = new + var/list/tokens = new /* Var: errors A list of fatal errors found by the parser. If there are any items in this list, then it is not safe to run the returned AST. @@ -25,48 +23,44 @@ See Also: - */ - errors = new + var/list/errors = new /* Var: warnings A list of non-fatal problems in the script. */ - warnings = new - token + var/list/warnings = new /* Var: curToken The token at in . */ - curToken - stack - blocks=new - node/BlockDefinition - GlobalBlock/global_block=new - curBlock + var/datum/token/curToken + var/datum/stack/blocks = new + var/datum/node/BlockDefinition/GlobalBlock/global_block = new + var/datum/node/BlockDefinition/GlobalBlock/curBlock - proc /* Proc: Parse Reads the tokens and returns the AST's node. Be sure to populate the tokens list before calling this procedure. */ - Parse() - +/datum/n_Parser/proc/Parse() + return /* Proc: NextToken Sets to the next token in the list, or null if there are no more tokens. */ - NextToken() - if(index>=tokens.len) - curToken=null - else - curToken=tokens[++index] - return curToken +/datum/n_Parser/proc/NextToken() + if(index >= tokens.len) + curToken = null + else + curToken = tokens[++index] + return curToken /* Class: nS_Parser An implmentation of a parser for n_Script. */ -/n_Parser/nS_Parser - var/n_scriptOptions/nS_Options/options +/datum/n_Parser/nS_Parser + var/datum/n_scriptOptions/nS_Options/options /* Constructor: New @@ -74,116 +68,138 @@ tokens - A list of tokens to parse. options - An object used for configuration. */ - New(tokens[], n_scriptOptions/options) - src.tokens=tokens - src.options=options - curBlock=global_block - return ..() +/datum/n_Parser/nS_Parser/New(tokens[], var/datum/n_scriptOptions/options) + src.tokens = tokens + src.options = options + curBlock = global_block + return ..() - Parse() - ASSERT(tokens) - for(,src.index<=src.tokens.len, src.index++) - curToken=tokens[index] - switch(curToken.type) - if(/token/keyword) - var/n_Keyword/kw=options.keywords[curToken.value] - kw=new kw() - if(kw) - if(!kw.Parse(src)) - return - if(/token/word) - var/token/ntok - if(index+1>tokens.len) - errors+=new/scriptError/BadToken(curToken) - continue - ntok=tokens[index+1] - if(!istype(ntok, /token/symbol)) - errors+=new/scriptError/BadToken(ntok) - continue - if(ntok.value=="(") - ParseFunctionStatement() - else if(options.assign_operators.Find(ntok.value)) - ParseAssignment() - else - errors+=new/scriptError/BadToken(ntok) - continue - if(!istype(curToken, /token/end)) - errors+=new/scriptError/ExpectedToken(";", curToken) - continue - if(/token/symbol) - if(curToken.value=="}") - if(!EndBlock()) - errors+=new/scriptError/BadToken(curToken) - continue - else - errors+=new/scriptError/BadToken(curToken) - continue - if(/token/end) - warnings+=new/scriptError/BadToken(curToken) +/datum/n_Parser/nS_Parser/Parse() + ASSERT(tokens) + for(,src.index <= src.tokens.len, src.index++) + curToken = tokens[index] + switch(curToken.type) + if(/datum/token/keyword) + var/datum/n_Keyword/kw = options.keywords[curToken.value] + kw = new kw() + if(kw) + if(!kw.Parse(src)) + return + + if(/datum/token/word) + var/datum/token/ntok + if(index + 1 > tokens.len) + errors += new/datum/scriptError/BadToken(curToken) continue + + ntok = tokens[index + 1] + + if(!istype(ntok, /datum/token/symbol)) + errors += new/datum/scriptError/BadToken(ntok) + continue + + if(ntok.value == "(") + ParseFunctionStatement() + + else if(options.assign_operators.Find(ntok.value)) + ParseAssignment() + else - errors+=new/scriptError/BadToken(curToken) - return - return global_block + errors += new/datum/scriptError/BadToken(ntok) + continue - proc - CheckToken(val, type, err=1, skip=1) - if(curToken.value!=val || !istype(curToken,type)) - if(err) - errors+=new/scriptError/ExpectedToken(val, curToken) - return 0 - if(skip)NextToken() - return 1 + if(!istype(curToken, /datum/token/end)) + errors += new/datum/scriptError/ExpectedToken(";", curToken) + continue - AddBlock(node/BlockDefinition/B) - blocks.Push(curBlock) - curBlock=B + if(/datum/token/symbol) + if(curToken.value == "}") + if(!EndBlock()) + errors += new/datum/scriptError/BadToken(curToken) + continue - EndBlock() - if(curBlock==global_block) return 0 - curBlock=blocks.Pop() - return 1 + else + errors += new/datum/scriptError/BadToken(curToken) + continue + + if(/datum/token/end) + warnings += new/datum/scriptError/BadToken(curToken) + continue - ParseAssignment() - var/name=curToken.value - if(!options.IsValidID(name)) - errors+=new/scriptError/InvalidID(curToken) - return - NextToken() - var/t=options.binary_operators[options.assign_operators[curToken.value]] - var/node/statement/VariableAssignment/stmt=new() - stmt.var_name=new(name) - NextToken() - if(t) - stmt.value=new t() - stmt.value:exp=new/node/expression/value/variable(stmt.var_name) - stmt.value:exp2=ParseExpression() else - stmt.value=ParseExpression() - curBlock.statements+=stmt - - ParseFunctionStatement() - if(!istype(curToken, /token/word)) - errors+=new/scriptError("Bad identifier in function call.") + errors += new/datum/scriptError/BadToken(curToken) return - var/node/statement/FunctionCall/stmt=new - stmt.func_name=curToken.value - NextToken() //skip function name - if(!CheckToken("(", /token/symbol)) //Check for and skip open parenthesis - return - var/loops = 0 - for() - loops++ - if(loops>=6000) - CRASH("Something TERRIBLE has gone wrong in ParseFunctionStatement ;__;") - if(!curToken) - errors+=new/scriptError/EndOfFile() - return - if(istype(curToken, /token/symbol) && curToken.value==")") - curBlock.statements+=stmt - NextToken() //Skip close parenthesis - return - var/node/expression/P=ParseParamExpression() - stmt.parameters+=P - if(istype(curToken, /token/symbol) && curToken.value==",") NextToken() \ No newline at end of file + return global_block + +/datum/n_Parser/nS_Parser/proc/CheckToken(val, type, err = 1, skip = 1) + if(curToken.value != val || !istype(curToken, type)) + if(err) + errors += new/datum/scriptError/ExpectedToken(val, curToken) + return 0 + if(skip) + NextToken() + + return 1 + +/datum/n_Parser/nS_Parser/proc/AddBlock(var/datum/node/BlockDefinition/B) + blocks.Push(curBlock) + curBlock = B + +/datum/n_Parser/nS_Parser/proc/EndBlock() + if(curBlock == global_block) + return 0 + + curBlock = blocks.Pop() + return 1 + +/datum/n_Parser/nS_Parser/proc/ParseAssignment() + var/name = curToken.value + if(!options.IsValidID(name)) + errors += new/datum/scriptError/InvalidID(curToken) + return + + NextToken() + var/t = options.binary_operators[options.assign_operators[curToken.value]] + var/datum/node/statement/VariableAssignment/stmt = new() + stmt.var_name = new(name) + NextToken() + + if(t) + stmt.value = new t() + stmt.value:exp = new/datum/node/expression/value/variable(stmt.var_name) + stmt.value:exp2 = ParseExpression() + else + stmt.value = ParseExpression() + + curBlock.statements += stmt + +/datum/n_Parser/nS_Parser/proc/ParseFunctionStatement() + if(!istype(curToken, /datum/token/word)) + errors += new/datum/scriptError("Bad identifier in function call.") + return + + var/datum/node/statement/FunctionCall/stmt=new + stmt.func_name = curToken.value + NextToken() //skip function name + if(!CheckToken("(", /datum/token/symbol)) //Check for and skip open parenthesis + return + var/loops = 0 + for() + loops++ + if(loops >= 800) + errors +=new/datum/scriptError("Cannot find ending params.") + return + + if(!curToken) + errors+=new/datum/scriptError/EndOfFile() + return + if(istype(curToken, /datum/token/symbol) && curToken.value == ")") + curBlock.statements += stmt + NextToken() //Skip close parenthesis + return + + var/datum/node/expression/P = ParseParamExpression(check_functions = 1) + stmt.parameters += P + if(istype(curToken, /datum/token/symbol) && curToken.value == ",") + NextToken() diff --git a/code/modules/scripting/Scanner/Scanner.dm b/code/modules/scripting/Scanner/Scanner.dm index a667becea17..011621c8ea8 100644 --- a/code/modules/scripting/Scanner/Scanner.dm +++ b/code/modules/scripting/Scanner/Scanner.dm @@ -5,10 +5,8 @@ Class: n_Scanner An object responsible for breaking up source code into tokens for use by the parser. */ -/n_Scanner - var - code - list +/datum/n_Scanner + var/code /* Var: errors A list of fatal errors found by the scanner. If there are any items in this list, then it is not safe to parse the returned tokens. @@ -16,54 +14,50 @@ See Also: - */ - errors = new + var/list/errors = new /* Var: warnings A list of non-fatal problems in the source code found by the scanner. */ - warnings = new + var/list/warnings = new - proc /* Proc: LoadCode Loads source code. */ - LoadCode(c) - code=c +/datum/n_Scanner/proc/LoadCode(var/c) + code=c /* Proc: LoadCodeFromFile Gets the code from a file and calls . */ - LoadCodeFromFile(f) - LoadCode(file2text(f)) +/datum/n_Scanner/proc/LoadCodeFromFile(var/f) + LoadCode(file2text(f)) /* Proc: Scan Runs the scanner and returns the resulting list of tokens. Ensure that has been called first. */ - Scan() +/datum/n_Scanner/proc/Scan() /* Class: nS_Scanner A scanner implementation for n_Script. */ -/n_Scanner/nS_Scanner - - var +/datum/n_Scanner/nS_Scanner /* Variable: codepos The scanner's position in the source code. */ - codepos = 1 - line = 1 - linepos = 0 //column=codepos-linepos - n_scriptOptions/nS_Options/options + var/codepos = 1 + var/line = 1 + var/linepos = 0 //column=codepos-linepos + var/datum/n_scriptOptions/nS_Options/options - commenting = 0 + var/commenting = 0 // 1: single-line // 2: multi-line - list /* Variable: ignore A list of characters that are ignored by the scanner. @@ -71,7 +65,7 @@ Default Value: Whitespace */ - ignore = list(" ", "\t", "\n") //Don't add tokens for whitespace + var/list/ignore = list(" ", "\t", "\n") //Don't add tokens for whitespace /* Variable: end_stmt A list of characters that end a statement. Each item may only be one character long. @@ -79,7 +73,7 @@ Default Value: Semicolon */ - end_stmt = list(";") + var/list/end_stmt = list(";") /* Variable: string_delim A list of characters that can start and end strings. @@ -87,12 +81,12 @@ Default Value: Double and single quotes. */ - string_delim = list("\"", "'") + var/list/string_delim = list("\"", "'") /* Variable: delim A list of characters that denote the start of a new token. This list is automatically populated. */ - delim = new + var/list/delim = new /* Macro: COL @@ -106,46 +100,52 @@ code - The source code to tokenize. options - An object used to configure the scanner. */ - New(code, n_scriptOptions/nS_Options/options) - .=..() - ignore+= ascii2text(13) //Carriage return - delim += ignore + options.symbols + end_stmt + string_delim - src.options=options - LoadCode(code) +/datum/n_Scanner/nS_Scanner/New(var/code, var/datum/n_scriptOptions/nS_Options/options) + . = ..() + ignore += ascii2text(13) //Carriage return + delim += ignore + options.symbols + end_stmt + string_delim + src.options = options + LoadCode(code) - Scan() //Creates a list of tokens from source code - var/list/tokens=new - for(, src.codepos<=lentext(code), src.codepos++) +/datum/n_Scanner/nS_Scanner/Scan() //Creates a list of tokens from source code + var/list/tokens = new + for(, src.codepos <= length(code), src.codepos++) - var/char=copytext(code, codepos, codepos+1) - var/nextchar=copytext(code, codepos+1, codepos+2) - if(char=="\n") - line++ - linepos=codepos + var/char = copytext(code, codepos, codepos + 1) + var/nextchar = copytext(code, codepos + 1, codepos + 2) + if(char == "\n") + line++ + linepos = codepos - if(ignore.Find(char)) - continue - else if(char == "/" && (nextchar == "/" || nextchar == "*")) - ReadComment() - else if(end_stmt.Find(char)) - tokens+=new /token/end(char, line, COL) - else if(string_delim.Find(char)) - codepos++ //skip string delimiter - tokens+=ReadString(char) - else if(options.CanStartID(char)) - tokens+=ReadWord() - else if(options.IsDigit(char)) - tokens+=ReadNumber() - else if(options.symbols.Find(char)) - tokens+=ReadSymbol() + if(ignore.Find(char)) + continue + + else if(char == "/" && (nextchar == "*" || nextchar == "/")) + ReadComment() + + else if(end_stmt.Find(char)) + tokens += new/datum/token/end(char, line, COL) + + else if(string_delim.Find(char)) + codepos++ //skip string delimiter + tokens += ReadString(char) + + else if(options.CanStartID(char)) + tokens += ReadWord() + + else if(options.IsDigit(char)) + tokens += ReadNumber() + + else if(options.symbols.Find(char)) + tokens += ReadSymbol() - codepos=initial(codepos) - line=initial(line) - linepos=initial(linepos) - return tokens + codepos = initial(codepos) + line = initial(line) + linepos = initial(linepos) + return tokens + - proc /* Proc: ReadString Reads a string in the source code into a token. @@ -153,136 +153,139 @@ Parameters: start - The character used to start the string. */ - ReadString(start) - var - buf - for(, codepos <= lentext(code), codepos++)//codepos to lentext(code)) - var/char=copytext(code, codepos, codepos+1) +/datum/n_Scanner/nS_Scanner/proc/ReadString(start) + var/buf + for(, codepos <= length(code), codepos++)//codepos to length(code)) + var/char = copytext(code, codepos, codepos + 1) + switch(char) + if("\\") //Backslash (\) encountered in string + codepos++ //Skip next character in string, since it was escaped by a backslash + char = copytext(code, codepos, codepos+1) switch(char) - if("\\") //Backslash (\) encountered in string - codepos++ //Skip next character in string, since it was escaped by a backslash - char=copytext(code, codepos, codepos+1) - switch(char) - if("\\") //Double backslash - buf+="\\" - if("n") //\n Newline - buf+="\n" - else - if(char==start) //\" Doublequote - buf+=start - else //Unknown escaped text - buf+=char - if("\n") - . = new/token/string(buf, line, COL) - errors+=new/scriptError("Unterminated string. Newline reached.", .) - line++ - linepos=codepos - break + if("\\") //Double backslash + buf += "\\" + if("n") //\n Newline + buf += "\n" else - if(char==start) //string delimiter found, end string - break - else - buf+=char //Just a normal character in a string - if(!.) return new/token/string(buf, line, COL) + if(char == start) //\" Doublequote + buf += start + else //Unknown escaped text + buf += char + if("\n") + . = new/datum/token/string(buf, line, COL) + errors += new/datum/scriptError("Unterminated string. Newline reached.", .) + line++ + linepos = codepos + break + else + if(char == start) //string delimiter found, end string + break + else + buf += char //Just a normal character in a string + if(!.) + return new/datum/token/string(buf, line, COL) /* Proc: ReadWord Reads characters separated by an item in into a token. */ - ReadWord() - var - char=copytext(code, codepos, codepos+1) - buf - while(!delim.Find(char) && codepos<=lentext(code)) - buf+=char - char=copytext(code, ++codepos, codepos+1) - codepos-- //allow main Scan() proc to read the delimiter - if(options.keywords.Find(buf)) - return new /token/keyword(buf, line, COL) - else - return new /token/word(buf, line, COL) +/datum/n_Scanner/nS_Scanner/proc/ReadWord() + var/char = copytext(code, codepos, codepos + 1) + var/buf + + while(!delim.Find(char) && codepos <= length(code)) + buf += char + char = copytext(code, ++codepos, codepos + 1) + codepos-- //allow main Scan() proc to read the delimiter + if(options.keywords.Find(buf)) + return new/datum/token/keyword(buf, line, COL) + else + return new/datum/token/word(buf, line, COL) /* Proc: ReadSymbol Reads a symbol into a token. */ - ReadSymbol() - var - char=copytext(code, codepos, codepos+1) - buf +/datum/n_Scanner/nS_Scanner/proc/ReadSymbol() + var/char=copytext(code, codepos, codepos + 1) + var/buf - while(options.symbols.Find(buf+char)) - buf+=char - if(++codepos>lentext(code)) break - char=copytext(code, codepos, codepos+1) + while(options.symbols.Find(buf + char)) + buf += char + if(++codepos > length(code)) break + char = copytext(code, codepos, codepos + 1) - codepos-- //allow main Scan() proc to read the next character - return new /token/symbol(buf, line, COL) + codepos-- //allow main Scan() proc to read the next character + return new /datum/token/symbol(buf, line, COL) /* Proc: ReadNumber Reads a number into a token. */ - ReadNumber() - var - char=copytext(code, codepos, codepos+1) - buf - dec=0 +/datum/n_Scanner/nS_Scanner/proc/ReadNumber() + var/char = copytext(code, codepos, codepos + 1) + var/buf + var/dec = 0 - while(options.IsDigit(char) || (char=="." && !dec)) - if(char==".") dec=1 - buf+=char - codepos++ - char=copytext(code, codepos, codepos+1) - var/token/number/T=new(buf, line, COL) - if(isnull(text2num(buf))) - errors+=new/scriptError("Bad number: ", T) - T.value=0 - codepos-- //allow main Scan() proc to read the next character - return T + while(options.IsDigit(char) || (char == "." && !dec)) + if(char == ".") + dec = 1 + + buf += char + codepos++ + char = copytext(code, codepos, codepos + 1) + + var/datum/token/number/T = new(buf, line, COL) + if(isnull(text2num(buf))) + errors += new/datum/scriptError("Bad number: ", T) + T.value = 0 + + codepos-- //allow main Scan() proc to read the next character + return T /* Proc: ReadComment Reads a comment and outputs the type of comment */ - ReadComment() - var - char=copytext(code, codepos, codepos+1) - nextchar=copytext(code, codepos+1, codepos+2) - charstring = char+nextchar - comm = 1 - // 1: single-line comment - // 2: multi-line comment +/datum/n_Scanner/nS_Scanner/proc/ReadComment() + var/char = copytext(code, codepos, codepos + 1) + var/nextchar = copytext(code, codepos + 1, codepos + 2) + var/charstring = char + nextchar + var/comm = 1 + // 1: single-line comment + // 2: multi-line comment + var/expectedend = 0 + + if(charstring == "//" || charstring == "/*") + if(charstring == "/*") + comm = 2 // starts a multi-line comment + + while(comm) + if(++codepos > length(code)) + break + + if(expectedend) // ending statement expected... + char = copytext(code, codepos, codepos + 1) + if(char == "/") // ending statement found - beak the comment + comm = 0 + break + + if(comm == 2) + // multi-line comments are broken by ending statements + char = copytext(code, codepos, codepos + 1) + if(char == "*") + expectedend = 1 + continue + else + char = copytext(code, codepos, codepos + 1) + if(char == "\n") + comm = 0 + break + + if(expectedend) expectedend = 0 - if(charstring == "//" || charstring == "/*") - if(charstring == "/*") - comm = 2 // starts a multi-line comment - - while(comm) - if(++codepos>lentext(code)) break - - if(expectedend) // ending statement expected... - char = copytext(code, codepos, codepos+1) - if(char == "/") // ending statement found - beak the comment - comm = 0 - break - - if(comm == 2) - // multi-line comments are broken by ending statements - char = copytext(code, codepos, codepos+1) - if(char == "*") - expectedend = 1 - continue - else - char = copytext(code, codepos, codepos+1) - if(char == "\n") - comm = 0 - break - - if(expectedend) expectedend = 0 - - if(comm == 2) - errors+=new/scriptError/UnterminatedComment() + if(comm == 2) + errors += new/datum/scriptError/UnterminatedComment() diff --git a/code/modules/scripting/Scanner/Tokens.dm b/code/modules/scripting/Scanner/Tokens.dm index 0c2a8a5cc70..acf7bbbad99 100644 --- a/code/modules/scripting/Scanner/Tokens.dm +++ b/code/modules/scripting/Scanner/Tokens.dm @@ -1,38 +1,40 @@ -//This file was auto-corrected by findeclaration.exe on 25.5.2012 20:42:33 - /* Class: Token Represents an entity and position in the source code. */ -/token +/datum/token var/value var/line var/column - New(v, l=0, c=0) - value=v - line=l - column=c +/datum/token/New(v, l = 0, c = 0) + value = v + line = l + column = c - string - symbol - word - keyword - number - New() - .=..() - if(!isnum(value)) - value=text2num(value) - ASSERT(!isnull(value)) - accessor - var/object - var/member +/datum/token/string - New(object, member, l=0, c=0) - src.object=object - src.member=member - src.value="[object].[member]" //for debugging only - src.line=l - src.column=c +/datum/token/symbol - end +/datum/token/word + +/datum/token/keyword + +/datum/token/number/New() + . = ..() + if(!isnum(value)) + value = text2num(value) + ASSERT(!isnull(value)) + +/datum/token/accessor + var/object + var/member + +/datum/token/accessor/New(object, member, l = 0, c = 0) + src.object = object + src.member = member + src.value = "[object].[member]" //for debugging only + src.line = l + src.column = c + +/datum/token/end diff --git a/code/modules/scripting/stack.dm b/code/modules/scripting/stack.dm index be4147c7ec6..601c3d7646e 100644 --- a/code/modules/scripting/stack.dm +++ b/code/modules/scripting/stack.dm @@ -1,23 +1,26 @@ -/stack - var/list - contents=new - proc - Push(value) - contents+=value +/datum/stack + var/list/contents = list() - Pop() - if(!contents.len) return null - . = contents[contents.len] - contents.len-- +/datum/stack/proc/Push(value) + contents += value - Top() //returns the item on the top of the stack without removing it - if(!contents.len) return null - return contents[contents.len] +/datum/stack/proc/Pop() + if(!contents.len) + return null - Copy() - var/stack/S=new() - S.contents=src.contents.Copy() - return S + . = contents[contents.len] + contents.len-- - Clear() - contents.Cut() \ No newline at end of file +/datum/stack/proc/Top() //returns the item on the top of the stack without removing it + if(!contents.len) + return null + + return contents[contents.len] + +/datum/stack/proc/Copy() + var/datum/stack/S = new() + S.contents = src.contents.Copy() + return S + +/datum/stack/proc/Clear() + contents.Cut() \ No newline at end of file diff --git a/nano/css/codemirror.css b/nano/css/codemirror.css new file mode 100644 index 00000000000..3543523e645 --- /dev/null +++ b/nano/css/codemirror.css @@ -0,0 +1,334 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actuall scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + margin-bottom: -30px; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget {} + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { position: absolute; } +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/nano/css/lesser-dark.css b/nano/css/lesser-dark.css new file mode 100644 index 00000000000..690c183d7b4 --- /dev/null +++ b/nano/css/lesser-dark.css @@ -0,0 +1,47 @@ +/* +http://lesscss.org/ dark theme +Ported to CodeMirror by Peter Kroon +*/ +.cm-s-lesser-dark { + line-height: 1.3em; +} +.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; } +.cm-s-lesser-dark div.CodeMirror-selected { background: #45443B; } /* 33322B*/ +.cm-s-lesser-dark .CodeMirror-line::selection, .cm-s-lesser-dark .CodeMirror-line > span::selection, .cm-s-lesser-dark .CodeMirror-line > span > span::selection { background: rgba(69, 68, 59, .99); } +.cm-s-lesser-dark .CodeMirror-line::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(69, 68, 59, .99); } +.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white; } +.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/ + +.cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/ + +.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; } +.cm-s-lesser-dark .CodeMirror-guttermarker { color: #599eff; } +.cm-s-lesser-dark .CodeMirror-guttermarker-subtle { color: #777; } +.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; } + +.cm-s-lesser-dark span.cm-header { color: #a0a; } +.cm-s-lesser-dark span.cm-quote { color: #090; } +.cm-s-lesser-dark span.cm-keyword { color: #599eff; } +.cm-s-lesser-dark span.cm-atom { color: #C2B470; } +.cm-s-lesser-dark span.cm-number { color: #B35E4D; } +.cm-s-lesser-dark span.cm-def { color: white; } +.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; } +.cm-s-lesser-dark span.cm-variable-2 { color: #669199; } +.cm-s-lesser-dark span.cm-variable-3 { color: white; } +.cm-s-lesser-dark span.cm-property { color: #92A75C; } +.cm-s-lesser-dark span.cm-operator { color: #92A75C; } +.cm-s-lesser-dark span.cm-comment { color: #666; } +.cm-s-lesser-dark span.cm-string { color: #BCD279; } +.cm-s-lesser-dark span.cm-string-2 { color: #f50; } +.cm-s-lesser-dark span.cm-meta { color: #738C73; } +.cm-s-lesser-dark span.cm-qualifier { color: #555; } +.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; } +.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; } +.cm-s-lesser-dark span.cm-tag { color: #669199; } +.cm-s-lesser-dark span.cm-attribute { color: #00c; } +.cm-s-lesser-dark span.cm-hr { color: #999; } +.cm-s-lesser-dark span.cm-link { color: #00c; } +.cm-s-lesser-dark span.cm-error { color: #9d1e15; } + +.cm-s-lesser-dark .CodeMirror-activeline-background { background: #3C3A3A; } +.cm-s-lesser-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } diff --git a/nano/js/codemirror-compressed.js b/nano/js/codemirror-compressed.js new file mode 100644 index 00000000000..78cb9989a87 --- /dev/null +++ b/nano/js/codemirror-compressed.js @@ -0,0 +1,22 @@ +/* CodeMirror - Minified & Bundled + Generated on 10/27/2015 with http://codemirror.net/doc/compress.html + Version: HEAD + + CodeMirror Library: + - codemirror.js + Modes: + - css.js + Add-ons: + - css-hint.js + - search.js + Keymaps: + - sublime.js + */ + +!function(a){if("object"==typeof exports&&"object"==typeof module)module.exports=a();else{if("function"==typeof define&&define.amd)return define([],a);this.CodeMirror=a()}}(function(){"use strict";function x(a,b){if(!(this instanceof x))return new x(a,b);this.options=b=b?lg(b):{},lg(Cd,b,!1),K(b);var c=b.value;"string"==typeof c&&(c=new cf(c,b.mode,null,b.lineSeparator)),this.doc=c;var d=new x.inputStyles[b.inputStyle](this),e=this.display=new y(a,c,d);e.wrapper.CodeMirror=this,G(this),E(this),b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),b.autofocus&&!p&&e.input.focus(),O(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new ag,keySeq:null,specialChars:null};var i=this;f&&11>g&&setTimeout(function(){i.display.input.reset(!0)},20),rc(this),Fg(),Xb(this),this.curOp.forceUpdate=!0,gf(this,c),b.autofocus&&!p||i.hasFocus()?setTimeout(mg(_c,this),20):ad(this);for(var j in Dd)Dd.hasOwnProperty(j)&&Dd[j](this,b[j],Fd);T(this),b.finishInit&&b.finishInit(this);for(var k=0;kg&&(e.gutters.style.zIndex=-1,e.scroller.style.paddingRight=0),h||c&&p||(e.scroller.draggable=!0),a&&(a.appendChild?a.appendChild(e.wrapper):a(e.wrapper)),e.viewFrom=e.viewTo=b.first,e.reportedViewFrom=e.reportedViewTo=b.first,e.view=[],e.renderedView=null,e.externalMeasured=null,e.viewOffset=0,e.lastWrapHeight=e.lastWrapWidth=0,e.updateLineNumbers=null,e.nativeBarWidth=e.barHeight=e.barWidth=0,e.scrollbarsClipped=!1,e.lineNumWidth=e.lineNumInnerWidth=e.lineNumChars=null,e.alignWidgets=!1,e.cachedCharWidth=e.cachedTextHeight=e.cachedPaddingH=null,e.maxLine=null,e.maxLineLength=0,e.maxLineChanged=!1,e.wheelDX=e.wheelDY=e.wheelStartX=e.wheelStartY=null,e.shift=!1,e.selForContextMenu=null,e.activeTouch=null,d.init(e)}function z(a){a.doc.mode=x.getMode(a.options,a.doc.modeOption),A(a)}function A(a){a.doc.iter(function(a){a.stateAfter&&(a.stateAfter=null),a.styles&&(a.styles=null)}),a.doc.frontier=a.doc.first,kb(a,100),a.state.modeGen++,a.curOp&&kc(a)}function B(a){a.options.lineWrapping?(Bg(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(Ag(a.display.wrapper,"CodeMirror-wrap"),J(a)),D(a),kc(a),Hb(a),setTimeout(function(){P(a)},100)}function C(a){var b=Tb(a.display),c=a.options.lineWrapping,d=c&&Math.max(5,a.display.scroller.clientWidth/Ub(a.display)-3);return function(e){if(ye(a.doc,e))return 0;var f=0;if(e.widgets)for(var g=0;gb.maxLineLength&&(b.maxLineLength=c,b.maxLine=a)})}function K(a){var b=hg(a.gutters,"CodeMirror-linenumbers");-1==b&&a.lineNumbers?a.gutters=a.gutters.concat(["CodeMirror-linenumbers"]):b>-1&&!a.lineNumbers&&(a.gutters=a.gutters.slice(0),a.gutters.splice(b,1))}function L(a){var b=a.display,c=b.gutters.offsetWidth,d=Math.round(a.doc.height+pb(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight,scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?c:0,docHeight:d,scrollHeight:d+rb(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:c}}function M(a,b,c){this.cm=c;var d=this.vert=tg("div",[tg("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),e=this.horiz=tg("div",[tg("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");a(d),a(e),Lf(d,"scroll",function(){d.clientHeight&&b(d.scrollTop,"vertical")}),Lf(e,"scroll",function(){e.clientWidth&&b(e.scrollLeft,"horizontal")}),this.checkedOverlay=!1,f&&8>g&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function N(){}function O(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&Ag(a.display.wrapper,a.display.scrollbars.addClass)),a.display.scrollbars=new x.scrollbarModel[a.options.scrollbarStyle](function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller),Lf(b,"mousedown",function(){a.state.focused&&setTimeout(function(){a.display.input.focus()},0)}),b.setAttribute("cm-not-content","true")},function(b,c){"horizontal"==c?Kc(a,b):Jc(a,b)},a),a.display.scrollbars.addClass&&Bg(a.display.wrapper,a.display.scrollbars.addClass)}function P(a,b){b||(b=L(a));var c=a.display.barWidth,d=a.display.barHeight;Q(a,b);for(var e=0;4>e&&c!=a.display.barWidth||d!=a.display.barHeight;e++)c!=a.display.barWidth&&a.options.lineWrapping&&aa(a),Q(a,L(a)),c=a.display.barWidth,d=a.display.barHeight}function Q(a,b){var c=a.display,d=c.scrollbars.update(b);c.sizer.style.paddingRight=(c.barWidth=d.right)+"px",c.sizer.style.paddingBottom=(c.barHeight=d.bottom)+"px",d.right&&d.bottom?(c.scrollbarFiller.style.display="block",c.scrollbarFiller.style.height=d.bottom+"px",c.scrollbarFiller.style.width=d.right+"px"):c.scrollbarFiller.style.display="",d.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(c.gutterFiller.style.display="block",c.gutterFiller.style.height=d.bottom+"px",c.gutterFiller.style.width=b.gutterWidth+"px"):c.gutterFiller.style.display=""}function R(a,b,c){var d=c&&null!=c.top?Math.max(0,c.top):a.scroller.scrollTop;d=Math.floor(d-ob(a));var e=c&&null!=c.bottom?c.bottom:d+a.wrapper.clientHeight,f=nf(b,d),g=nf(b,e);if(c&&c.ensure){var h=c.ensure.from.line,i=c.ensure.to.line;f>h?(f=h,g=nf(b,of(hf(b,h))+a.wrapper.clientHeight)):Math.min(i,b.lastLine())>=g&&(f=nf(b,of(hf(b,i))-a.wrapper.clientHeight),g=i)}return{from:f,to:Math.max(g,f+1)}}function S(a){var b=a.display,c=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var d=V(b)-b.scroller.scrollLeft+a.doc.scrollLeft,e=b.gutters.offsetWidth,f=d+"px",g=0;g=c.viewFrom&&b.visible.to<=c.viewTo&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo)&&c.renderedView==c.view&&0==qc(a))return!1;T(a)&&(mc(a),b.dims=ca(a));var e=d.first+d.size,f=Math.max(b.visible.from-a.options.viewportMargin,d.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);c.viewFromg&&c.viewTo-g<20&&(g=Math.min(e,c.viewTo)),w&&(f=we(a.doc,f),g=xe(a.doc,g));var h=f!=c.viewFrom||g!=c.viewTo||c.lastWrapHeight!=b.wrapperHeight||c.lastWrapWidth!=b.wrapperWidth;pc(a,f,g),c.viewOffset=of(hf(a.doc,c.viewFrom)),a.display.mover.style.top=c.viewOffset+"px";var i=qc(a);if(!h&&0==i&&!b.force&&c.renderedView==c.view&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo))return!1;var j=yg();return i>4&&(c.lineDiv.style.display="none"),da(a,c.updateLineNumbers,b.dims),i>4&&(c.lineDiv.style.display=""),c.renderedView=c.view,j&&yg()!=j&&j.offsetHeight&&j.focus(),vg(c.cursorDiv),vg(c.selectionDiv),c.gutters.style.height=c.sizer.style.minHeight=0,h&&(c.lastWrapHeight=b.wrapperHeight,c.lastWrapWidth=b.wrapperWidth,kb(a,400)),c.updateLineNumbers=null,!0}function Z(a,b){for(var c=b.viewport,d=!0;(d&&a.options.lineWrapping&&b.oldDisplayWidth!=sb(a)||(c&&null!=c.top&&(c={top:Math.min(a.doc.height+pb(a.display)-tb(a),c.top)}),b.visible=R(a.display,a.doc,c),!(b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)))&&Y(a,b);d=!1){aa(a);var e=L(a);fb(a),_(a,e),P(a,e)}b.signal(a,"update",a),(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)&&(b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo)}function $(a,b){var c=new W(a,b);if(Y(a,c)){aa(a),Z(a,c);var d=L(a);fb(a),_(a,d),P(a,d),c.finish()}}function _(a,b){a.display.sizer.style.minHeight=b.docHeight+"px";var c=b.docHeight+a.display.barHeight;a.display.heightForcer.style.top=c+"px",a.display.gutters.style.height=Math.max(c+rb(a),b.clientHeight)+"px"}function aa(a){for(var b=a.display,c=b.lineDiv.offsetTop,d=0;dg){var i=e.node.offsetTop+e.node.offsetHeight;h=i-c,c=i}else{var j=e.node.getBoundingClientRect();h=j.bottom-j.top}var k=e.line.height-h;if(2>h&&(h=Tb(b)),(k>.001||-.001>k)&&(lf(e.line,h),ba(e.line),e.rest))for(var l=0;l=b&&m.lineNumber;m.changes&&(hg(m.changes,"gutter")>-1&&(o=!1),ea(a,m,k,c)),o&&(vg(m.lineNumber),m.lineNumber.appendChild(document.createTextNode(U(a.options,k)))),g=m.node.nextSibling}else{var n=ma(a,m,k,c);f.insertBefore(n,g)}k+=m.size}for(;g;)g=i(g)}function ea(a,b,c,d){for(var e=0;eg&&(a.node.style.zIndex=2)),a.node}function ga(a){var b=a.bgClass?a.bgClass+" "+(a.line.bgClass||""):a.line.bgClass;if(b&&(b+=" CodeMirror-linebackground"),a.background)b?a.background.className=b:(a.background.parentNode.removeChild(a.background),a.background=null);else if(b){var c=fa(a);a.background=c.insertBefore(tg("div",null,b),c.firstChild)}}function ha(a,b){var c=a.display.externalMeasured;return c&&c.line==b.line?(a.display.externalMeasured=null,b.measure=c.measure,c.built):Se(a,b)}function ia(a,b){var c=b.text.className,d=ha(a,b);b.text==b.node&&(b.node=d.pre),b.text.parentNode.replaceChild(d.pre,b.text),b.text=d.pre,d.bgClass!=b.bgClass||d.textClass!=b.textClass?(b.bgClass=d.bgClass,b.textClass=d.textClass,ja(b)):c&&(b.text.className=c)}function ja(a){ga(a),a.line.wrapClass?fa(a).className=a.line.wrapClass:a.node!=a.text&&(a.node.className="");var b=a.textClass?a.textClass+" "+(a.line.textClass||""):a.line.textClass;a.text.className=b||""}function ka(a,b,c,d){if(b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null),b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null),b.line.gutterClass){var e=fa(b);b.gutterBackground=tg("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?d.fixedPos:-d.gutterTotalWidth)+"px; width: "+d.gutterTotalWidth+"px"),e.insertBefore(b.gutterBackground,b.text)}var f=b.line.gutterMarkers;if(a.options.lineNumbers||f){var e=fa(b),g=b.gutter=tg("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?d.fixedPos:-d.gutterTotalWidth)+"px");if(a.display.input.setUneditable(g),e.insertBefore(g,b.text),b.line.gutterClass&&(g.className+=" "+b.line.gutterClass),!a.options.lineNumbers||f&&f["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(tg("div",U(a.options,c),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+d.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+a.display.lineNumInnerWidth+"px"))),f)for(var h=0;h1)if(xa&&xa.join("\n")==b){if(d.ranges.length%xa.length==0){i=[];for(var j=0;j=0;j--){var k=d.ranges[j],l=k.from(),m=k.to();k.empty()&&(c&&c>0?l=qa(l.line,l.ch-c):a.state.overwrite&&!g&&(m=qa(m.line,Math.min(hf(f,m.line).text.length,m.ch+fg(h).length))));var n=a.curOp.updateInput,o={from:l,to:m,text:i?i[j%i.length]:h,origin:e||(g?"paste":a.state.cutIncoming?"cut":"+input")};jd(a.doc,o),Rf(a,"inputRead",a,o)}b&&!g&&Aa(a,b),vd(a),a.curOp.updateInput=n,a.curOp.typing=!0,a.state.pasteIncoming=a.state.cutIncoming=!1}function za(a,b){var c=a.clipboardData&&a.clipboardData.getData("text/plain");return c?(a.preventDefault(),wa(b)||b.options.disableInput||ec(b,function(){ya(b,c,0,null,"paste")}),!0):void 0}function Aa(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var c=a.doc.sel,d=c.ranges.length-1;d>=0;d--){var e=c.ranges[d];if(!(e.head.ch>100||d&&c.ranges[d-1].head.line==e.head.line)){var f=a.getModeAt(e.head),g=!1;if(f.electricChars){for(var h=0;h-1){g=xd(a,e.head.line,"smart");break}}else f.electricInput&&f.electricInput.test(hf(a.doc,e.head.line).text.slice(0,e.head.ch))&&(g=xd(a,e.head.line,"smart"));g&&Rf(a,"electricInput",a,e.head.line)}}}function Ba(a){for(var b=[],c=[],d=0;de?i.map:j[e],g=0;ge?a.line:a.rest[e]),l=f[g]+d;return(0>d||h!=b)&&(l=f[g+(d?1:0)]),qa(k,l)}}}var d=a.text.firstChild,e=!1;if(!b||!xg(d,b))return Ha(qa(mf(a.line),0),!0);if(b==d&&(e=!0,b=d.childNodes[c],c=0,!b)){var f=a.rest?fg(a.rest):a.line;return Ha(qa(mf(f),f.text.length),e)}var g=3==b.nodeType?b:null,h=b;for(g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,c&&(c=g.nodeValue.length));h.parentNode!=d;)h=h.parentNode;var i=a.measure,j=i.maps,l=k(g,h,c);if(l)return Ha(l,e);for(var m=h.nextSibling,n=g?g.nodeValue.length-c:0;m;m=m.nextSibling){if(l=k(m,m.firstChild,0))return Ha(qa(l.line,l.ch-n),e);n+=m.textContent.length}for(var o=h.previousSibling,n=c;o;o=o.previousSibling){if(l=k(o,o.firstChild,-1))return Ha(qa(l.line,l.ch+n),e);n+=m.textContent.length}}function Ka(a,b,c,d,e){function i(a){return function(b){return b.id==a}}function j(b){if(1==b.nodeType){var c=b.getAttribute("cm-text");if(null!=c)return""==c&&(c=b.textContent.replace(/\u200b/g,"")),void(f+=c);var l,k=b.getAttribute("cm-marker");if(k){var m=a.findMarks(qa(d,0),qa(e+1,0),i(+k));return void(m.length&&(l=m[0].find())&&(f+=jf(a.doc,l.from,l.to).join(h)))}if("false"==b.getAttribute("contenteditable"))return;for(var n=0;n=0){var g=ua(f.from(),e.from()),h=ta(f.to(),e.to()),i=f.empty()?e.from()==e.head:f.from()==f.head;b>=d&&--b,a.splice(--d,2,new Ma(i?h:g,i?g:h))}}return new La(a,b)}function Oa(a,b){return new La([new Ma(a,b||a)],0)}function Pa(a,b){return Math.max(a.first,Math.min(b,a.first+a.size-1))}function Qa(a,b){if(b.linec?qa(c,hf(a,c).text.length):Ra(b,hf(a,b.line).text.length)}function Ra(a,b){var c=a.ch;return null==c||c>b?qa(a.line,b):0>c?qa(a.line,0):a}function Sa(a,b){return b>=a.first&&b=f.ch:j.to>f.ch))){if(d&&(Pf(k,"beforeCursorEnter"),k.explicitlyCleared)){if(h.markedSpans){--i;continue}break}if(!k.atomic)continue;var l=k.find(0>g?-1:1);if(0==ra(l,f)&&(l.ch+=g,l.ch<0?l=l.line>a.first?Qa(a,qa(l.line-1)):null:l.ch>h.text.length&&(l=l.lineb&&(b=0),b=Math.round(b),d=Math.round(d),f.appendChild(tg("div",null,"CodeMirror-selected","position: absolute; left: "+a+"px; top: "+b+"px; width: "+(null==c?i-a:c)+"px; height: "+(d-b)+"px"))}function k(b,c,d){function m(c,d){return Mb(a,qa(b,c),"div",f,d)}var k,l,f=hf(e,b),g=f.text.length;return Sg(pf(f),c||0,null==d?g:d,function(a,b,e){var n,o,p,f=m(a,"left");if(a==b)n=f,o=p=f.left;else{if(n=m(b-1,"right"),"rtl"==e){var q=f;f=n,n=q}o=f.left,p=n.right}null==c&&0==a&&(o=h),n.top-f.top>3&&(j(o,f.top,null,f.bottom),o=h,f.bottoml.bottom||n.bottom==l.bottom&&n.right>l.right)&&(l=n),h+1>o&&(o=h),j(o,n.top,p-o,n.bottom)}),{start:k,end:l}}var d=a.display,e=a.doc,f=document.createDocumentFragment(),g=qb(a.display),h=g.left,i=Math.max(d.sizerWidth,sb(a)-d.sizer.offsetLeft)-g.right,l=b.from(),m=b.to();if(l.line==m.line)k(l.line,l.ch,m.ch);else{var n=hf(e,l.line),o=hf(e,m.line),p=ue(n)==ue(o),q=k(l.line,l.ch,p?n.text.length+1:null).end,r=k(m.line,p?0:null,m.ch).start;p&&(q.top0?b.blinker=setInterval(function(){b.cursorDiv.style.visibility=(c=!c)?"":"hidden"},a.options.cursorBlinkRate):a.options.cursorBlinkRate<0&&(b.cursorDiv.style.visibility="hidden")}}function kb(a,b){a.doc.mode.startState&&a.doc.frontier=a.display.viewTo)){var c=+new Date+a.options.workTime,d=Ld(b.mode,nb(a,b.frontier)),e=[];b.iter(b.frontier,Math.min(b.first+b.size,a.display.viewTo+500),function(f){if(b.frontier>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength,i=Me(a,f,h?Ld(b.mode,d):d,!0);f.styles=i.styles;var j=f.styleClasses,k=i.classes;k?f.styleClasses=k:j&&(f.styleClasses=null);for(var l=!g||g.length!=f.styles.length||j!=k&&(!j||!k||j.bgClass!=k.bgClass||j.textClass!=k.textClass),m=0;!l&&mc?(kb(a,a.options.workDelay),!0):void 0}),e.length&&ec(a,function(){for(var b=0;bg;--h){if(h<=f.first)return f.first;var i=hf(f,h-1);if(i.stateAfter&&(!c||h<=f.frontier))return h;var j=bg(i.text,null,a.options.tabSize);(null==e||d>j)&&(e=h-1,d=j)}return e}function nb(a,b,c){var d=a.doc,e=a.display;if(!d.mode.startState)return!0;var f=mb(a,b,c),g=f>d.first&&hf(d,f-1).stateAfter;return g=g?Ld(d.mode,g):Md(d.mode),d.iter(f,b,function(c){Oe(a,c.text,g);var h=f==b-1||f%5==0||f>=e.viewFrom&&f2&&f.push((i.bottom+j.top)/2-c.top)}}f.push(c.bottom-c.top)}}function vb(a,b,c){if(a.line==b)return{map:a.measure.map,cache:a.measure.cache};for(var d=0;dc)return{map:a.measure.maps[d],cache:a.measure.caches[d],before:!0}}function wb(a,b){b=ue(b);var c=mf(b),d=a.display.externalMeasured=new ic(a.doc,b,c);d.lineN=c;var e=d.built=Se(a,d);return d.text=e.pre,wg(a.display.lineMeasure,e.pre),d}function xb(a,b,c,d){return Ab(a,zb(a,b),c,d)}function yb(a,b){if(b>=a.display.viewFrom&&b=c.lineN&&bb?(e=0,f=1,g="left"):j>b?(e=b-i,f=e+1):(h==a.length-3||b==j&&a[h+3]>b)&&(f=j-i,e=f-1,b>=j&&(g="right")),null!=e){if(d=a[h+2],i==j&&c==(d.insertLeft?"left":"right")&&(g=c),"left"==c&&0==e)for(;h&&a[h-2]==a[h-3]&&a[h-1].insertLeft;)d=a[(h-=3)+2],g="left";if("right"==c&&e==j-i)for(;hm;m++){for(;i&&sg(b.line.text.charAt(e.coverStart+i));)--i;for(;e.coverStart+jg&&0==i&&j==e.coverEnd-e.coverStart)l=h.parentNode.getBoundingClientRect();else if(f&&a.options.lineWrapping){var n=ug(h,i,j).getClientRects();l=n.length?n["right"==d?n.length-1:0]:Bb}else l=ug(h,i,j).getBoundingClientRect()||Bb;if(l.left||l.right||0==i)break;j=i,i-=1,k="right"}f&&11>g&&(l=Eb(a.display.measure,l))}else{i>0&&(k=d="right");var n;l=a.options.lineWrapping&&(n=h.getClientRects()).length>1?n["right"==d?n.length-1:0]:h.getBoundingClientRect()}if(f&&9>g&&!i&&(!l||!l.left&&!l.right)){var o=h.parentNode.getClientRects()[0];l=o?{left:o.left,right:o.left+Ub(a.display),top:o.top,bottom:o.bottom}:Bb}for(var p=l.top-b.rect.top,q=l.bottom-b.rect.top,r=(p+q)/2,s=b.view.measure.heights,m=0;mc.from?g(a-1):g(a,d)}d=d||hf(a.doc,b.line),e||(e=zb(a,d));var i=pf(d),j=b.ch;if(!i)return g(j);var k=ah(i,j),l=h(j,k);return null!=_g&&(l.other=h(j,_g)),l}function Ob(a,b){var c=0,b=Qa(a.doc,b);a.options.lineWrapping||(c=Ub(a.display)*b.ch);var d=hf(a.doc,b.line),e=of(d)+ob(a.display);return{left:c,right:c,top:e,bottom:e+d.height}}function Pb(a,b,c,d){var e=qa(a,b);return e.xRel=d,c&&(e.outside=!0),e}function Qb(a,b,c){var d=a.doc;if(c+=a.display.viewOffset,0>c)return Pb(d.first,0,!0,-1);var e=nf(d,c),f=d.first+d.size-1;if(e>f)return Pb(d.first+d.size-1,hf(d,f).text.length,!0,1);0>b&&(b=0);for(var g=hf(d,e);;){var h=Rb(a,g,e,b,c),i=se(g),j=i&&i.find(0,!0);if(!i||!(h.ch>j.from.ch||h.ch==j.from.ch&&h.xRel>0))return h;e=mf(g=j.to.line)}}function Rb(a,b,c,d,e){function j(d){var e=Nb(a,qa(c,d),"line",b,i);return g=!0,f>e.bottom?e.left-h:fq)return Pb(c,n,r,1);for(;;){if(k?n==m||n==ch(b,m,1):1>=n-m){for(var s=o>d||q-d>=d-o?m:n,t=d-(s==m?o:q);sg(b.text.charAt(s));)++s;var u=Pb(c,s,s==m?p:r,-1>t?-1:t>1?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=ch(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 Tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==Sb){Sb=tg("pre");for(var b=0;49>b;++b)Sb.appendChild(document.createTextNode("x")),Sb.appendChild(tg("br"));Sb.appendChild(document.createTextNode("x"))}wg(a.measure,Sb);var c=Sb.offsetHeight/50;return c>3&&(a.cachedTextHeight=c),vg(a.measure),c||1}function Ub(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=tg("span","xxxxxxxxxx"),c=tg("pre",[b]);wg(a.measure,c);var d=b.getBoundingClientRect(),e=(d.right-d.left)/10;return e>2&&(a.cachedCharWidth=e),e||10}function Xb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Wb},Vb?Vb.ops.push(a.curOp):a.curOp.ownsGroup=Vb={ops:[a.curOp],delayedCallbacks:[]}}function Yb(a){var b=a.delayedCallbacks,c=0;do{for(;c=c.viewTo)||c.maxLineChanged&&b.options.lineWrapping,a.update=a.mustUpdate&&new W(b,a.mustUpdate&&{top:a.scrollTop,ensure:a.scrollToPos},a.forceUpdate)}function ac(a){a.updatedDisplay=a.mustUpdate&&Y(a.cm,a.update)}function bc(a){var b=a.cm,c=b.display;a.updatedDisplay&&aa(b),a.barMeasure=L(b),c.maxLineChanged&&!b.options.lineWrapping&&(a.adjustWidthTo=xb(b,c.maxLine,c.maxLine.text.length).left+3,b.display.sizerWidth=a.adjustWidthTo,a.barMeasure.scrollWidth=Math.max(c.scroller.clientWidth,c.sizer.offsetLeft+a.adjustWidthTo+rb(b)+b.display.barWidth),a.maxScrollLeft=Math.max(0,c.sizer.offsetLeft+a.adjustWidthTo-sb(b))),(a.updatedDisplay||a.selectionChanged)&&(a.preparedSelection=c.input.prepareSelection())}function cc(a){var b=a.cm;null!=a.adjustWidthTo&&(b.display.sizer.style.minWidth=a.adjustWidthTo+"px",a.maxScrollLeftf;f=e){var g=new ic(a.doc,hf(a.doc,f),f);e=f+g.size,d.push(g)}return d}function kc(a,b,c,d){null==b&&(b=a.doc.first),null==c&&(c=a.doc.first+a.doc.size),d||(d=0);var e=a.display;if(d&&cb)&&(e.updateLineNumbers=b),a.curOp.viewChanged=!0,b>=e.viewTo)w&&we(a.doc,b)e.viewFrom?mc(a):(e.viewFrom+=d,e.viewTo+=d);else if(b<=e.viewFrom&&c>=e.viewTo)mc(a);else if(b<=e.viewFrom){var f=oc(a,c,c+d,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=d):mc(a)}else if(c>=e.viewTo){var f=oc(a,b,b,-1);f?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):mc(a)}else{var g=oc(a,b,b,-1),h=oc(a,c,c+d,1);g&&h?(e.view=e.view.slice(0,g.index).concat(jc(a,g.lineN,h.lineN)).concat(e.view.slice(h.index)),e.viewTo+=d):mc(a)}var i=e.externalMeasured;i&&(c=e.lineN&&b=d.viewTo)){var f=d.view[nc(a,b)];if(null!=f.node){var g=f.changes||(f.changes=[]);-1==hg(g,c)&&g.push(c)}}}function mc(a){a.display.viewFrom=a.display.viewTo=a.doc.first,a.display.view=[],a.display.viewOffset=0}function nc(a,b){if(b>=a.display.viewTo)return null;if(b-=a.display.viewFrom,0>b)return null;for(var c=a.display.view,d=0;db)return d}function oc(a,b,c,d){var f,e=nc(a,b),g=a.display.view;if(!w||c==a.doc.first+a.doc.size)return{index:e,lineN:c};for(var h=0,i=a.display.viewFrom;e>h;h++)i+=g[h].size;if(i!=b){if(d>0){if(e==g.length-1)return null;f=i+g[e].size-b,e++}else f=i-b;b+=f,c+=f}for(;we(a.doc,c)!=c;){if(e==(0>d?0:g.length-1))return null;c+=d*g[e-(0>d?1:0)].size,e+=d}return{index:e,lineN:c}}function pc(a,b,c){var d=a.display,e=d.view;0==e.length||b>=d.viewTo||c<=d.viewFrom?(d.view=jc(a,b,c),d.viewFrom=b):(d.viewFrom>b?d.view=jc(a,b,d.viewFrom).concat(d.view):d.viewFromc&&(d.view=d.view.slice(0,nc(a,c)))),d.viewTo=c}function qc(a){for(var b=a.display.view,c=0,d=0;d400}var b=a.display;Lf(b.scroller,"mousedown",fc(a,wc)),f&&11>g?Lf(b.scroller,"dblclick",fc(a,function(b){if(!Tf(a,b)){var c=vc(a,b);if(c&&!Dc(a,b)&&!uc(a.display,b)){Ff(b);var d=a.findWordAt(c);Va(a.doc,d.anchor,d.head)}}})):Lf(b.scroller,"dblclick",function(b){Tf(a,b)||Ff(b)}),u||Lf(b.scroller,"contextmenu",function(b){bd(a,b)});var c,d={end:0};Lf(b.scroller,"touchstart",function(a){if(!h(a)){clearTimeout(c);var e=+new Date;b.activeTouch={start:e,moved:!1,prev:e-d.end<=300?d:null},1==a.touches.length&&(b.activeTouch.left=a.touches[0].pageX,b.activeTouch.top=a.touches[0].pageY)}}),Lf(b.scroller,"touchmove",function(){b.activeTouch&&(b.activeTouch.moved=!0)}),Lf(b.scroller,"touchend",function(c){var d=b.activeTouch;if(d&&!uc(b,c)&&null!=d.left&&!d.moved&&new Date-d.start<300){var g,f=a.coordsChar(b.activeTouch,"page");g=!d.prev||i(d,d.prev)?new Ma(f,f):!d.prev.prev||i(d,d.prev.prev)?a.findWordAt(f):new Ma(qa(f.line,0),Qa(a.doc,qa(f.line+1,0))),a.setSelection(g.anchor,g.head),a.focus(),Ff(c)}e()}),Lf(b.scroller,"touchcancel",e),Lf(b.scroller,"scroll",function(){b.scroller.clientHeight&&(Jc(a,b.scroller.scrollTop),Kc(a,b.scroller.scrollLeft,!0),Pf(a,"scroll",a))}),Lf(b.scroller,"mousewheel",function(b){Oc(a,b)}),Lf(b.scroller,"DOMMouseScroll",function(b){Oc(a,b)}),Lf(b.wrapper,"scroll",function(){b.wrapper.scrollTop=b.wrapper.scrollLeft=0}),b.dragFunctions={enter:function(b){Tf(a,b)||If(b)},over:function(b){Tf(a,b)||(Hc(a,b),If(b))},start:function(b){Gc(a,b)},drop:fc(a,Fc),leave:function(){Ic(a)}};var j=b.input.getField();Lf(j,"keyup",function(b){Yc.call(a,b)}),Lf(j,"keydown",fc(a,Wc)),Lf(j,"keypress",fc(a,Zc)),Lf(j,"focus",mg(_c,a)),Lf(j,"blur",mg(ad,a))}function sc(a,b,c){var d=c&&c!=x.Init;if(!b!=!d){var e=a.display.dragFunctions,f=b?Lf:Of;f(a.display.scroller,"dragstart",e.start),f(a.display.scroller,"dragenter",e.enter),f(a.display.scroller,"dragover",e.over),f(a.display.scroller,"dragleave",e.leave),f(a.display.scroller,"drop",e.drop)}}function tc(a){var b=a.display;(b.lastWrapHeight!=b.wrapper.clientHeight||b.lastWrapWidth!=b.wrapper.clientWidth)&&(b.cachedCharWidth=b.cachedTextHeight=b.cachedPaddingH=null,b.scrollbarsClipped=!1,a.setSize())}function uc(a,b){for(var c=Jf(b);c!=a.wrapper;c=c.parentNode)if(!c||1==c.nodeType&&"true"==c.getAttribute("cm-ignore-events")||c.parentNode==a.sizer&&c!=a.mover)return!0}function vc(a,b,c,d){var e=a.display;if(!c&&"true"==Jf(b).getAttribute("cm-not-content"))return null;var f,g,h=e.lineSpace.getBoundingClientRect();try{f=b.clientX-h.left,g=b.clientY-h.top}catch(b){return null}var j,i=Qb(a,f,g);if(d&&1==i.xRel&&(j=hf(a.doc,i.line).text).length==i.ch){var k=bg(j,j.length,a.options.tabSize)-j.length;i=qa(i.line,Math.max(0,Math.round((f-qb(a.display).left)/Ub(a.display))-k))}return i}function wc(a){var b=this,c=b.display;if(!(c.activeTouch&&c.input.supportsTouch()||Tf(b,a))){if(c.shift=a.shiftKey,uc(c,a))return void(h||(c.scroller.draggable=!1,setTimeout(function(){c.scroller.draggable=!0},100)));if(!Dc(b,a)){var d=vc(b,a);switch(window.focus(),Kf(a)){case 1:b.state.selectingText?b.state.selectingText(a):d?zc(b,a,d):Jf(a)==c.scroller&&Ff(a);break;case 2:h&&(b.state.lastMiddleDown=+new Date),d&&Va(b.doc,d),setTimeout(function(){c.input.focus()},20),Ff(a);break;case 3:u?bd(b,a):$c(b)}}}}function zc(a,b,c){f?setTimeout(mg(va,a),0):a.curOp.focus=yg();var e,d=+new Date;yc&&yc.time>d-400&&0==ra(yc.pos,c)?e="triple":xc&&xc.time>d-400&&0==ra(xc.pos,c)?(e="double",yc={time:d,pos:c}):(e="single",xc={time:d,pos:c});var i,g=a.doc.sel,h=q?b.metaKey:b.ctrlKey;a.options.dragDrop&&Hg&&!wa(a)&&"single"==e&&(i=g.contains(c))>-1&&(ra((i=g.ranges[i]).from(),c)<0||c.xRel>0)&&(ra(i.to(),c)>0||c.xRel<0)?Ac(a,b,c,h):Bc(a,b,c,e,h)}function Ac(a,b,c,d){var e=a.display,i=+new Date,j=fc(a,function(k){h&&(e.scroller.draggable=!1),a.state.draggingText=!1,Of(document,"mouseup",j),Of(e.scroller,"drop",j),Math.abs(b.clientX-k.clientX)+Math.abs(b.clientY-k.clientY)<10&&(Ff(k),!d&&+new Date-200=p;p++){var r=hf(g,p).text,s=cg(r,m,f);m==o?e.push(new Ma(qa(p,s),qa(p,s))):r.length>s&&e.push(new Ma(qa(p,s),qa(p,cg(r,o,f))))}e.length||e.push(new Ma(c,c)),_a(g,Na(j.ranges.slice(0,i).concat(e),i),{origin:"*mouse",scroll:!1}),a.scrollIntoView(b)}else{var t=h,u=t.anchor,v=b;if("single"!=d){if("double"==d)var w=a.findWordAt(b);else var w=new Ma(qa(b.line,0),Qa(g,qa(b.line+1,0)));ra(w.anchor,u)>0?(v=w.head,u=ua(t.from(),w.anchor)):(v=w.anchor,u=ta(t.to(),w.head))}var e=j.ranges.slice(0);e[i]=new Ma(Qa(g,u),v),_a(g,Na(e,i),$f)}}function r(b){var c=++q,e=vc(a,b,!0,"rect"==d);if(e)if(0!=ra(e,n)){a.curOp.focus=yg(),o(e);var h=R(f,g);(e.line>=h.to||e.linep.bottom?20:0;i&&setTimeout(fc(a,function(){q==c&&(f.scroller.scrollTop+=i,r(b))}),50)}}function s(b){a.state.selectingText=!1,q=1/0,Ff(b),f.input.focus(),Of(document,"mousemove",t),Of(document,"mouseup",u),g.history.lastSelOrigin=null}var f=a.display,g=a.doc;Ff(b);var h,i,j=g.sel,k=j.ranges;if(e&&!b.shiftKey?(i=g.sel.contains(c),h=i>-1?k[i]:new Ma(c,c)):(h=g.sel.primary(),i=g.sel.primIndex),b.altKey)d="rect",e||(h=new Ma(c,c)),c=vc(a,b,!0,!0),i=-1;else if("double"==d){var l=a.findWordAt(c);h=a.display.shift||g.extend?Ua(g,h,l.anchor,l.head):l}else if("triple"==d){var m=new Ma(qa(c.line,0),Qa(g,qa(c.line+1,0)));h=a.display.shift||g.extend?Ua(g,h,m.anchor,m.head):m}else h=Ua(g,h,c);e?-1==i?(i=k.length,_a(g,Na(k.concat([h]),i),{scroll:!1,origin:"*mouse"})):k.length>1&&k[i].empty()&&"single"==d&&!b.shiftKey?(_a(g,Na(k.slice(0,i).concat(k.slice(i+1)),0),{scroll:!1,origin:"*mouse"}),j=g.sel):Xa(g,i,h,$f):(i=0,_a(g,new La([h],0),$f),j=g.sel);var n=c,p=f.wrapper.getBoundingClientRect(),q=0,t=fc(a,function(a){Kf(a)?r(a):s(a)}),u=fc(a,s);a.state.selectingText=u,Lf(document,"mousemove",t),Lf(document,"mouseup",u)}function Cc(a,b,c,d){try{var e=b.clientX,f=b.clientY}catch(b){return!1}if(e>=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;d&&Ff(b);var g=a.display,h=g.lineDiv.getBoundingClientRect();if(f>h.bottom||!Vf(a,c))return Hf(b);f-=h.top-g.viewOffset;for(var i=0;i=e){var k=nf(a.doc,f),l=a.options.gutters[i];return Pf(a,c,a,k,l,b),Hf(b)}}}function Dc(a,b){return Cc(a,b,"gutterClick",!0)}function Fc(a){var b=this;if(Ic(b),!Tf(b,a)&&!uc(b.display,a)){Ff(a),f&&(Ec=+new Date);var c=vc(b,a,!0),d=a.dataTransfer.files;if(c&&!wa(b))if(d&&d.length&&window.FileReader&&window.File)for(var e=d.length,g=Array(e),h=0,i=function(a,d){if(!b.options.allowDropFileTypes||-1!=hg(b.options.allowDropFileTypes,a.type)){var f=new FileReader;f.onload=fc(b,function(){var a=f.result;if(/[\x00-\x08\x0e-\x1f]{2}/.test(a)&&(a=""),g[d]=a,++h==e){c=Qa(b.doc,c);var i={from:c,to:c,text:b.doc.splitLines(g.join(b.doc.lineSeparator())),origin:"paste"};jd(b.doc,i),$a(b.doc,Oa(c,dd(i)))}}),f.readAsText(a)}},j=0;e>j;++j)i(d[j],j);else{if(b.state.draggingText&&b.doc.sel.contains(c)>-1)return b.state.draggingText(a),void setTimeout(function(){b.display.input.focus()},20);try{var g=a.dataTransfer.getData("Text");if(g){if(b.state.draggingText&&!(q?a.altKey:a.ctrlKey))var k=b.listSelections();if(ab(b.doc,Oa(c,c)),k)for(var j=0;ji.clientWidth,l=i.scrollHeight>i.clientHeight;if(e&&j||f&&l){if(f&&q&&h)a:for(var m=b.target,n=g.view;m!=i;m=m.parentNode)for(var o=0;op?r=Math.max(0,r+p-50):s=Math.min(a.doc.height,s+p+50),$(a,{top:r,bottom:s})}20>Lc&&(null==g.wheelStartX?(g.wheelStartX=i.scrollLeft,g.wheelStartY=i.scrollTop,g.wheelDX=e,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&&(Mc=(Mc*Lc+c)/(Lc+1),++Lc)}},200)):(g.wheelDX+=e,g.wheelDY+=f))}}function Pc(a,b,c){if("string"==typeof b&&(b=Nd[b],!b))return!1;a.display.input.ensurePolled();var d=a.display.shift,e=!1;try{wa(a)&&(a.state.suppressEdits=!0),c&&(a.display.shift=!1),e=b(a)!=Yf}finally{a.display.shift=d,a.state.suppressEdits=!1}return e}function Qc(a,b,c){for(var d=0;dg&&27==a.keyCode&&(a.returnValue=!1);var c=a.keyCode;b.display.shift=16==c||a.shiftKey;var d=Tc(b,a);k&&(Vc=d?c:null,!d&&88==c&&!Og&&(q?a.metaKey:a.ctrlKey)&&b.replaceSelection("",null,"cut")),18!=c||/\bCodeMirror-crosshair\b/.test(b.display.lineDiv.className)||Xc(b)}}function Xc(a){function c(a){18!=a.keyCode&&a.altKey||(Ag(b,"CodeMirror-crosshair"),Of(document,"keyup",c),Of(document,"mouseover",c))}var b=a.display.lineDiv;Bg(b,"CodeMirror-crosshair"),Lf(document,"keyup",c),Lf(document,"mouseover",c)}function Yc(a){16==a.keyCode&&(this.doc.sel.shift=!1),Tf(this,a)}function Zc(a){var b=this;if(!(uc(b.display,a)||Tf(b,a)||a.ctrlKey&&!a.altKey||q&&a.metaKey)){var c=a.keyCode,d=a.charCode;if(k&&c==Vc)return Vc=null,void Ff(a);if(!k||a.which&&!(a.which<10)||!Tc(b,a)){var e=String.fromCharCode(null==d?c:d);Uc(b,a,e)||b.display.input.onKeyPress(a)}}}function $c(a){a.state.delayingBlurEvent=!0,setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,ad(a))},100)}function _c(a){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1),"nocursor"!=a.options.readOnly&&(a.state.focused||(Pf(a,"focus",a),a.state.focused=!0,Bg(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),h&&setTimeout(function(){a.display.input.reset(!0)},20)),a.display.input.receivedFocus()),jb(a))}function ad(a){a.state.delayingBlurEvent||(a.state.focused&&(Pf(a,"blur",a),a.state.focused=!1,Ag(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused||(a.display.shift=!1)},150))}function bd(a,b){uc(a.display,b)||cd(a,b)||Tf(a,b,"contextmenu")||a.display.input.onContextMenu(b)}function cd(a,b){return Vf(a,"gutterContextMenu")?Cc(a,b,"gutterContextMenu",!1):!1}function ed(a,b){if(ra(a,b.from)<0)return a;if(ra(a,b.to)<=0)return dd(b);var c=a.line+b.text.length-(b.to.line-b.from.line)-1,d=a.ch;return a.line==b.to.line&&(d+=dd(b).ch-b.to.ch),qa(c,d)}function fd(a,b){for(var c=[],d=0;d=0;--e)kd(a,{from:d[e].from,to:d[e].to,text:e?[""]:b.text});else kd(a,b)}}function kd(a,b){if(1!=b.text.length||""!=b.text[0]||0!=ra(b.from,b.to)){var c=fd(a,b);uf(a,b,c,a.cm?a.cm.curOp.id:NaN),nd(a,b,c,he(a,b));var d=[];ff(a,function(a,c){c||-1!=hg(d,a.history)||(Ef(a.history,b),d.push(a.history)),nd(a,b,null,he(a,b))})}}function ld(a,b,c){if(!a.cm||!a.cm.state.suppressEdits){for(var e,d=a.history,f=a.sel,g="undo"==b?d.done:d.undone,h="undo"==b?d.undone:d.done,i=0;i=0;--i){var l=e.changes[i];if(l.origin=b,k&&!id(a,l,!1))return void(g.length=0);j.push(rf(a,l));var m=i?fd(a,l):fg(g);nd(a,l,m,je(a,l)),!i&&a.cm&&a.cm.scrollIntoView({from:l.from,to:dd(l)});var n=[];ff(a,function(a,b){b||-1!=hg(n,a.history)||(Ef(a.history,l),n.push(a.history)),nd(a,l,null,je(a,l))})}}}}function md(a,b){if(0!=b&&(a.first+=b,a.sel=new La(ig(a.sel.ranges,function(a){return new Ma(qa(a.anchor.line+b,a.anchor.ch),qa(a.head.line+b,a.head.ch))}),a.sel.primIndex),a.cm)){kc(a.cm,a.first,a.first-b,b);for(var c=a.cm.display,d=c.viewFrom;da.lastLine())){if(b.from.linef&&(b={from:b.from,to:qa(f,hf(a,f).text.length),text:[b.text[0]],origin:b.origin}),b.removed=jf(a,b.from,b.to),c||(c=fd(a,b)),a.cm?od(a.cm,b,d):$e(a,b,d),ab(a,c,Zf)}}function od(a,b,c){var d=a.doc,e=a.display,f=b.from,g=b.to,h=!1,i=f.line;a.options.lineWrapping||(i=mf(ue(hf(d,f.line))),d.iter(i,g.line+1,function(a){return a==e.maxLine?(h=!0,!0):void 0})),d.sel.contains(b.from,b.to)>-1&&Uf(a),$e(d,b,c,C(a)),a.options.lineWrapping||(d.iter(i,f.line+b.text.length,function(a){var b=I(a);b>e.maxLineLength&&(e.maxLine=a,e.maxLineLength=b,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0)),d.frontier=Math.min(d.frontier,f.line),kb(a,400);var j=b.text.length-(g.line-f.line)-1;b.full?kc(a):f.line!=g.line||1!=b.text.length||Ze(a.doc,b)?kc(a,f.line,g.line+1,j):lc(a,f.line,"text");var k=Vf(a,"changes"),l=Vf(a,"change");if(l||k){var m={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin};l&&Rf(a,"change",a,m),k&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(m)}a.display.selForContextMenu=null}function pd(a,b,c,d,e){if(d||(d=c),ra(d,c)<0){var f=d;d=c,c=f}"string"==typeof b&&(b=a.splitLines(b)),jd(a,{from:c,to:d,text:b,origin:e})}function qd(a,b){if(!Tf(a,"scrollCursorIntoView")){var c=a.display,d=c.sizer.getBoundingClientRect(),e=null;if(b.top+d.top<0?e=!0:b.bottom+d.top>(window.innerHeight||document.documentElement.clientHeight)&&(e=!1),null!=e&&!n){var f=tg("div","\u200b",null,"position: absolute; top: "+(b.top-c.viewOffset-ob(a.display))+"px; height: "+(b.bottom-b.top+rb(a)+c.barHeight)+"px; left: "+b.left+"px; width: 2px;");a.display.lineSpace.appendChild(f),f.scrollIntoView(e),a.display.lineSpace.removeChild(f)}}}function rd(a,b,c,d){null==d&&(d=0);for(var e=0;5>e;e++){var f=!1,g=Nb(a,b),h=c&&c!=b?Nb(a,c):g,i=td(a,Math.min(g.left,h.left),Math.min(g.top,h.top)-d,Math.max(g.left,h.left),Math.max(g.bottom,h.bottom)+d),j=a.doc.scrollTop,k=a.doc.scrollLeft;if(null!=i.scrollTop&&(Jc(a,i.scrollTop),Math.abs(a.doc.scrollTop-j)>1&&(f=!0)),null!=i.scrollLeft&&(Kc(a,i.scrollLeft),Math.abs(a.doc.scrollLeft-k)>1&&(f=!0)),!f)break}return g}function sd(a,b,c,d,e){var f=td(a,b,c,d,e);null!=f.scrollTop&&Jc(a,f.scrollTop),null!=f.scrollLeft&&Kc(a,f.scrollLeft)}function td(a,b,c,d,e){var f=a.display,g=Tb(a.display);0>c&&(c=0);var h=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:f.scroller.scrollTop,i=tb(a),j={};e-c>i&&(e=c+i);var k=a.doc.height+pb(f),l=g>c,m=e>k-g;if(h>c)j.scrollTop=l?0:c;else if(e>h+i){var n=Math.min(c,(m?k:e)-i);n!=h&&(j.scrollTop=n)}var o=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:f.scroller.scrollLeft,p=sb(a)-(a.options.fixedGutter?f.gutters.offsetWidth:0),q=d-b>p;return q&&(d=b+p),10>b?j.scrollLeft=0:o>b?j.scrollLeft=Math.max(0,b-(q?0:10)):d>p+o-3&&(j.scrollLeft=d+(q?0:10)-p),j}function ud(a,b,c){(null!=b||null!=c)&&wd(a),null!=b&&(a.curOp.scrollLeft=(null==a.curOp.scrollLeft?a.doc.scrollLeft:a.curOp.scrollLeft)+b),null!=c&&(a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+c)}function vd(a){wd(a);var b=a.getCursor(),c=b,d=b;a.options.lineWrapping||(c=b.ch?qa(b.line,b.ch-1):b,d=qa(b.line,b.ch+1)),a.curOp.scrollToPos={from:c,to:d,margin:a.options.cursorScrollMargin,isCursor:!0}}function wd(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var c=Ob(a,b.from),d=Ob(a,b.to),e=td(a,Math.min(c.left,d.left),Math.min(c.top,d.top)-b.margin,Math.max(c.right,d.right),Math.max(c.bottom,d.bottom)+b.margin);a.scrollTo(e.scrollLeft,e.scrollTop)}}function xd(a,b,c,d){var f,e=a.doc;null==c&&(c="add"),"smart"==c&&(e.mode.indent?f=nb(a,b):c="prev");var g=a.options.tabSize,h=hf(e,b),i=bg(h.text,null,g);h.stateAfter&&(h.stateAfter=null);var k,j=h.text.match(/^\s*/)[0];if(d||/\S/.test(h.text)){if("smart"==c&&(k=e.mode.indent(f,h.text.slice(j.length),h.text),k==Yf||k>150)){ +if(!d)return;c="prev"}}else k=0,c="not";"prev"==c?k=b>e.first?bg(hf(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+=" ";if(k>m&&(l+=eg(k-m)),l!=j)return pd(e,l,qa(b,0),qa(b,j.length),"+input"),h.stateAfter=null,!0;for(var n=0;n=0;b--)pd(a.doc,"",d[b].from,d[b].to,"+delete");vd(a)})}function Ad(a,b,c,d,e){function k(){var b=f+c;return b=a.first+a.size?j=!1:(f=b,i=hf(a,b))}function l(a){var b=(e?ch:dh)(i,g,c,!0);if(null==b){if(a||!k())return j=!1;g=e?(0>c?Wg:Vg)(i):0>c?i.text.length:0}else g=b;return!0}var f=b.line,g=b.ch,h=c,i=hf(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=a.cm&&a.cm.getHelper(b,"wordChars"),p=!0;!(0>c)||l(!p);p=!1){var q=i.text.charAt(g)||"\n",r=pg(q,o)?"w":n&&"\n"==q?"n":!n||/\s/.test(q)?null:"p";if(!n||p||r||(r="s"),m&&m!=r){0>c&&(c=1,l());break}if(r&&(m=r),c>0&&!l(!p))break}var s=eb(a,qa(f,g),h,!0);return j||(s.hitSide=!0),s}function Bd(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)*Tb(a.display))}else"line"==d&&(g=c>0?b.bottom+3:b.top-3);for(;;){var i=Qb(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 Ed(a,b,c,d){x.defaults[a]=b,c&&(Dd[a]=d?function(a,b,d){d!=Fd&&c(a,b,d)}:c)}function Pd(a){for(var c,d,e,f,b=a.split(/-(?!$)/),a=b[b.length-1],g=0;g0||0==g&&f.clearWhenEmpty!==!1)return f;if(f.replacedWith&&(f.collapsed=!0,f.widgetNode=tg("span",[f.replacedWith],"CodeMirror-widget"),d.handleMouseEvents||f.widgetNode.setAttribute("cm-ignore-events","true"),d.insertLeft&&(f.widgetNode.insertLeft=!0)),f.collapsed){if(te(a,b.line,b,c,f)||b.line!=c.line&&te(a,c.line,b,c,f))throw new Error("Inserting collapsed marker partially overlapping an existing one");w=!0}f.addToHistory&&uf(a,{from:b,to:c,origin:"markText"},a.sel,NaN);var j,h=b.line,i=a.cm;if(a.iter(h,c.line+1,function(a){i&&f.collapsed&&!i.options.lineWrapping&&ue(a)==i.display.maxLine&&(j=!0),f.collapsed&&h!=b.line&&lf(a,0),ee(a,new be(f,h==b.line?b.ch:null,h==c.line?c.ch:null)),++h}),f.collapsed&&a.iter(b.line,c.line+1,function(b){ye(a,b)&&lf(b,0)}),f.clearOnEnter&&Lf(f,"beforeCursorEnter",function(){f.clear()}),f.readOnly&&(v=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory()),f.collapsed&&(f.id=++Vd,f.atomic=!0),i){if(j&&(i.curOp.updateMaxLine=!0),f.collapsed)kc(i,b.line,c.line+1);else if(f.className||f.title||f.startStyle||f.endStyle||f.css)for(var k=b.line;k<=c.line;k++)lc(i,k,"text");f.atomic&&cb(i.doc),Rf(i,"markerAdded",i,f)}return f}function Zd(a,b,c,d,e){d=lg(d),d.shared=!1;var f=[Xd(a,b,c,d,e)],g=f[0],h=d.widgetNode;return ff(a,function(a){h&&(d.widgetNode=h.cloneNode(!0)),f.push(Xd(a,Qa(a,b),Qa(a,c),d,e));for(var i=0;i=b:f.to>b);(e||(e=[])).push(new be(g,f.from,i?null:f.to))}}return e}function ge(a,b,c){if(a)for(var e,d=0;d=b:f.to>b);if(h||f.from==b&&"bookmark"==g.type&&(!c||f.marker.insertLeft)){var i=null==f.from||(g.inclusiveLeft?f.from<=b:f.from0&&h)for(var l=0;ll;++l)o.push(q);o.push(i)}return o}function ie(a){for(var b=0;b0)){var k=[i,1],l=ra(j.from,h.from),m=ra(j.to,h.to);(0>l||!g.inclusiveLeft&&!l)&&k.push({from:j.from,to:h.from}),(m>0||!g.inclusiveRight&&!m)&&k.push({from:h.to,to:j.to}),e.splice.apply(e,k),i+=k.length-1}}return e}function le(a){var b=a.markedSpans;if(b){for(var c=0;c=0&&0>=l||0>=k&&l>=0)&&(0>=k&&(ra(j.to,c)>0||i.marker.inclusiveRight&&e.inclusiveLeft)||k>=0&&(ra(j.from,d)<0||i.marker.inclusiveLeft&&e.inclusiveRight)))return!0}}}function ue(a){for(var b;b=re(a);)a=b.find(-1,!0).line;return a}function ve(a){for(var b,c;b=se(a);)a=b.find(1,!0).line,(c||(c=[])).push(a);return c}function we(a,b){var c=hf(a,b),d=ue(c);return c==d?b:mf(d)}function xe(a,b){if(b>a.lastLine())return b;var d,c=hf(a,b);if(!ye(a,c))return b;for(;d=se(c);)c=d.find(1,!0).line;return mf(c)+1}function ye(a,b){var c=w&&b.markedSpans;if(c)for(var d,e=0;ee;e++){d&&(d[0]=x.innerMode(a,c).mode);var f=a.token(b,c);if(b.pos>b.start)return f}throw new Error("Mode "+a.name+" failed to advance stream.")}function Ke(a,b,c,d){function e(a){return{start:k.start,end:k.pos,string:k.current(),type:h||null,state:a?Ld(f.mode,j):j}}var h,f=a.doc,g=f.mode;b=Qa(f,b);var l,i=hf(f,b.line),j=nb(a,b.line,c),k=new Ud(i.text,a.options.tabSize);for(d&&(l=[]);(d||k.posa.options.maxHighlightLength?(h=!1,g&&Oe(a,b,d,k.pos),k.pos=b.length,l=null):l=He(Je(c,k,d,m),f),m){var n=m[0].name;n&&(l="m-"+(l?n+" "+l:n))}if(!h||j!=l){for(;ij;){var d=e[i];d>a&&e.splice(i,1,a,e[i+1],d),i+=2,j=Math.min(a,d)}if(b)if(h.opaque)e.splice(c,i-c,a,"cm-overlay "+b),i=c+2;else for(;i>c;c+=2){var f=e[c+1];e[c+1]=(f?f+" ":"")+"cm-overlay "+b}},f)}return{styles:e,classes:f.bgClass||f.textClass?f:null}}function Ne(a,b,c){if(!b.styles||b.styles[0]!=a.state.modeGen){var d=nb(a,mf(b)),e=Me(a,b,b.text.length>a.options.maxHighlightLength?Ld(a.doc.mode,d):d);b.stateAfter=d,b.styles=e.styles,e.classes?b.styleClasses=e.classes:b.styleClasses&&(b.styleClasses=null),c===a.doc.frontier&&a.doc.frontier++}return b.styles}function Oe(a,b,c,d){var e=a.doc.mode,f=new Ud(b,a.options.tabSize);for(f.start=f.pos=d||0,""==b&&Ie(e,c);!f.eol();)Je(e,f,c),f.start=f.pos}function Re(a,b){if(!a||/^\s*$/.test(a))return null;var c=b.addModeClass?Qe:Pe;return c[a]||(c[a]=a.replace(/\S+/g,"cm-$&"))}function Se(a,b){var c=tg("span",null,null,h?"padding-right: .1px":null),d={pre:tg("pre",[c],"CodeMirror-line"),content:c,col:0,pos:0,cm:a,splitSpaces:(f||h)&&a.getOption("lineWrapping")};b.measure={};for(var e=0;e<=(b.rest?b.rest.length:0);e++){var i,g=e?b.rest[e-1]:b.line;d.pos=0,d.addToken=Ue,Lg(a.display.measure)&&(i=pf(g))&&(d.addToken=We(d.addToken,i)),d.map=[];var j=b!=a.display.externalMeasured&&mf(g);Ye(g,d,Ne(a,g,j)),g.styleClasses&&(g.styleClasses.bgClass&&(d.bgClass=Cg(g.styleClasses.bgClass,d.bgClass||"")),g.styleClasses.textClass&&(d.textClass=Cg(g.styleClasses.textClass,d.textClass||""))),0==d.map.length&&d.map.push(0,0,d.content.appendChild(Jg(a.display.measure))),0==e?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}return h&&/\bcm-tab\b/.test(d.content.lastChild.className)&&(d.content.className="cm-tab-wrap-hack"),Pf(a,"renderLine",a,b.line,d.pre),d.pre.className&&(d.textClass=Cg(d.pre.className,d.textClass||"")),d}function Te(a){var b=tg("span","\u2022","cm-invalidchar");return b.title="\\u"+a.charCodeAt(0).toString(16),b.setAttribute("aria-label",b.title),b}function Ue(a,b,c,d,e,h,i){if(b){var j=a.splitSpaces?b.replace(/ {3,}/g,Ve):b,k=a.cm.state.specialChars,l=!1;if(k.test(b))for(var m=document.createDocumentFragment(),n=0;;){k.lastIndex=n;var o=k.exec(b),p=o?o.index-n:b.length-n;if(p){var q=document.createTextNode(j.slice(n,n+p));f&&9>g?m.appendChild(tg("span",[q])):m.appendChild(q),a.map.push(a.pos,a.pos+p,q),a.col+=p,a.pos+=p}if(!o)break;if(n+=p+1," "==o[0]){var r=a.cm.options.tabSize,s=r-a.col%r,q=m.appendChild(tg("span",eg(s),"cm-tab"));q.setAttribute("role","presentation"),q.setAttribute("cm-text"," "),a.col+=s}else if("\r"==o[0]||"\n"==o[0]){var q=m.appendChild(tg("span","\r"==o[0]?"\u240d":"\u2424","cm-invalidchar"));q.setAttribute("cm-text",o[0]),a.col+=1}else{var q=a.cm.options.specialCharPlaceholder(o[0]);q.setAttribute("cm-text",o[0]),f&&9>g?m.appendChild(tg("span",[q])):m.appendChild(q),a.col+=1}a.map.push(a.pos,a.pos+1,q),a.pos++}else{a.col+=b.length;var m=document.createTextNode(j);a.map.push(a.pos,a.pos+b.length,m),f&&9>g&&(l=!0),a.pos+=b.length}if(c||d||e||l||i){var t=c||"";d&&(t+=d),e&&(t+=e);var u=tg("span",[m],t,i);return h&&(u.title=h),a.content.appendChild(u)}a.content.appendChild(m)}}function Ve(a){for(var b=" ",c=0;cj&&m.from<=j)break}if(m.to>=k)return a(c,d,e,f,g,h,i);a(c,d.slice(0,m.to-j),e,f,null,h,i),f=null,d=d.slice(m.to-j),j=m.to}}}function Xe(a,b,c,d){var e=!d&&c.widgetNode;e&&a.map.push(a.pos,a.pos+b,e),!d&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",c.id)),e&&(a.cm.display.input.setUneditable(e),a.content.appendChild(e)),a.pos+=b}function Ye(a,b,c){var d=a.markedSpans,e=a.text,f=0;if(d)for(var k,l,n,o,p,q,r,h=e.length,i=0,g=1,j="",m=0;;){if(m==i){n=o=p=q=l="",r=null,m=1/0;for(var s=[],t=0;ti||v.collapsed&&u.to==i&&u.from==i)?(null!=u.to&&u.to!=i&&m>u.to&&(m=u.to,o=""),v.className&&(n+=" "+v.className),v.css&&(l=v.css),v.startStyle&&u.from==i&&(p+=" "+v.startStyle),v.endStyle&&u.to==m&&(o+=" "+v.endStyle),v.title&&!q&&(q=v.title),v.collapsed&&(!r||pe(r.marker,v)<0)&&(r=u)):u.from>i&&m>u.from&&(m=u.from)}if(r&&(r.from||0)==i){if(Xe(b,(null==r.to?h+1:r.to)-i,r.marker,null==r.from),null==r.to)return;r.to==i&&(r=!1)}if(!r&&s.length)for(var t=0;t=h)break;for(var w=Math.min(h,m);;){if(j){var x=i+j.length;if(!r){var y=x>w?j.slice(0,w-i):j;b.addToken(b,y,k?k+n:n,p,i+y.length==m?o:"",q,l)}if(x>=w){j=j.slice(w-i),i=w;break}i=x,p=""}j=e.slice(f,f=c[g++]),k=Re(c[g++],b.cm.options)}}else for(var g=1;gc;++c)f.push(new Ee(j[c],e(c),d));return f}var h=b.from,i=b.to,j=b.text,k=hf(a,h.line),l=hf(a,i.line),m=fg(j),n=e(j.length-1),o=i.line-h.line;if(b.full)a.insert(0,g(0,j.length)),a.remove(j.length,a.size-j.length);else if(Ze(a,b)){var p=g(0,j.length-1);f(l,l.text,n),o&&a.remove(h.line,o),p.length&&a.insert(h.line,p)}else if(k==l)if(1==j.length)f(k,k.text.slice(0,h.ch)+m+k.text.slice(i.ch),n);else{var p=g(1,j.length-1);p.push(new Ee(m+k.text.slice(i.ch),n,d)),f(k,k.text.slice(0,h.ch)+j[0],e(0)),a.insert(h.line+1,p)}else if(1==j.length)f(k,k.text.slice(0,h.ch)+j[0]+l.text.slice(i.ch),e(0)),a.remove(h.line+1,o);else{f(k,k.text.slice(0,h.ch)+j[0],e(0)),f(l,m+l.text.slice(i.ch),n);var p=g(1,j.length-1);o>1&&a.remove(h.line+1,o-1),a.insert(h.line+1,p)}Rf(a,"change",a,b)}function _e(a){this.lines=a,this.parent=null;for(var b=0,c=0;bb||b>=a.size)throw new Error("There is no line "+(b+a.first)+" in the document.");for(var c=a;!c.lines;)for(var d=0;;++d){var e=c.children[d],f=e.chunkSize();if(f>b){c=e;break}b-=f}return c.lines[b]}function jf(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 kf(a,b,c){var d=[];return a.iter(b,c,function(a){d.push(a.text)}),d}function lf(a,b){var c=b-a.height;if(c)for(var d=a;d;d=d.parent)d.height+=c}function mf(a){if(null==a.parent)return null;for(var b=a.parent,c=hg(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 nf(a,b){var c=a.first;a:do{for(var d=0;db){a=e;continue a}b-=f,c+=e.chunkSize()}return c}while(!a.lines);for(var d=0;db)break;b-=h}return c+d}function of(a){a=ue(a);for(var b=0,c=a.parent,d=0;d1&&!a.done[a.done.length-2].ranges?(a.done.pop(),fg(a.done)):void 0}function uf(a,b,c,d){var e=a.history;e.undone.length=0;var g,f=+new Date;if((e.lastOp==d||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&a.cm&&e.lastModTime>f-a.cm.options.historyEventDelay||"*"==b.origin.charAt(0)))&&(g=tf(e,e.lastOp==d))){var h=fg(g.changes);0==ra(b.from,b.to)&&0==ra(b.from,h.to)?h.to=dd(b):g.changes.push(rf(a,b))}else{var i=fg(e.done);for(i&&i.ranges||xf(a.sel,e.done),g={changes:[rf(a,b)],generation:e.generation},e.done.push(g);e.done.length>e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift()}e.done.push(c),e.generation=++e.maxGeneration,e.lastModTime=e.lastSelTime=f,e.lastOp=e.lastSelOp=d,e.lastOrigin=e.lastSelOrigin=b.origin,h||Pf(a,"historyAdded")}function vf(a,b,c,d){var e=b.charAt(0);return"*"==e||"+"==e&&c.ranges.length==d.ranges.length&&c.somethingSelected()==d.somethingSelected()&&new Date-a.history.lastSelTime<=(a.cm?a.cm.options.historyEventDelay:500)}function wf(a,b,c,d){var e=a.history,f=d&&d.origin;c==e.lastSelOp||f&&e.lastSelOrigin==f&&(e.lastModTime==e.lastSelTime&&e.lastOrigin==f||vf(a,f,fg(e.done),b))?e.done[e.done.length-1]=b:xf(b,e.done),e.lastSelTime=+new Date,e.lastSelOrigin=f,e.lastSelOp=c,d&&d.clearRedo!==!1&&sf(e.undone)}function xf(a,b){var c=fg(b);c&&c.ranges&&c.equals(a)||b.push(a)}function yf(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 zf(a){if(!a)return null;for(var c,b=0;b-1&&(fg(h)[l]=j[l],delete j[l])}}}return e}function Cf(a,b,c,d){c0?d.slice():Mf:d||Mf}function Rf(a,b){function f(a){return function(){a.apply(null,d)}}var c=Nf(a,b,!1);if(c.length){var e,d=Array.prototype.slice.call(arguments,2);Vb?e=Vb.delayedCallbacks:Qf?e=Qf:(e=Qf=[],setTimeout(Sf,0));for(var g=0;g0}function Wf(a){a.prototype.on=function(a,b){Lf(this,a,b)},a.prototype.off=function(a,b){Of(this,a,b)}}function ag(){this.id=null}function eg(a){for(;dg.length<=a;)dg.push(fg(dg)+" ");return dg[a]}function fg(a){return a[a.length-1]}function hg(a,b){for(var c=0;c-1&&og(a)?!0:b.test(a):og(a)}function qg(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function sg(a){return a.charCodeAt(0)>=768&&rg.test(a)}function tg(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f0;--b)a.removeChild(a.firstChild);return a}function wg(a,b){return vg(a).appendChild(b)}function yg(){for(var a=document.activeElement;a&&a.root&&a.root.activeElement;)a=a.root.activeElement;return a}function zg(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function Cg(a,b){for(var c=a.split(" "),d=0;d2&&!(f&&8>g))}var c=Ig?tg("span","\u200b"):tg("span","\xa0",null,"display: inline-block; width: 1px; margin-right: -1px");return c.setAttribute("cm-text",""),c}function Lg(a){if(null!=Kg)return Kg;var b=wg(a,document.createTextNode("A\u062eA")),c=ug(b,0,1).getBoundingClientRect();if(!c||c.left==c.right)return!1;var d=ug(b,1,2).getBoundingClientRect();return Kg=d.right-c.right<3}function Qg(a){if(null!=Pg)return Pg;var b=wg(a,tg("span","x")),c=b.getBoundingClientRect(),d=ug(b,0,1).getBoundingClientRect();return Pg=Math.abs(c.left-d.left)>1}function Sg(a,b,c,d){if(!a)return d(b,c,"ltr");for(var e=!1,f=0;fb||b==c&&g.to==b)&&(d(Math.max(g.from,b),Math.min(g.to,c),1==g.level?"rtl":"ltr"),e=!0)}e||d(b,c,"ltr")}function Tg(a){return a.level%2?a.to:a.from}function Ug(a){return a.level%2?a.from:a.to}function Vg(a){var b=pf(a);return b?Tg(b[0]):0}function Wg(a){var b=pf(a);return b?Ug(fg(b)):a.text.length}function Xg(a,b){var c=hf(a.doc,b),d=ue(c);d!=c&&(b=mf(d));var e=pf(d),f=e?e[0].level%2?Wg(d):Vg(d):0;return qa(b,f)}function Yg(a,b){for(var c,d=hf(a.doc,b);c=se(d);)d=c.find(1,!0).line,b=null;var e=pf(d),f=e?e[0].level%2?Vg(d):Wg(d):d.text.length;return qa(null==b?mf(d):b,f)}function Zg(a,b){var c=Xg(a,b.line),d=hf(a.doc,c.line),e=pf(d);if(!e||0==e[0].level){var f=Math.max(0,d.text.search(/\S/)),g=b.line==c.line&&b.ch<=f&&b.ch;return qa(c.line,g?0:f)}return c}function $g(a,b,c){var d=a[0].level;return b==d?!0:c==d?!1:c>b}function ah(a,b){_g=null;for(var d,c=0;cb)return c;if(e.from==b||e.to==b){if(null!=d)return $g(a,e.level,a[d].level)?(e.from!=e.to&&(_g=d),c):(e.from!=e.to&&(_g=c),d);d=c}}return d}function bh(a,b,c,d){if(!d)return b+c;do b+=c;while(b>0&&sg(a.text.charAt(b)));return b}function ch(a,b,c,d){var e=pf(a);if(!e)return dh(a,b,c,d);for(var f=ah(e,b),g=e[f],h=bh(a,b,g.level%2?-c:c,d);;){if(h>g.from&&h0==g.level%2?g.to:g.from);if(g=e[f+=c],!g)return null;h=c>0==g.level%2?bh(a,g.to,-1,d):bh(a,g.from,1,d)}}function dh(a,b,c,d){var e=b+c;if(d)for(;e>0&&sg(a.text.charAt(e));)e+=c;return 0>e||e>a.text.length?null:e}var a=navigator.userAgent,b=navigator.platform,c=/gecko\/\d/i.test(a),d=/MSIE \d/.test(a),e=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(a),f=d||e,g=f&&(d?document.documentMode||6:e[1]),h=/WebKit\//.test(a),i=h&&/Qt\/\d+\.\d+/.test(a),j=/Chrome\//.test(a),k=/Opera\//.test(a),l=/Apple Computer/.test(navigator.vendor),m=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(a),n=/PhantomJS/.test(a),o=/AppleWebKit/.test(a)&&/Mobile\/\w+/.test(a),p=o||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(a),q=o||/Mac/.test(b),r=/win/i.test(b),s=k&&a.match(/Version\/(\d*\.\d*)/);s&&(s=Number(s[1])),s&&s>=15&&(k=!1,h=!0);var t=q&&(i||k&&(null==s||12.11>s)),u=c||f&&g>=9,v=!1,w=!1;M.prototype=lg({update:function(a){var b=a.scrollWidth>a.clientWidth+1,c=a.scrollHeight>a.clientHeight+1,d=a.nativeBarWidth;if(c){this.vert.style.display="block",this.vert.style.bottom=b?d+"px":"0";var e=a.viewHeight-(b?d:0);this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+e)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(b){this.horiz.style.display="block",this.horiz.style.right=c?d+"px":"0",this.horiz.style.left=a.barLeft+"px";var f=a.viewWidth-a.barLeft-(c?d:0);this.horiz.firstChild.style.width=a.scrollWidth-a.clientWidth+f+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedOverlay&&a.clientHeight>0&&(0==d&&this.overlayHack(),this.checkedOverlay=!0),{right:c?d:0,bottom:b?d:0}},setScrollLeft:function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a)},setScrollTop:function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a)},overlayHack:function(){var a=q&&!m?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=a;var b=this,c=function(a){Jf(a)!=b.vert&&Jf(a)!=b.horiz&&fc(b.cm,wc)(a)};Lf(this.vert,"mousedown",c),Lf(this.horiz,"mousedown",c)},clear:function(){var a=this.horiz.parentNode;a.removeChild(this.horiz),a.removeChild(this.vert)}},M.prototype),N.prototype=lg({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},N.prototype),x.scrollbarModel={"native":M,"null":N},W.prototype.signal=function(a,b){Vf(a,b)&&this.events.push(arguments)},W.prototype.finish=function(){for(var a=0;a=9&&b.hasSelection&&(b.hasSelection=null),b.poll()}),Lf(e,"paste",function(a){return za(a,c)?!0:(c.state.pasteIncoming=!0,void b.fastPoll())}),Lf(e,"cut",h),Lf(e,"copy",h),Lf(a.scroller,"paste",function(d){uc(a,d)||(c.state.pasteIncoming=!0,b.focus())}),Lf(a.lineSpace,"selectstart",function(b){uc(a,b)||Ff(b)}),Lf(e,"compositionstart",function(){ +var a=c.getCursor("from");b.composing&&b.composing.range.clear(),b.composing={start:a,range:c.markText(a,c.getCursor("to"),{className:"CodeMirror-composing"})}}),Lf(e,"compositionend",function(){b.composing&&(b.poll(),b.composing.range.clear(),b.composing=null)})},prepareSelection:function(){var a=this.cm,b=a.display,c=a.doc,d=gb(a);if(a.options.moveInputWithCursor){var e=Nb(a,c.sel.primary().head,"div"),f=b.wrapper.getBoundingClientRect(),g=b.lineDiv.getBoundingClientRect();d.teTop=Math.max(0,Math.min(b.wrapper.clientHeight-10,e.top+g.top-f.top)),d.teLeft=Math.max(0,Math.min(b.wrapper.clientWidth-10,e.left+g.left-f.left))}return d},showSelection:function(a){var b=this.cm,c=b.display;wg(c.cursorDiv,a.cursors),wg(c.selectionDiv,a.selection),null!=a.teTop&&(this.wrapper.style.top=a.teTop+"px",this.wrapper.style.left=a.teLeft+"px")},reset:function(a){if(!this.contextMenuPending){var b,c,d=this.cm,e=d.doc;if(d.somethingSelected()){this.prevInput="";var h=e.sel.primary();b=Og&&(h.to().line-h.from().line>100||(c=d.getSelection()).length>1e3);var i=b?"-":c||d.getSelection();this.textarea.value=i,d.state.focused&&gg(this.textarea),f&&g>=9&&(this.hasSelection=i)}else a||(this.prevInput=this.textarea.value="",f&&g>=9&&(this.hasSelection=null));this.inaccurateSelection=b}},getField:function(){return this.textarea},supportsTouch:function(){return!1},focus:function(){if("nocursor"!=this.cm.options.readOnly&&(!p||yg()!=this.textarea))try{this.textarea.focus()}catch(a){}},blur:function(){this.textarea.blur()},resetPosition:function(){this.wrapper.style.top=this.wrapper.style.left=0},receivedFocus:function(){this.slowPoll()},slowPoll:function(){var a=this;a.pollingFast||a.polling.set(this.cm.options.pollInterval,function(){a.poll(),a.cm.state.focused&&a.slowPoll()})},fastPoll:function(){function c(){var d=b.poll();d||a?(b.pollingFast=!1,b.slowPoll()):(a=!0,b.polling.set(60,c))}var a=!1,b=this;b.pollingFast=!0,b.polling.set(20,c)},poll:function(){var a=this.cm,b=this.textarea,c=this.prevInput;if(this.contextMenuPending||!a.state.focused||Ng(b)&&!c&&!this.composing||wa(a)||a.options.disableInput||a.state.keySeq)return!1;var d=b.value;if(d==c&&!a.somethingSelected())return!1;if(f&&g>=9&&this.hasSelection===d||q&&/[\uf700-\uf7ff]/.test(d))return a.display.input.reset(),!1;if(a.doc.sel==a.display.selForContextMenu){var e=d.charCodeAt(0);if(8203!=e||c||(c="\u200b"),8666==e)return this.reset(),this.cm.execCommand("undo")}for(var h=0,i=Math.min(c.length,d.length);i>h&&c.charCodeAt(h)==d.charCodeAt(h);)++h;var j=this;return ec(a,function(){ya(a,d.slice(h),c.length-h,null,j.composing?"*compose":null),d.length>1e3||d.indexOf("\n")>-1?b.value=j.prevInput="":j.prevInput=d,j.composing&&(j.composing.range.clear(),j.composing.range=a.markText(j.composing.start,a.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},ensurePolled:function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},onKeyPress:function(){f&&g>=9&&(this.hasSelection=null),this.fastPoll()},onContextMenu:function(a){function o(){if(null!=e.selectionStart){var a=c.somethingSelected(),f="\u200b"+(a?e.value:"");e.value="\u21da",e.value=f,b.prevInput=a?"":"\u200b",e.selectionStart=1,e.selectionEnd=f.length,d.selForContextMenu=c.doc.sel}}function p(){if(b.contextMenuPending=!1,b.wrapper.style.position="relative",e.style.cssText=m,f&&9>g&&d.scrollbars.setScrollTop(d.scroller.scrollTop=j),null!=e.selectionStart){(!f||f&&9>g)&&o();var a=0,h=function(){d.selForContextMenu==c.doc.sel&&0==e.selectionStart&&e.selectionEnd>0&&"\u200b"==b.prevInput?fc(c,Nd.selectAll)(c):a++<10?d.detectingSelectAll=setTimeout(h,500):d.input.reset()};d.detectingSelectAll=setTimeout(h,200)}}var b=this,c=b.cm,d=c.display,e=b.textarea,i=vc(c,a),j=d.scroller.scrollTop;if(i&&!k){var l=c.options.resetSelectionOnContextMenu;l&&-1==c.doc.sel.contains(i)&&fc(c,_a)(c.doc,Oa(i),Zf);var m=e.style.cssText;if(b.wrapper.style.position="absolute",e.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(a.clientY-5)+"px; left: "+(a.clientX-5)+"px; z-index: 1000; background: "+(f?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",h)var n=window.scrollY;if(d.input.focus(),h&&window.scrollTo(null,n),d.input.reset(),c.somethingSelected()||(e.value=b.prevInput=" "),b.contextMenuPending=!0,d.selForContextMenu=c.doc.sel,clearTimeout(d.detectingSelectAll),f&&g>=9&&o(),u){If(a);var q=function(){Of(window,"mouseup",q),setTimeout(p,20)};Lf(window,"mouseup",q)}else setTimeout(p,50)}},readOnlyChanged:function(a){a||this.reset()},setUneditable:jg,needsContentAttribute:!1},Da.prototype),Fa.prototype=lg({init:function(a){function e(a){if(c.somethingSelected())xa=c.getSelections(),"cut"==a.type&&c.replaceSelection("",null,"cut");else{if(!c.options.lineWiseCopyCut)return;var b=Ba(c);xa=b.text,"cut"==a.type&&c.operation(function(){c.setSelections(b.ranges,0,Zf),c.replaceSelection("",null,"cut")})}if(a.clipboardData&&!o)a.preventDefault(),a.clipboardData.clearData(),a.clipboardData.setData("text/plain",xa.join("\n"));else{var d=Ea(),e=d.firstChild;c.display.lineSpace.insertBefore(d,c.display.lineSpace.firstChild),e.value=xa.join("\n");var f=document.activeElement;gg(e),setTimeout(function(){c.display.lineSpace.removeChild(d),f.focus()},50)}}var b=this,c=b.cm,d=b.div=a.lineDiv;Ca(d),Lf(d,"paste",function(a){za(a,c)}),Lf(d,"compositionstart",function(a){var d=a.data;if(b.composing={sel:c.doc.sel,data:d,startData:d},d){var e=c.doc.sel.primary(),f=c.getLine(e.head.line),g=f.indexOf(d,Math.max(0,e.head.ch-d.length));g>-1&&g<=e.head.ch&&(b.composing.sel=Oa(qa(e.head.line,g),qa(e.head.line,g+d.length)))}}),Lf(d,"compositionupdate",function(a){b.composing.data=a.data}),Lf(d,"compositionend",function(a){var c=b.composing;c&&(a.data==c.startData||/\u200b/.test(a.data)||(c.data=a.data),setTimeout(function(){c.handled||b.applyComposition(c),b.composing==c&&(b.composing=null)},50))}),Lf(d,"touchstart",function(){b.forceCompositionEnd()}),Lf(d,"input",function(){b.composing||(wa(c)||!b.pollContent())&&ec(b.cm,function(){kc(c)})}),Lf(d,"copy",e),Lf(d,"cut",e)},prepareSelection:function(){var a=gb(this.cm,!1);return a.focus=this.cm.state.focused,a},showSelection:function(a){a&&this.cm.display.view.length&&(a.focus&&this.showPrimarySelection(),this.showMultipleSelections(a))},showPrimarySelection:function(){var a=window.getSelection(),b=this.cm.doc.sel.primary(),d=Ia(this.cm,a.anchorNode,a.anchorOffset),e=Ia(this.cm,a.focusNode,a.focusOffset);if(!d||d.bad||!e||e.bad||0!=ra(ua(d,e),b.from())||0!=ra(ta(d,e),b.to())){var f=Ga(this.cm,b.from()),g=Ga(this.cm,b.to());if(f||g){var h=this.cm.display.view,i=a.rangeCount&&a.getRangeAt(0);if(f){if(!g){var j=h[h.length-1].measure,k=j.maps?j.maps[j.maps.length-1]:j.map;g={node:k[k.length-1],offset:k[k.length-2]-k[k.length-3]}}}else f={node:h[0].measure.map[2],offset:0};try{var l=ug(f.node,f.offset,g.offset,g.node)}catch(m){}l&&(a.removeAllRanges(),a.addRange(l),i&&null==a.anchorNode?a.addRange(i):c&&this.startGracePeriod()),this.rememberSelection()}}},startGracePeriod:function(){var a=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){a.gracePeriod=!1,a.selectionChanged()&&a.cm.operation(function(){a.cm.curOp.selectionChanged=!0})},20)},showMultipleSelections:function(a){wg(this.cm.display.cursorDiv,a.cursors),wg(this.cm.display.selectionDiv,a.selection)},rememberSelection:function(){var a=window.getSelection();this.lastAnchorNode=a.anchorNode,this.lastAnchorOffset=a.anchorOffset,this.lastFocusNode=a.focusNode,this.lastFocusOffset=a.focusOffset},selectionInEditor:function(){var a=window.getSelection();if(!a.rangeCount)return!1;var b=a.getRangeAt(0).commonAncestorContainer;return xg(this.div,b)},focus:function(){"nocursor"!=this.cm.options.readOnly&&this.div.focus()},blur:function(){this.div.blur()},getField:function(){return this.div},supportsTouch:function(){return!0},receivedFocus:function(){function b(){a.cm.state.focused&&(a.pollSelection(),a.polling.set(a.cm.options.pollInterval,b))}var a=this;this.selectionInEditor()?this.pollSelection():ec(this.cm,function(){a.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,b)},selectionChanged:function(){var a=window.getSelection();return a.anchorNode!=this.lastAnchorNode||a.anchorOffset!=this.lastAnchorOffset||a.focusNode!=this.lastFocusNode||a.focusOffset!=this.lastFocusOffset},pollSelection:function(){if(!this.composing&&!this.gracePeriod&&this.selectionChanged()){var a=window.getSelection(),b=this.cm;this.rememberSelection();var c=Ia(b,a.anchorNode,a.anchorOffset),d=Ia(b,a.focusNode,a.focusOffset);c&&d&&ec(b,function(){_a(b.doc,Oa(c,d),Zf),(c.bad||d.bad)&&(b.curOp.selectionChanged=!0)})}},pollContent:function(){var a=this.cm,b=a.display,c=a.doc.sel.primary(),d=c.from(),e=c.to();if(d.lineb.viewTo-1)return!1;var f;if(d.line==b.viewFrom||0==(f=nc(a,d.line)))var g=mf(b.view[0].line),h=b.view[0].node;else var g=mf(b.view[f].line),h=b.view[f-1].node.nextSibling;var i=nc(a,e.line);if(i==b.view.length-1)var j=b.viewTo-1,k=b.lineDiv.lastChild;else var j=mf(b.view[i+1].line)-1,k=b.view[i+1].node.previousSibling;for(var l=a.doc.splitLines(Ka(a,h,k,g,j)),m=jf(a.doc,qa(g,0),qa(j,hf(a.doc,j).text.length));l.length>1&&m.length>1;)if(fg(l)==fg(m))l.pop(),m.pop(),j--;else{if(l[0]!=m[0])break;l.shift(),m.shift(),g++}for(var n=0,o=0,p=l[0],q=m[0],r=Math.min(p.length,q.length);r>n&&p.charCodeAt(n)==q.charCodeAt(n);)++n;for(var s=fg(l),t=fg(m),u=Math.min(s.length-(1==l.length?n:0),t.length-(1==m.length?n:0));u>o&&s.charCodeAt(s.length-o-1)==t.charCodeAt(t.length-o-1);)++o;l[l.length-1]=s.slice(0,s.length-o),l[0]=l[0].slice(n);var v=qa(g,n),w=qa(j,m.length?fg(m).length-o:0);return l.length>1||l[0]||ra(v,w)?(pd(a.doc,l,v,w,"+input"),!0):void 0},ensurePolled:function(){this.forceCompositionEnd()},reset:function(){this.forceCompositionEnd()},forceCompositionEnd:function(){this.composing&&!this.composing.handled&&(this.applyComposition(this.composing),this.composing.handled=!0,this.div.blur(),this.div.focus())},applyComposition:function(a){wa(this.cm)?fc(this.cm,kc)(this.cm):a.data&&a.data!=a.startData&&fc(this.cm,ya)(this.cm,a.data,0,a.sel)},setUneditable:function(a){a.contentEditable="false"},onKeyPress:function(a){a.preventDefault(),wa(this.cm)||fc(this.cm,ya)(this.cm,String.fromCharCode(null==a.charCode?a.keyCode:a.charCode),0)},readOnlyChanged:function(a){this.div.contentEditable=String("nocursor"!=a)},onContextMenu:jg,resetPosition:jg,needsContentAttribute:!0},Fa.prototype),x.inputStyles={textarea:Da,contenteditable:Fa},La.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(a){if(a==this)return!0;if(a.primIndex!=this.primIndex||a.ranges.length!=this.ranges.length)return!1;for(var b=0;b=0&&ra(a,d.to())<=0)return c}return-1}},Ma.prototype={from:function(){return ua(this.anchor,this.head)},to:function(){return ta(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var Sb,xc,yc,Bb={left:0,right:0,top:0,bottom:0},Vb=null,Wb=0,Ec=0,Lc=0,Mc=null;f?Mc=-.53:c?Mc=15:j?Mc=-.7:l&&(Mc=-1/3);var Nc=function(a){var b=a.wheelDeltaX,c=a.wheelDeltaY;return null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail),null==c&&a.detail&&a.axis==a.VERTICAL_AXIS?c=a.detail:null==c&&(c=a.wheelDelta),{x:b,y:c}};x.wheelEventPixels=function(a){var b=Nc(a);return b.x*=Mc,b.y*=Mc,b};var Rc=new ag,Vc=null,dd=x.changeEnd=function(a){return a.text?qa(a.from.line+a.text.length-1,fg(a.text).length+(1==a.text.length?a.from.ch:0)):a.to};x.prototype={constructor:x,focus:function(){window.focus(),this.display.input.focus()},setOption:function(a,b){var c=this.options,d=c[a];(c[a]!=b||"mode"==a)&&(c[a]=b,Dd.hasOwnProperty(a)&&fc(this,Dd[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"](Td(a))},removeKeyMap:function(a){for(var b=this.state.keyMaps,c=0;cc&&(xd(this,e.head.line,a,!0),c=e.head.line,d==this.doc.sel.primIndex&&vd(this));else{var f=e.from(),g=e.to(),h=Math.max(c,f.line);c=Math.min(this.lastLine(),g.line-(g.ch?0:1))+1;for(var i=h;c>i;++i)xd(this,i,a);var j=this.doc.sel.ranges;0==f.ch&&b.length==j.length&&j[d].from().ch>0&&Xa(this.doc,d,new Ma(f,j[d].to()),Zf)}}}),getTokenAt:function(a,b){return Ke(this,a,b)},getLineTokens:function(a,b){return Ke(this,qa(a),b,!0)},getTokenTypeAt:function(a){a=Qa(this.doc,a);var f,b=Ne(this,hf(this.doc,a.line)),c=0,d=(b.length-1)/2,e=a.ch;if(0==e)f=b[2];else for(;;){var g=c+d>>1;if((g?b[2*g-1]:0)>=e)d=g;else{if(!(b[2*g+1]h?f:0==h?null:f.slice(0,h-1)},getModeAt:function(a){var b=this.doc.mode;return b.innerMode?x.innerMode(b,this.getTokenAt(a).state).mode:b},getHelper:function(a,b){return this.getHelpers(a,b)[0]},getHelpers:function(a,b){var c=[];if(!Kd.hasOwnProperty(b))return c;var d=Kd[b],e=this.getModeAt(a);if("string"==typeof e[b])d[e[b]]&&c.push(d[e[b]]);else if(e[b])for(var f=0;fe&&(a=e,c=!0),d=hf(this.doc,a)}else d=a;return Kb(this,d,{top:0,left:0},b||"page").top+(c?this.doc.height-of(d):0)},defaultTextHeight:function(){return Tb(this.display)},defaultCharWidth:function(){return Ub(this.display)},setGutterMarker:gc(function(a,b,c){return yd(this.doc,a,"gutter",function(a){var d=a.gutterMarkers||(a.gutterMarkers={});return d[b]=c,!c&&qg(d)&&(a.gutterMarkers=null),!0})}),clearGutter:gc(function(a){var b=this,c=b.doc,d=c.first;c.iter(function(c){c.gutterMarkers&&c.gutterMarkers[a]&&(c.gutterMarkers[a]=null,lc(b,d,"gutter"),qg(c.gutterMarkers)&&(c.gutterMarkers=null)),++d})}),lineInfo:function(a){if("number"==typeof a){if(!Sa(this.doc,a))return null;var b=a;if(a=hf(this.doc,a),!a)return null}else{var b=mf(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.viewFrom,to:this.display.viewTo}},addWidget:function(a,b,c,d,e){var f=this.display;a=Nb(this,Qa(this.doc,a));var g=a.bottom,h=a.left;if(b.style.position="absolute",b.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(b),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&&sd(this,h,g,h+b.offsetWidth,g+b.offsetHeight)},triggerOnKeyDown:gc(Wc),triggerOnKeyPress:gc(Zc),triggerOnKeyUp:Yc,execCommand:function(a){return Nd.hasOwnProperty(a)?Nd[a].call(null,this):void 0},triggerElectric:gc(function(a){Aa(this,a)}),findPosH:function(a,b,c,d){var e=1;0>b&&(e=-1,b=-b);for(var f=0,g=Qa(this.doc,a);b>f&&(g=Ad(this.doc,g,e,c,d),!g.hitSide);++f);return g},moveH:gc(function(a,b){var c=this;c.extendSelectionsBy(function(d){return c.display.shift||c.doc.extend||d.empty()?Ad(c.doc,d.head,a,b,c.options.rtlMoveVisually):0>a?d.from():d.to()},_f)}),deleteH:gc(function(a,b){var c=this.doc.sel,d=this.doc;c.somethingSelected()?d.replaceSelection("",null,"+delete"):zd(this,function(c){var e=Ad(d,c.head,a,b,!1);return 0>a?{from:e,to:c.head}:{from:c.head,to:e}})}),findPosV:function(a,b,c,d){var e=1,f=d;0>b&&(e=-1,b=-b);for(var g=0,h=Qa(this.doc,a);b>g;++g){var i=Nb(this,h,"div");if(null==f?f=i.left:i.left=f,h=Bd(this,i,e,c),h.hitSide)break}return h},moveV:gc(function(a,b){var c=this,d=this.doc,e=[],f=!c.display.shift&&!d.extend&&d.sel.somethingSelected();if(d.extendSelectionsBy(function(g){if(f)return 0>a?g.from():g.to();var h=Nb(c,g.head,"div");null!=g.goalColumn&&(h.left=g.goalColumn),e.push(h.left);var i=Bd(c,h,a,b);return"page"==b&&g==d.sel.primary()&&ud(c,null,Mb(c,i,"div").top-h.top),i},_f),e.length)for(var g=0;g0&&h(c.charAt(d-1));)--d;for(;e.5)&&D(this),Pf(this,"refresh",this)}),swapDoc:gc(function(a){var b=this.doc;return b.cm=null,gf(this,a),Hb(this),this.display.input.reset(),this.scrollTo(a.scrollLeft,a.scrollTop),this.curOp.forceScroll=!0,Rf(this,"swapDoc",this,b),b}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},Wf(x);var Cd=x.defaults={},Dd=x.optionHandlers={},Fd=x.Init={toString:function(){return"CodeMirror.Init"}};Ed("value","",function(a,b){a.setValue(b)},!0),Ed("mode",null,function(a,b){a.doc.modeOption=b,z(a)},!0),Ed("indentUnit",2,z,!0),Ed("indentWithTabs",!1),Ed("smartIndent",!0),Ed("tabSize",4,function(a){A(a),Hb(a),kc(a)},!0),Ed("lineSeparator",null,function(a,b){if(a.doc.lineSep=b,b){var c=[],d=a.doc.first;a.doc.iter(function(a){for(var e=0;;){var f=a.text.indexOf(b,e);if(-1==f)break;e=f+b.length,c.push(qa(d,f))}d++});for(var e=c.length-1;e>=0;e--)pd(a.doc,b,c[e],qa(c[e].line,c[e].ch+b.length))}}),Ed("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(a,b,c){a.state.specialChars=new RegExp(b.source+(b.test(" ")?"":"| "),"g"),c!=x.Init&&a.refresh()}),Ed("specialCharPlaceholder",Te,function(a){a.refresh()},!0),Ed("electricChars",!0),Ed("inputStyle",p?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),Ed("rtlMoveVisually",!r),Ed("wholeLineUpdateBefore",!0),Ed("theme","default",function(a){E(a),F(a)},!0),Ed("keyMap","default",function(a,b,c){var d=Td(b),e=c!=x.Init&&Td(c);e&&e.detach&&e.detach(a,d),d.attach&&d.attach(a,e||null)}),Ed("extraKeys",null),Ed("lineWrapping",!1,B,!0),Ed("gutters",[],function(a){K(a.options),F(a)},!0),Ed("fixedGutter",!0,function(a,b){a.display.gutters.style.left=b?V(a.display)+"px":"0",a.refresh()},!0),Ed("coverGutterNextToScrollbar",!1,function(a){P(a)},!0),Ed("scrollbarStyle","native",function(a){O(a),P(a),a.display.scrollbars.setScrollTop(a.doc.scrollTop),a.display.scrollbars.setScrollLeft(a.doc.scrollLeft)},!0),Ed("lineNumbers",!1,function(a){K(a.options),F(a)},!0),Ed("firstLineNumber",1,F,!0),Ed("lineNumberFormatter",function(a){return a},F,!0),Ed("showCursorWhenSelecting",!1,fb,!0),Ed("resetSelectionOnContextMenu",!0),Ed("lineWiseCopyCut",!0),Ed("readOnly",!1,function(a,b){"nocursor"==b?(ad(a),a.display.input.blur(),a.display.disabled=!0):a.display.disabled=!1,a.display.input.readOnlyChanged(b)}),Ed("disableInput",!1,function(a,b){b||a.display.input.reset()},!0),Ed("dragDrop",!0,sc),Ed("allowDropFileTypes",null),Ed("cursorBlinkRate",530),Ed("cursorScrollMargin",0),Ed("cursorHeight",1,fb,!0),Ed("singleCursorHeightPerLine",!0,fb,!0),Ed("workTime",100),Ed("workDelay",100),Ed("flattenSpans",!0,A,!0),Ed("addModeClass",!1,A,!0),Ed("pollInterval",100),Ed("undoDepth",200,function(a,b){a.doc.history.undoDepth=b}),Ed("historyEventDelay",1250),Ed("viewportMargin",10,function(a){a.refresh()},!0),Ed("maxHighlightLength",1e4,A,!0),Ed("moveInputWithCursor",!0,function(a,b){b||a.display.input.resetPosition()}),Ed("tabindex",null,function(a,b){a.display.input.getField().tabIndex=b||""}),Ed("autofocus",null);var Gd=x.modes={},Hd=x.mimeModes={};x.defineMode=function(a,b){x.defaults.mode||"null"==a||(x.defaults.mode=a),arguments.length>2&&(b.dependencies=Array.prototype.slice.call(arguments,2)),Gd[a]=b},x.defineMIME=function(a,b){Hd[a]=b},x.resolveMode=function(a){if("string"==typeof a&&Hd.hasOwnProperty(a))a=Hd[a];else if(a&&"string"==typeof a.name&&Hd.hasOwnProperty(a.name)){var b=Hd[a.name];"string"==typeof b&&(b={name:b}),a=kg(b,a),a.name=b.name}else if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return x.resolveMode("application/xml");return"string"==typeof a?{name:a}:a||{name:"null"}},x.getMode=function(a,b){var b=x.resolveMode(b),c=Gd[b.name];if(!c)return x.getMode(a,"text/plain");var d=c(a,b);if(Id.hasOwnProperty(b.name)){var e=Id[b.name];for(var f in e)e.hasOwnProperty(f)&&(d.hasOwnProperty(f)&&(d["_"+f]=d[f]),d[f]=e[f])}if(d.name=b.name,b.helperType&&(d.helperType=b.helperType),b.modeProps)for(var f in b.modeProps)d[f]=b.modeProps[f];return d},x.defineMode("null",function(){return{token:function(a){a.skipToEnd()}}}),x.defineMIME("text/plain","null");var Id=x.modeExtensions={};x.extendMode=function(a,b){var c=Id.hasOwnProperty(a)?Id[a]:Id[a]={};lg(b,c)},x.defineExtension=function(a,b){x.prototype[a]=b},x.defineDocExtension=function(a,b){cf.prototype[a]=b},x.defineOption=Ed;var Jd=[];x.defineInitHook=function(a){Jd.push(a)};var Kd=x.helpers={};x.registerHelper=function(a,b,c){Kd.hasOwnProperty(a)||(Kd[a]=x[a]={_global:[]}),Kd[a][b]=c},x.registerGlobalHelper=function(a,b,c,d){x.registerHelper(a,b,d),Kd[a]._global.push({pred:c,val:d})};var Ld=x.copyState=function(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},Md=x.startState=function(a,b,c){return a.startState?a.startState(b,c):!0};x.innerMode=function(a,b){for(;a.innerMode;){var c=a.innerMode(b);if(!c||c.mode==a)break;b=c.state,a=c.mode}return c||{mode:a,state:b}};var Nd=x.commands={selectAll:function(a){a.setSelection(qa(a.firstLine(),0),qa(a.lastLine()),Zf)},singleSelection:function(a){a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Zf)},killLine:function(a){zd(a,function(b){if(b.empty()){var c=hf(a.doc,b.head.line).text.length;return b.head.ch==c&&b.head.line0)e=new qa(e.line,e.ch+1),a.replaceRange(f.charAt(e.ch-1)+f.charAt(e.ch-2),qa(e.line,e.ch-2),e,"+transpose");else if(e.line>a.doc.first){var g=hf(a.doc,e.line-1).text;g&&a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),qa(e.line-1,g.length-1),qa(e.line,1),"+transpose")}c.push(new Ma(e,e))}a.setSelections(c)})},newlineAndIndent:function(a){ec(a,function(){for(var b=a.listSelections().length,c=0;b>c;c++){var d=a.listSelections()[c];a.replaceRange(a.doc.lineSeparator(),d.anchor,d.head,"+input"),a.indentLine(d.from().line+1,null,!0)}vd(a)})},toggleOverwrite:function(a){a.toggleOverwrite()}},Od=x.keyMap={};Od.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Od.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","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","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Od.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"},Od.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","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":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Od["default"]=q?Od.macDefault:Od.pcDefault,x.normalizeKeyMap=function(a){var b={};for(var c in a)if(a.hasOwnProperty(c)){var d=a[c];if(/^(name|fallthrough|(de|at)tach)$/.test(c))continue;if("..."==d){delete a[c];continue}for(var e=ig(c.split(" "),Pd),f=0;f=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.posb},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.lastColumnPos0?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)},hideFirstChars:function(a,b){this.lineStart+=a;try{return b()}finally{this.lineStart-=a}}};var Vd=0,Wd=x.TextMarker=function(a,b){this.lines=[],this.type=b,this.doc=a,this.id=++Vd};Wf(Wd),Wd.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;if(b&&Xb(a),Vf(this,"clear")){var c=this.find();c&&Rf(this,"clear",c.from,c.to)}for(var d=null,e=null,f=0;fa.display.maxLineLength&&(a.display.maxLine=i,a.display.maxLineLength=j,a.display.maxLineChanged=!0)}null!=d&&a&&this.collapsed&&kc(a,d,e+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&cb(a.doc)),a&&Rf(a,"markerCleared",a,this),b&&Zb(a),this.parent&&this.parent.clear()}},Wd.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var c,d,e=0;ec;++c){var e=this.lines[c];this.height-=e.height,Ge(e),Rf(e,"delete")}this.lines.splice(a,b)},collapse:function(a){a.push.apply(a,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;da;++a)if(c(this.lines[a]))return!0}},af.prototype={chunkSize:function(){return this.size},removeInner:function(a,b){this.size-=b;for(var c=0;ca){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&&(this.children.length>1||!(this.children[0]instanceof _e))){var h=[];this.collapse(h),this.children=[new _e(h)],this.children[0].parent=this}},collapse:function(a){for(var b=0;b=a){if(e.insertInner(a,b,c),e.lines&&e.lines.length>50){for(;e.lines.length>50;){var g=e.lines.splice(e.lines.length-25,25),h=new _e(g);e.height-=h.height,this.children.splice(d+1,0,h),h.parent=this}this.maybeSpill()}break}a-=f}},maybeSpill:function(){if(!(this.children.length<=10)){var a=this;do{var b=a.children.splice(a.children.length-5,5),c=new af(b);if(a.parent){a.size-=c.size,a.height-=c.height;var e=hg(a.parent.children,a);a.parent.children.splice(e+1,0,c)}else{var d=new af(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;da){var g=Math.min(b,f-a);if(e.iterN(a,g,c))return!0;if(0==(b-=g))break;a=0}else a-=f}}};var bf=0,cf=x.Doc=function(a,b,c,d){if(!(this instanceof cf))return new cf(a,b,c,d);null==c&&(c=0),af.call(this,[new _e([new Ee("",null)])]),this.first=c,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=c;var e=qa(c,0);this.sel=Oa(e),this.history=new qf(null),this.id=++bf,this.modeOption=b,this.lineSep=d,"string"==typeof a&&(a=this.splitLines(a)),$e(this,{from:e,to:e,text:a}),_a(this,Oa(e),Zf)};cf.prototype=kg(af.prototype,{constructor:cf,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;d=0;f--)jd(this,d[f]);h?$a(this,h):this.cm&&vd(this.cm)}),undo:hc(function(){ld(this,"undo")}),redo:hc(function(){ld(this,"redo")}),undoSelection:hc(function(){ld(this,"undo",!0)}),redoSelection:hc(function(){ld(this,"redo",!0)}),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,c=0,d=0;d=a.ch)&&b.push(e.marker.parent||e.marker)}return b},findMarks:function(a,b,c){a=Qa(this,a),b=Qa(this,b);var d=[],e=a.line;return this.iter(a.line,b.line+1,function(f){var g=f.markedSpans;if(g)for(var h=0;hi.to||null==i.from&&e!=a.line||e==b.line&&i.from>b.ch||c&&!c(i.marker)||d.push(i.marker.parent||i.marker)}++e}),d},getAllMarks:function(){var a=[];return this.iter(function(b){var c=b.markedSpans;if(c)for(var d=0;da?(b=a,!0):(a-=e,void++c)}),Qa(this,qa(c,b))},indexFromPos:function(a){a=Qa(this,a);var b=a.ch;return a.lineb&&(b=a.from),null!=a.to&&a.toh||h>=b)return g+(b-f);g+=h-f,g+=c-g%c,f=h+1}},cg=x.findColumn=function(a,b,c){for(var d=0,e=0;;){var f=a.indexOf(" ",d);-1==f&&(f=a.length);var g=f-d;if(f==a.length||e+g>=b)return d+Math.min(g,b-e);if(e+=f-d,e+=c-e%c,d=f+1,e>=b)return d}},dg=[""],gg=function(a){a.select()};o?gg=function(a){a.selectionStart=0,a.selectionEnd=a.value.length}:f&&(gg=function(a){try{a.select()}catch(b){}});var ug,ng=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,og=x.isWordChar=function(a){return/\w/.test(a)||a>"\x80"&&(a.toUpperCase()!=a.toLowerCase()||ng.test(a))},rg=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ug=document.createRange?function(a,b,c,d){var e=document.createRange();return e.setEnd(d||a,c),e.setStart(a,b),e}:function(a,b,c){var d=document.body.createTextRange();try{d.moveToElementText(a.parentNode)}catch(e){return d}return d.collapse(!0),d.moveEnd("character",c),d.moveStart("character",b),d};var xg=x.contains=function(a,b){if(3==b.nodeType&&(b=b.parentNode),a.contains)return a.contains(b);do if(11==b.nodeType&&(b=b.host),b==a)return!0;while(b=b.parentNode)};f&&11>g&&(yg=function(){try{return document.activeElement}catch(a){return document.body}});var Ig,Kg,Ag=x.rmClass=function(a,b){var c=a.className,d=zg(b).exec(c);if(d){var e=c.slice(d.index+d[0].length);a.className=c.slice(0,d.index)+(e?d[1]+e:"")}},Bg=x.addClass=function(a,b){var c=a.className;zg(b).test(c)||(a.className+=(c?" ":"")+b)},Eg=!1,Hg=function(){if(f&&9>g)return!1;var a=tg("div");return"draggable"in a||"dragDrop"in a}(),Mg=x.splitLines=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/)},Ng=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},Og=function(){var a=tg("div");return"oncopy"in a?!0:(a.setAttribute("oncopy","return;"),"function"==typeof a.oncopy)}(),Pg=null,Rg=x.keyNames={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:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};!function(){for(var a=0;10>a;a++)Rg[a+48]=Rg[a+96]=String(a);for(var a=65;90>=a;a++)Rg[a]=String.fromCharCode(a);for(var a=1;12>=a;a++)Rg[a+111]=Rg[a+63235]="F"+a}();var _g,eh=function(){function c(c){return 247>=c?a.charAt(c):c>=1424&&1524>=c?"R":c>=1536&&1773>=c?b.charAt(c-1536):c>=1774&&2220>=c?"r":c>=8192&&8203>=c?"w":8204==c?"b":"L"}function j(a,b,c){this.level=a,this.from=b,this.to=c}var a="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",b="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",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 m,b=a.length,k=[],l=0;b>l;++l)k.push(m=c(a.charCodeAt(l)));for(var l=0,n=i;b>l;++l){var m=k[l];"m"==m?k[l]=n:n=m}for(var l=0,o=i;b>l;++l){var m=k[l];"1"==m&&"r"==o?k[l]="n":f.test(m)&&(o=m,"r"==m&&(k[l]="R"))}for(var l=1,n=k[0];b-1>l;++l){var m=k[l];"+"==m&&"1"==n&&"1"==k[l+1]?k[l]="1":","!=m||n!=k[l+1]||"1"!=n&&"n"!=n||(k[l]=n),n=m}for(var l=0;b>l;++l){var m=k[l];if(","==m)k[l]="N";else if("%"==m){for(var p=l+1;b>p&&"%"==k[p];++p);for(var q=l&&"!"==k[l-1]||b>p&&"1"==k[p]?"1":"N",r=l;p>r;++r)k[r]=q;l=p-1}}for(var l=0,o=i;b>l;++l){var m=k[l];"L"==o&&"1"==m?k[l]="L":f.test(m)&&(o=m)}for(var l=0;b>l;++l)if(e.test(k[l])){for(var p=l+1;b>p&&e.test(k[p]);++p);for(var s="L"==(l?k[l-1]:i),t="L"==(b>p?k[p]:i),q=s||t?"L":"R",r=l;p>r;++r)k[r]=q;l=p-1}for(var v,u=[],l=0;b>l;)if(g.test(k[l])){var w=l;for(++l;b>l&&g.test(k[l]);++l);u.push(new j(0,w,l))}else{var x=l,y=u.length;for(++l;b>l&&"L"!=k[l];++l);for(var r=x;l>r;)if(h.test(k[r])){r>x&&u.splice(y,0,new j(1,x,r));var z=r;for(++r;l>r&&h.test(k[r]);++r);u.splice(y,0,new j(2,z,r)),x=r}else++r;l>x&&u.splice(y,0,new j(1,x,l))}return 1==u[0].level&&(v=a.match(/^\s+/))&&(u[0].from=v[0].length,u.unshift(new j(0,0,v[0].length))),1==fg(u).level&&(v=a.match(/\s+$/))&&(fg(u).to-=v[0].length,u.push(new j(0,b-v[0].length,b))),2==u[0].level&&u.unshift(new j(1,u[0].to,u[0].to)),u[0].level!=fg(u).level&&u.push(new j(u[0].level,b,b)),u}}();return x.version="5.8.1",x}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)}(function(a){"use strict";function b(a){for(var b={},c=0;c*\/]/.test(c)?u(null,"select-op"):"."==c&&a.match(/^-?[_a-z][_a-z0-9-]*/i)?u("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(c)?u(null,c):"u"==c&&a.match(/rl(-prefix)?\(/)||"d"==c&&a.match("omain(")||"r"==c&&a.match("egexp(")?(a.backUp(1),b.tokenize=x,u("property","word")):/[\w\\\-]/.test(c)?(a.eatWhile(/[\w\\\-]/),u("property","word")):u(null,null):/[\d.]/.test(a.peek())?(a.eatWhile(/[\w.%]/),u("number","unit")):a.match(/^-[\w\\\-]+/)?(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?u("variable-2","variable-definition"):u("variable-2","variable")):a.match(/^\w+-/)?u("meta","meta"):void 0}function w(a){return function(b,c){for(var e,d=!1;null!=(e=b.next());){if(e==a&&!d){")"==a&&b.backUp(1);break}d=!d&&"\\"==e}return(e==a||!d&&")"!=a)&&(c.tokenize=null),u("string","string")}}function x(a,b){return a.next(),a.match(/\s*[\"\')]/,!1)?b.tokenize=null:b.tokenize=w(")"),u(null,"(")}function y(a,b,c){this.type=a,this.indent=b,this.prev=c}function z(a,b,c,d){return a.context=new y(c,b.indentation()+(d===!1?0:e),a.context),c}function A(a){return a.context.prev&&(a.context=a.context.prev),a.context.type}function B(a,b,c){return E[c.context.type](a,b,c)}function C(a,b,c,d){for(var e=d||1;e>0;e--)c.context=c.context.prev;return B(a,b,c)}function D(a){var b=a.current().toLowerCase();t=p.hasOwnProperty(b)?"atom":o.hasOwnProperty(b)?"keyword":"variable"}var d=c;c.propertyKeywords||(c=a.resolveMode("text/css")),c.inline=d.inline;var s,t,e=b.indentUnit,f=c.tokenHooks,g=c.documentTypes||{},h=c.mediaTypes||{},i=c.mediaFeatures||{},j=c.mediaValueKeywords||{},k=c.propertyKeywords||{},l=c.nonStandardPropertyKeywords||{},m=c.fontProperties||{},n=c.counterDescriptors||{},o=c.colorKeywords||{},p=c.valueKeywords||{},q=c.allowNested,r=c.supportsAtComponent===!0,E={};return E.top=function(a,b,c){if("{"==a)return z(c,b,"block");if("}"==a&&c.context.prev)return A(c);if(r&&/@component/.test(a))return z(c,b,"atComponentBlock");if(/^@(-moz-)?document$/.test(a))return z(c,b,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(a))return z(c,b,"atBlock");if(/^@(font-face|counter-style)/.test(a))return c.stateArg=a,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(a))return"keyframes";if(a&&"@"==a.charAt(0))return z(c,b,"at");if("hash"==a)t="builtin";else if("word"==a)t="tag";else{if("variable-definition"==a)return"maybeprop";if("interpolation"==a)return z(c,b,"interpolation");if(":"==a)return"pseudo";if(q&&"("==a)return z(c,b,"parens")}return c.context.type},E.block=function(a,b,c){if("word"==a){var d=b.current().toLowerCase();return k.hasOwnProperty(d)?(t="property","maybeprop"):l.hasOwnProperty(d)?(t="string-2","maybeprop"):q?(t=b.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(t+=" error","maybeprop")}return"meta"==a?"block":q||"hash"!=a&&"qualifier"!=a?E.top(a,b,c):(t="error","block")},E.maybeprop=function(a,b,c){return":"==a?z(c,b,"prop"):B(a,b,c)},E.prop=function(a,b,c){if(";"==a)return A(c);if("{"==a&&q)return z(c,b,"propBlock");if("}"==a||"{"==a)return C(a,b,c);if("("==a)return z(c,b,"parens");if("hash"!=a||/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(b.current())){if("word"==a)D(b);else if("interpolation"==a)return z(c,b,"interpolation")}else t+=" error";return"prop"},E.propBlock=function(a,b,c){return"}"==a?A(c):"word"==a?(t="property","maybeprop"):c.context.type},E.parens=function(a,b,c){return"{"==a||"}"==a?C(a,b,c):")"==a?A(c):"("==a?z(c,b,"parens"):"interpolation"==a?z(c,b,"interpolation"):("word"==a&&D(b),"parens")},E.pseudo=function(a,b,c){return"word"==a?(t="variable-3",c.context.type):B(a,b,c)},E.documentTypes=function(a,b,c){return"word"==a&&g.hasOwnProperty(b.current())?(t="tag",c.context.type):E.atBlock(a,b,c)},E.atBlock=function(a,b,c){if("("==a)return z(c,b,"atBlock_parens");if("}"==a||";"==a)return C(a,b,c);if("{"==a)return A(c)&&z(c,b,q?"block":"top");if("interpolation"==a)return z(c,b,"interpolation");if("word"==a){var d=b.current().toLowerCase();t="only"==d||"not"==d||"and"==d||"or"==d?"keyword":h.hasOwnProperty(d)?"attribute":i.hasOwnProperty(d)?"property":j.hasOwnProperty(d)?"keyword":k.hasOwnProperty(d)?"property":l.hasOwnProperty(d)?"string-2":p.hasOwnProperty(d)?"atom":o.hasOwnProperty(d)?"keyword":"error"}return c.context.type},E.atComponentBlock=function(a,b,c){return"}"==a?C(a,b,c):"{"==a?A(c)&&z(c,b,q?"block":"top",!1):("word"==a&&(t="error"),c.context.type)},E.atBlock_parens=function(a,b,c){return")"==a?A(c):"{"==a||"}"==a?C(a,b,c,2):E.atBlock(a,b,c)},E.restricted_atBlock_before=function(a,b,c){return"{"==a?z(c,b,"restricted_atBlock"):"word"==a&&"@counter-style"==c.stateArg?(t="variable","restricted_atBlock_before"):B(a,b,c)},E.restricted_atBlock=function(a,b,c){return"}"==a?(c.stateArg=null,A(c)):"word"==a?(t="@font-face"==c.stateArg&&!m.hasOwnProperty(b.current().toLowerCase())||"@counter-style"==c.stateArg&&!n.hasOwnProperty(b.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},E.keyframes=function(a,b,c){return"word"==a?(t="variable","keyframes"):"{"==a?z(c,b,"top"):B(a,b,c)},E.at=function(a,b,c){return";"==a?A(c):"{"==a||"}"==a?C(a,b,c):("word"==a?t="tag":"hash"==a&&(t="builtin"),"at")},E.interpolation=function(a,b,c){return"}"==a?A(c):"{"==a||";"==a?C(a,b,c):("word"==a?t="variable":"variable"!=a&&"("!=a&&")"!=a&&(t="error"),"interpolation")},{startState:function(a){return{tokenize:null,state:c.inline?"block":"top", +stateArg:null,context:new y(c.inline?"block":"top",a||0,null)}},token:function(a,b){if(!b.tokenize&&a.eatSpace())return null;var c=(b.tokenize||v)(a,b);return c&&"object"==typeof c&&(s=c[1],c=c[0]),t=c,b.state=E[b.state](s,a,b),t},indent:function(a,b){var c=a.context,d=b&&b.charAt(0),f=c.indent;return"prop"!=c.type||"}"!=d&&")"!=d||(c=c.prev),c.prev&&("}"!=d||"block"!=c.type&&"top"!=c.type&&"interpolation"!=c.type&&"restricted_atBlock"!=c.type?(")"==d&&("parens"==c.type||"atBlock_parens"==c.type)||"{"==d&&("at"==c.type||"atBlock"==c.type))&&(f=Math.max(0,c.indent-e),c=c.prev):(c=c.prev,f=c.indent)),f},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",fold:"brace"}});var c=["domain","regexp","url","url-prefix"],d=b(c),e=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],f=b(e),g=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],h=b(g),i=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],j=b(i),k=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-position","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],l=b(k),m=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],n=b(m),o=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],p=b(o),q=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],r=b(q),s=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],t=b(s),u=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","column","column-reverse","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","dashed","decimal","decimal-leading-zero","default","default-button","destination-atop","destination-in","destination-out","destination-over","devanagari","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","scale","scale3d","scaleX","scaleY","scaleZ","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],v=b(u),w=c.concat(e).concat(g).concat(i).concat(k).concat(m).concat(s).concat(u);a.registerHelper("hintWords","css",w),a.defineMIME("text/css",{documentTypes:d,mediaTypes:f,mediaFeatures:h,mediaValueKeywords:j,propertyKeywords:l,nonStandardPropertyKeywords:n,fontProperties:p,counterDescriptors:r,colorKeywords:t,valueKeywords:v,tokenHooks:{"/":function(a,b){return a.eat("*")?(b.tokenize=x,x(a,b)):!1}},name:"css"}),a.defineMIME("text/x-scss",{mediaTypes:f,mediaFeatures:h,mediaValueKeywords:j,propertyKeywords:l,nonStandardPropertyKeywords:n,colorKeywords:t,valueKeywords:v,fontProperties:p,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=x,x(a,b)):["operator","operator"]},":":function(a){return a.match(/\s*\{/)?[null,"{"]:!1},$:function(a){return a.match(/^[\w-]+/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(a){return a.eat("{")?[null,"interpolation"]:!1}},name:"css",helperType:"scss"}),a.defineMIME("text/x-less",{mediaTypes:f,mediaFeatures:h,mediaValueKeywords:j,propertyKeywords:l,nonStandardPropertyKeywords:n,colorKeywords:t,valueKeywords:v,fontProperties:p,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=x,x(a,b)):["operator","operator"]},"@":function(a){return a.eat("{")?[null,"interpolation"]:a.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1)?!1:(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),a.defineMIME("text/x-gss",{documentTypes:d,mediaTypes:f,mediaFeatures:h,propertyKeywords:l,nonStandardPropertyKeywords:n,fontProperties:p,counterDescriptors:r,colorKeywords:t,valueKeywords:v,supportsAtComponent:!0,tokenHooks:{"/":function(a,b){return a.eat("*")?(b.tokenize=x,x(a,b)):!1}},name:"css",helperType:"gss"})}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../../mode/css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../../mode/css/css"],a):a(CodeMirror)}(function(a){"use strict";var b={link:1,visited:1,active:1,hover:1,focus:1,"first-letter":1,"first-line":1,"first-child":1,before:1,after:1,lang:1};a.registerHelper("hint","css",function(c){function l(a){for(var b in a)i&&0!=b.lastIndexOf(i,0)||k.push(b)}var d=c.getCursor(),e=c.getTokenAt(d),f=a.innerMode(c.getMode(),e.state);if("css"==f.mode.name){if("keyword"==e.type&&0=="!important".indexOf(e.string))return{list:["!important"],from:a.Pos(d.line,e.start),to:a.Pos(d.line,e.end)};var g=e.start,h=d.ch,i=e.string.slice(0,h-g);/[^\w$_-]/.test(i)&&(i="",g=h=d.ch);var j=a.resolveMode("text/css"),k=[],m=f.state.state;return"pseudo"==m||"variable-3"==e.type?l(b):"block"==m||"maybeprop"==m?l(j.propertyKeywords):"prop"==m||"parens"==m||"at"==m||"params"==m?(l(j.valueKeywords),l(j.colorKeywords)):("media"==m||"media_parens"==m)&&(l(j.mediaTypes),l(j.mediaFeatures)),k.length?{list:k,from:a.Pos(d.line,g),to:a.Pos(d.line,h)}:void 0}})}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("./searchcursor"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../dialog/dialog"],a):a(CodeMirror)}(function(a){"use strict";function b(a,b){return"string"==typeof a?a=new RegExp(a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),b?"gi":"g"):a.global||(a=new RegExp(a.source,a.ignoreCase?"gi":"g")),{token:function(b){a.lastIndex=b.pos;var c=a.exec(b.string);return c&&c.index==b.pos?(b.pos+=c[0].length,"searching"):void(c?b.pos=c.index:b.skipToEnd())}}}function c(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function d(a){return a.state.search||(a.state.search=new c)}function e(a){return"string"==typeof a&&a==a.toLowerCase()}function f(a,b,c){return a.getSearchCursor(b,c,e(b))}function g(a,b,c,d){a.openDialog(b,d,{value:c,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){p(a)}})}function h(a,b,c,d,e){a.openDialog?a.openDialog(b,e,{value:d,selectValueOnOpen:!0}):e(prompt(c,d))}function i(a,b,c,d){a.openConfirm?a.openConfirm(b,d):confirm(c)&&d[0]()}function j(a){return a.replace(/\\(.)/g,function(a,b){return"n"==b?"\n":"r"==b?"\r":b})}function k(a){var b=a.match(/^\/(.*)\/([a-z]*)$/);if(b)try{a=new RegExp(b[1],-1==b[2].indexOf("i")?"":"i")}catch(c){}else a=j(a);return("string"==typeof a?""==a:a.test(""))&&(a=/x^/),a}function m(a,c,d){c.queryText=d,c.query=k(d),a.removeOverlay(c.overlay,e(c.query)),c.overlay=b(c.query,e(c.query)),a.addOverlay(c.overlay),a.showMatchesOnScrollbar&&(c.annotate&&(c.annotate.clear(),c.annotate=null),c.annotate=a.showMatchesOnScrollbar(c.query,e(c.query)))}function n(b,c,e){var f=d(b);if(f.query)return o(b,c);var i=b.getSelection()||f.lastQuery;if(e&&b.openDialog){var j=null;g(b,l,i,function(c,d){a.e_stop(d),c&&(c!=f.queryText&&m(b,f,c),j&&(j.style.opacity=1),o(b,d.shiftKey,function(a,c){var d;c.line<3&&document.querySelector&&(d=b.display.wrapper.querySelector(".CodeMirror-dialog"))&&d.getBoundingClientRect().bottom-4>b.cursorCoords(c,"window").top&&((j=d).style.opacity=.4)}))})}else h(b,l,"Search for:",i,function(a){a&&!f.query&&b.operation(function(){m(b,f,a),f.posFrom=f.posTo=b.getCursor(),o(b,c)})})}function o(b,c,e){b.operation(function(){var g=d(b),h=f(b,g.query,c?g.posFrom:g.posTo);(h.find(c)||(h=f(b,g.query,c?a.Pos(b.lastLine()):a.Pos(b.firstLine(),0)),h.find(c)))&&(b.setSelection(h.from(),h.to()),b.scrollIntoView({from:h.from(),to:h.to()},20),g.posFrom=h.from(),g.posTo=h.to(),e&&e(h.from(),h.to()))})}function p(a){a.operation(function(){var b=d(a);b.lastQuery=b.query,b.query&&(b.query=b.queryText=null,a.removeOverlay(b.overlay),b.annotate&&(b.annotate.clear(),b.annotate=null))})}function t(a,b,c){a.operation(function(){for(var d=f(a,b);d.findNext();)if("string"!=typeof b){var e=a.getRange(d.from(),d.to()).match(b);d.replace(c.replace(/\$(\d)/g,function(a,b){return e[b]}))}else d.replace(c)})}function u(a,b){if(!a.getOption("readOnly")){var c=a.getSelection()||d(a).lastQuery,e=b?"Replace all:":"Replace:";h(a,e+q,e,c,function(c){c&&(c=k(c),h(a,r,"Replace with:","",function(d){if(d=j(d),b)t(a,c,d);else{p(a);var e=f(a,c,a.getCursor()),g=function(){var j,b=e.from();!(j=e.findNext())&&(e=f(a,c),!(j=e.findNext())||b&&e.from().line==b.line&&e.from().ch==b.ch)||(a.setSelection(e.from(),e.to()),a.scrollIntoView({from:e.from(),to:e.to()}),i(a,s,"Replace?",[function(){h(j)},g,function(){t(a,c,d)}]))},h=function(a){e.replace("string"==typeof c?d:d.replace(/\$(\d)/g,function(b,c){return a[c]})),g()};g()}}))})}}var l='Search: (Use /re/ syntax for regexp search)',q=' (Use /re/ syntax for regexp search)',r='With: ',s="Replace? ";a.commands.find=function(a){p(a),n(a)},a.commands.findPersistent=function(a){p(a),n(a,!1,!0)},a.commands.findNext=n,a.commands.findPrev=function(a){n(a,!0)},a.commands.clearSearch=p,a.commands.replace=u,a.commands.replaceAll=function(a){u(a,!0)}}),function(a){"object"==typeof exports&&"object"==typeof module?a(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/edit/matchbrackets")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/edit/matchbrackets"],a):a(CodeMirror)}(function(a){"use strict";function g(b,c,e){if(0>e&&0==c.ch)return b.clipPos(d(c.line-1));var f=b.getLine(c.line);if(e>0&&c.ch>=f.length)return b.clipPos(d(c.line+1,0));for(var h,g="start",i=c.ch,j=0>e?0:f.length,k=0;i!=j;i+=e,k++){var l=f.charAt(0>e?i-1:i),m="_"!=l&&a.isWordChar(l)?"w":"o";if("w"==m&&l.toUpperCase()==l&&(m="W"),"start"==g)"o"!=m&&(g="in",h=m);else if("in"==g&&h!=m){if("w"==h&&"W"==m&&0>e&&i--,"W"==h&&"w"==m&&e>0){h="w";continue}break}}return d(c.line,i)}function h(a,b){a.extendSelectionsBy(function(c){return a.display.shift||a.doc.extend||c.empty()?g(a.doc,c.head,b):0>b?c.from():c.to()})}function j(a,b){a.operation(function(){for(var c=a.listSelections().length,e=[],f=-1,g=0;c>g;g++){var h=a.listSelections()[g].head;if(!(h.line<=f)){var i=d(h.line+(b?0:1),0);a.replaceRange("\n",i,null,"+insertLine"),a.indentLine(i.line,null,!0),e.push({head:i,anchor:i}),f=h.line+1}}a.setSelections(e)})}function k(b,c){for(var e=c.ch,f=e,g=b.getLine(c.line);e&&a.isWordChar(g.charAt(e-1));)--e;for(;fa?-1:a==b?0:1}),a.replaceRange(l,j,k),f&&c.push({anchor:j,head:k})}f&&a.setSelections(c,0)})}function q(b,c){b.operation(function(){for(var d=b.listSelections(),e=[],f=[],g=0;g=0;g--){var h=d[e[g]];if(!(i&&a.cmpPos(h.head,i)>0)){var j=k(b,h.head);i=j.from,b.replaceRange(c(j.word),j.from,j.to)}}})}function r(b){var c=b.getCursor("from"),d=b.getCursor("to");if(0==a.cmpPos(c,d)){var e=k(b,c);if(!e.word)return;c=e.from,d=e.to}return{from:c,to:d,query:b.getRange(c,d),word:e}}function s(a,b){var c=r(a);if(c){var e=c.query,f=a.getSearchCursor(e,b?c.to:c.from);(b?f.findNext():f.findPrevious())?a.setSelection(f.from(),f.to()):(f=a.getSearchCursor(e,b?d(a.firstLine(),0):a.clipPos(d(a.lastLine()))),(b?f.findNext():f.findPrevious())?a.setSelection(f.from(),f.to()):c.word&&a.setSelection(c.from,c.to))}}var b=a.keyMap.sublime={fallthrough:"default"},c=a.commands,d=a.Pos,e=a.keyMap["default"]==a.keyMap.macDefault,f=e?"Cmd-":"Ctrl-";c[b["Alt-Left"]="goSubwordLeft"]=function(a){h(a,-1)},c[b["Alt-Right"]="goSubwordRight"]=function(a){h(a,1)};var i=e?"Ctrl-Alt-":"Ctrl-";c[b[i+"Up"]="scrollLineUp"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top+b.clientHeight,"local");a.getCursor().line>=c&&a.execCommand("goLineUp")}a.scrollTo(null,b.top-a.defaultTextHeight())},c[b[i+"Down"]="scrollLineDown"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top,"local")+1;a.getCursor().line<=c&&a.execCommand("goLineDown")}a.scrollTo(null,b.top+a.defaultTextHeight())},c[b["Shift-"+f+"L"]="splitSelectionByLine"]=function(a){for(var b=a.listSelections(),c=[],e=0;ef.line&&h==g.line&&0==g.ch||c.push({anchor:h==f.line?f:d(h,0),head:h==g.line?g:d(h)});a.setSelections(c,0)},b["Shift-Tab"]="indentLess",c[b.Esc="singleSelectionTop"]=function(a){var b=a.listSelections()[0];a.setSelection(b.anchor,b.head,{scroll:!1})},c[b[f+"L"]="selectLine"]=function(a){for(var b=a.listSelections(),c=[],e=0;ee?c.push(i,j):c.length&&(c[c.length-1]=j),e=j}a.operation(function(){for(var b=0;ba.lastLine()?a.replaceRange("\n"+h,d(a.lastLine()),null,"+swapLine"):a.replaceRange(h+"\n",d(g,0),null,"+swapLine")}a.setSelections(f),a.scrollIntoView()})},c[b[n+"Down"]="swapLineDown"]=function(a){for(var b=a.listSelections(),c=[],e=a.lastLine()+1,f=b.length-1;f>=0;f--){var g=b[f],h=g.to().line+1,i=g.from().line;0!=g.to().ch||g.empty()||h--,e>h?c.push(h,i):c.length&&(c[c.length-1]=i),e=i}a.operation(function(){for(var b=c.length-2;b>=0;b-=2){var e=c[b],f=c[b+1],g=a.getLine(e);e==a.lastLine()?a.replaceRange("",d(e-1),d(e),"+swapLine"):a.replaceRange("",d(e,0),d(e+1,0),"+swapLine"),a.replaceRange(g+"\n",d(f,0),null,"+swapLine")}a.scrollIntoView()})},b[f+"/"]=function(a){a.toggleComment({indent:!0})},c[b[f+"J"]="joinLines"]=function(a){for(var b=a.listSelections(),c=[],e=0;ec;c++){var e=a.listSelections()[c];e.empty()?a.replaceRange(a.getLine(e.head.line)+"\n",d(e.head.line,0)):a.replaceRange(a.getRange(e.from(),e.to()),e.from())}a.scrollIntoView()})},b[f+"T"]="transposeChars",c[b.F9="sortLines"]=function(a){o(a,!0)},c[b[f+"F9"]="sortLinesInsensitive"]=function(a){o(a,!1)},c[b.F2="nextBookmark"]=function(a){var b=a.state.sublimeBookmarks;if(b)for(;b.length;){var c=b.shift(),d=c.find();if(d)return b.push(c),a.setSelection(d.from,d.to)}},c[b["Shift-F2"]="prevBookmark"]=function(a){var b=a.state.sublimeBookmarks;if(b)for(;b.length;){b.unshift(b.pop());var c=b[b.length-1].find();if(c)return a.setSelection(c.from,c.to);b.pop()}},c[b[f+"F2"]="toggleBookmark"]=function(a){for(var b=a.listSelections(),c=a.state.sublimeBookmarks||(a.state.sublimeBookmarks=[]),d=0;d=0;c--)a.replaceRange("",b[c].anchor,d(b[c].to().line),"+delete");a.scrollIntoView()})},c[b[p+f+"U"]="upcaseAtCursor"]=function(a){q(a,function(a){return a.toUpperCase()})},c[b[p+f+"L"]="downcaseAtCursor"]=function(a){q(a,function(a){return a.toLowerCase()})},c[b[p+f+"Space"]="setSublimeMark"]=function(a){a.state.sublimeMark&&a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor())},c[b[p+f+"A"]="selectToSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&a.setSelection(a.getCursor(),b)},c[b[p+f+"W"]="deleteToSublimeMark"]=function(b){var c=b.state.sublimeMark&&b.state.sublimeMark.find();if(c){var d=b.getCursor(),e=c;if(a.cmpPos(d,e)>0){var f=e;e=d,d=f}b.state.sublimeKilled=b.getRange(d,e),b.replaceRange("",d,e)}},c[b[p+f+"X"]="swapWithSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&(a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor()),a.setCursor(b))},c[b[p+f+"Y"]="sublimeYank"]=function(a){null!=a.state.sublimeKilled&&a.replaceSelection(a.state.sublimeKilled,null,"paste")},b[p+f+"G"]="clearBookmarks",c[b[p+f+"C"]="showInCenter"]=function(a){var b=a.cursorCoords(null,"local");a.scrollTo(null,(b.top+b.bottom)/2-a.getScrollInfo().clientHeight/2)},c[b["Shift-Alt-Up"]="selectLinesUpward"]=function(a){a.operation(function(){for(var b=a.listSelections(),c=0;ca.firstLine()&&a.addSelection(d(e.head.line-1,e.head.ch))}})},c[b["Shift-Alt-Down"]="selectLinesDownward"]=function(a){a.operation(function(){for(var b=a.listSelections(),c=0;c (Use /re/ syntax for regexp search)'; + + function startSearch(cm, state, query) { + state.queryText = query; + state.query = parseQuery(query); + cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); + state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); + cm.addOverlay(state.overlay); + if (cm.showMatchesOnScrollbar) { + if (state.annotate) { state.annotate.clear(); state.annotate = null; } + state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); + } + } + + function doSearch(cm, rev, persistent) { + var state = getSearchState(cm); + if (state.query) return findNext(cm, rev); + var q = cm.getSelection() || state.lastQuery; + if (persistent && cm.openDialog) { + var hiding = null + persistentDialog(cm, queryDialog, q, function(query, event) { + CodeMirror.e_stop(event); + if (!query) return; + if (query != state.queryText) startSearch(cm, state, query); + if (hiding) hiding.style.opacity = 1 + findNext(cm, event.shiftKey, function(_, to) { + var dialog + if (to.line < 3 && document.querySelector && + (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && + dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) + (hiding = dialog).style.opacity = .4 + }) + }); + } else { + dialog(cm, queryDialog, "Search for:", q, function(query) { + if (query && !state.query) cm.operation(function() { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + findNext(cm, rev); + }); + }); + } + } + + function findNext(cm, rev, callback) {cm.operation(function() { + var state = getSearchState(cm); + var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); + if (!cursor.find(rev)) { + cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20); + state.posFrom = cursor.from(); state.posTo = cursor.to(); + if (callback) callback(cursor.from(), cursor.to()) + });} + + function clearSearch(cm) {cm.operation(function() { + var state = getSearchState(cm); + state.lastQuery = state.query; + if (!state.query) return; + state.query = state.queryText = null; + cm.removeOverlay(state.overlay); + if (state.annotate) { state.annotate.clear(); state.annotate = null; } + });} + + var replaceQueryDialog = + ' (Use /re/ syntax for regexp search)'; + var replacementQueryDialog = 'With: '; + var doReplaceConfirm = "Replace? "; + + function replaceAll(cm, query, text) { + cm.operation(function() { + for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { + if (typeof query != "string") { + var match = cm.getRange(cursor.from(), cursor.to()).match(query); + cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];})); + } else cursor.replace(text); + } + }); + } + + function replace(cm, all) { + if (cm.getOption("readOnly")) return; + var query = cm.getSelection() || getSearchState(cm).lastQuery; + var dialogText = all ? "Replace all:" : "Replace:" + dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) { + if (!query) return; + query = parseQuery(query); + dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) { + text = parseString(text) + if (all) { + replaceAll(cm, query, text) + } else { + clearSearch(cm); + var cursor = getSearchCursor(cm, query, cm.getCursor()); + var advance = function() { + var start = cursor.from(), match; + if (!(match = cursor.findNext())) { + cursor = getSearchCursor(cm, query); + if (!(match = cursor.findNext()) || + (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); + confirmDialog(cm, doReplaceConfirm, "Replace?", + [function() {doReplace(match);}, advance, + function() {replaceAll(cm, query, text)}]); + }; + var doReplace = function(match) { + cursor.replace(typeof query == "string" ? text : + text.replace(/\$(\d)/g, function(_, i) {return match[i];})); + advance(); + }; + advance(); + } + }); + }); + } + + CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);}; + CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);}; + CodeMirror.commands.findNext = doSearch; + CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);}; + CodeMirror.commands.clearSearch = clearSearch; + CodeMirror.commands.replace = replace; + CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);}; +}); diff --git a/nano/js/libraries/codemirror/keymap/sublime.js b/nano/js/libraries/codemirror/keymap/sublime.js new file mode 100644 index 00000000000..a0ca41ea2a2 --- /dev/null +++ b/nano/js/libraries/codemirror/keymap/sublime.js @@ -0,0 +1,565 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// A rough approximation of Sublime Text's keybindings +// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets")); + else if (typeof define == "function" && define.amd) // AMD + define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var map = CodeMirror.keyMap.sublime = {fallthrough: "default"}; + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault; + var ctrl = mac ? "Cmd-" : "Ctrl-"; + + // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); + var line = doc.getLine(start.line); + if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); + var state = "start", type; + for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { + var next = line.charAt(dir < 0 ? pos - 1 : pos); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { state = "in"; type = cat; } + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; } + break; + } + } + } + return Pos(start.line, pos); + } + + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosSubword(cm.doc, range.head, dir); + else + return dir < 0 ? range.from() : range.to(); + }); + } + + cmds[map["Alt-Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); }; + cmds[map["Alt-Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); }; + + var scrollLineCombo = mac ? "Ctrl-Alt-" : "Ctrl-"; + + cmds[map[scrollLineCombo + "Up"] = "scrollLineUp"] = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) + cm.execCommand("goLineUp"); + } + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds[map[scrollLineCombo + "Down"] = "scrollLineDown"] = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local")+1; + if (cm.getCursor().line <= visibleTopLine) + cm.execCommand("goLineDown"); + } + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + + cmds[map["Shift-" + ctrl + "L"] = "splitSelectionByLine"] = function(cm) { + var ranges = cm.listSelections(), lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) + if (!(to.line > from.line && line == to.line && to.ch == 0)) + lineRanges.push({anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line)}); + } + cm.setSelections(lineRanges, 0); + }; + + map["Shift-Tab"] = "indentLess"; + + cmds[map["Esc"] = "singleSelectionTop"] = function(cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, {scroll: false}); + }; + + cmds[map[ctrl + "L"] = "selectLine"] = function(cm) { + var ranges = cm.listSelections(), extended = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + extended.push({anchor: Pos(range.from().line, 0), + head: Pos(range.to().line + 1, 0)}); + } + cm.setSelections(extended); + }; + + map["Shift-" + ctrl + "K"] = "deleteLine"; + + function insertLine(cm, above) { + cm.operation(function() { + var len = cm.listSelections().length, newSelection = [], last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({head: at, anchor: at}); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + } + + cmds[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { insertLine(cm, false); }; + + cmds[map["Shift-" + ctrl + "Enter"] = "insertLineBefore"] = function(cm) { insertLine(cm, true); }; + + function wordAt(cm, pos) { + var start = pos.ch, end = start, line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; + return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)}; + } + + cmds[map[ctrl + "D"] = "selectNextOccurrence"] = function(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + if (cur.findNext()) { + cm.addSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + if (cur.findNext()) + cm.addSelection(cur.from(), cur.to()); + } + } + if (fullWord) + cm.state.sublimeFindFullWord = cm.doc.sel; + }; + + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var pos = cm.getCursor(), opening = cm.scanForBracket(pos, -1); + if (!opening) return; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return; + if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { + cm.setSelection(Pos(opening.pos.line, opening.pos.ch + 1), closing.pos, false); + return true; + } + pos = Pos(closing.pos.line, closing.pos.ch + 1); + } + } + + cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + + cmds[map[ctrl + "M"] = "goToBracket"] = function(cm) { + cm.extendSelectionsBy(function(range) { + var next = cm.scanForBracket(range.head, 1); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + + var swapLineCombo = mac ? "Cmd-Ctrl-" : "Shift-Ctrl-"; + + cmds[map[swapLineCombo + "Up"] = "swapLineUp"] = function(cm) { + var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from().line - 1, to = range.to().line; + newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch), + head: Pos(range.head.line - 1, range.head.ch)}); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to); + else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function() { + for (var i = 0; i < linesToMove.length; i += 2) { + var from = linesToMove[i], to = linesToMove[i + 1]; + var line = cm.getLine(from); + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + if (to > cm.lastLine()) + cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine"); + else + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + + cmds[map[swapLineCombo + "Down"] = "swapLineDown"] = function(cm) { + var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], from = range.to().line + 1, to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to); + else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function() { + for (var i = linesToMove.length - 2; i >= 0; i -= 2) { + var from = linesToMove[i], to = linesToMove[i + 1]; + var line = cm.getLine(from); + if (from == cm.lastLine()) + cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine"); + else + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + + map[ctrl + "/"] = function(cm) { + cm.toggleComment({ indent: true }); + } + + cmds[map[ctrl + "J"] = "joinLines"] = function(cm) { + var ranges = cm.listSelections(), joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from(); + var start = from.line, end = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == end) + end = ranges[++i].to().line; + joined.push({start: start, end: end, anchor: !range.empty() && from}); + } + cm.operation(function() { + var offset = 0, ranges = []; + for (var i = 0; i < joined.length; i++) { + var obj = joined[i]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); + if (actual < cm.lastLine()) { + cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); + ++offset; + } + } + ranges.push({anchor: anchor || head, head: head}); + } + cm.setSelections(ranges, 0); + }); + }; + + cmds[map["Shift-" + ctrl + "D"] = "duplicateLine"] = function(cm) { + cm.operation(function() { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) + cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0)); + else + cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + + map[ctrl + "T"] = "transposeChars"; + + function sortLines(cm, caseSensitive) { + var ranges = cm.listSelections(), toSort = [], selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) + to = range[++i].to().line; + toSort.push(from, to); + } + if (toSort.length) selected = true; + else toSort.push(cm.firstLine(), cm.lastLine()); + + cm.operation(function() { + var ranges = []; + for (var i = 0; i < toSort.length; i += 2) { + var from = toSort[i], to = toSort[i + 1]; + var start = Pos(from, 0), end = Pos(to); + var lines = cm.getRange(start, end, false); + if (caseSensitive) + lines.sort(); + else + lines.sort(function(a, b) { + var au = a.toUpperCase(), bu = b.toUpperCase(); + if (au != bu) { a = au; b = bu; } + return a < b ? -1 : a == b ? 0 : 1; + }); + cm.replaceRange(lines, start, end); + if (selected) ranges.push({anchor: start, head: end}); + } + if (selected) cm.setSelections(ranges, 0); + }); + } + + cmds[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); }; + cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); }; + + cmds[map["F2"] = "nextBookmark"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + + cmds[map["Shift-F2"] = "prevBookmark"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) + marks.pop(); + else + return cm.setSelection(found.from, found.to); + } + }; + + cmds[map[ctrl + "F2"] = "toggleBookmark"] = function(cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + var found = cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) + if (marks[k] == found[j]) + marks.splice(k--, 1); + break; + } + } + if (j == found.length) + marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false})); + } + }; + + cmds[map["Shift-" + ctrl + "F2"] = "clearBookmarks"] = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); + marks.length = 0; + }; + + cmds[map["Alt-F2"] = "selectBookmarks"] = function(cm) { + var marks = cm.state.sublimeBookmarks, ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) + marks.splice(i--, 0); + else + ranges.push({anchor: found.from, head: found.to}); + } + if (ranges.length) + cm.setSelections(ranges, 0); + }; + + map["Alt-Q"] = "wrapLines"; + + var cK = ctrl + "K "; + + function modifyWordOrSelection(cm, mod) { + cm.operation(function() { + var ranges = cm.listSelections(), indices = [], replacements = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) { indices.push(i); replacements.push(""); } + else replacements.push(mod(cm.getRange(range.from(), range.to()))); + } + cm.replaceSelections(replacements, "around", "case"); + for (var i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + + map[cK + ctrl + "Backspace"] = "delLineLeft"; + + cmds[map["Backspace"] = "smartBackspace"] = function(cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + + var cursor = cm.getCursor(); + var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + var indentUnit = cm.getOption("indentUnit"); + + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, + CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + + // If no smart delete is happening (due to tab sizing) just do a regular delete + if (prevIndent.ch == cursor.ch) return CodeMirror.Pass; + + return cm.replaceRange("", prevIndent, cursor, "+delete"); + } else { + return CodeMirror.Pass; + } + }; + + cmds[map[cK + ctrl + "K"] = "delLineRight"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + + cmds[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); + }; + cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); + }; + + cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds[map[cK + ctrl + "W"] = "deleteToSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + var from = cm.getCursor(), to = found; + if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; } + cm.state.sublimeKilled = cm.getRange(from, to); + cm.replaceRange("", from, to); + } + }; + cmds[map[cK + ctrl + "X"] = "swapWithSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + cm.setCursor(found); + } + }; + cmds[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + + map[cK + ctrl + "G"] = "clearBookmarks"; + cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + + cmds[map["Shift-Alt-Up"] = "selectLinesUpward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line > cm.firstLine()) + cm.addSelection(Pos(range.head.line - 1, range.head.ch)); + } + }); + }; + cmds[map["Shift-Alt-Down"] = "selectLinesDownward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line < cm.lastLine()) + cm.addSelection(Pos(range.head.line + 1, range.head.ch)); + } + }); + }; + + function getTarget(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + from = word.from; + to = word.to; + } + return {from: from, to: to, query: cm.getRange(from, to), word: word}; + } + + function findAndGoTo(cm, forward) { + var target = getTarget(cm); + if (!target) return; + var query = target.query; + var cur = cm.getSearchCursor(query, forward ? target.to : target.from); + + if (forward ? cur.findNext() : cur.findPrevious()) { + cm.setSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) + : cm.clipPos(Pos(cm.lastLine()))); + if (forward ? cur.findNext() : cur.findPrevious()) + cm.setSelection(cur.from(), cur.to()); + else if (target.word) + cm.setSelection(target.from, target.to); + } + }; + cmds[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); }; + cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); }; + cmds[map["Alt-F3"] = "findAllUnder"] = function(cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({anchor: cur.from(), head: cur.to()}); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) + primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + + map["Shift-" + ctrl + "["] = "fold"; + map["Shift-" + ctrl + "]"] = "unfold"; + map[cK + ctrl + "0"] = map[cK + ctrl + "j"] = "unfoldAll"; + + map[ctrl + "I"] = "findIncremental"; + map["Shift-" + ctrl + "I"] = "findIncrementalReverse"; + map[ctrl + "H"] = "replace"; + map["F3"] = "findNext"; + map["Shift-F3"] = "findPrev"; + + CodeMirror.normalizeKeyMap(map); +}); diff --git a/nano/js/libraries/codemirror/lib/codemirror.css b/nano/js/libraries/codemirror/lib/codemirror.css new file mode 100644 index 00000000000..3543523e645 --- /dev/null +++ b/nano/js/libraries/codemirror/lib/codemirror.css @@ -0,0 +1,334 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actuall scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + margin-bottom: -30px; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget {} + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { position: absolute; } +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/nano/js/libraries/codemirror/lib/codemirror.js b/nano/js/libraries/codemirror/lib/codemirror.js new file mode 100644 index 00000000000..e08dedea4e8 --- /dev/null +++ b/nano/js/libraries/codemirror/lib/codemirror.js @@ -0,0 +1,8856 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + module.exports = mod(); + else if (typeof define == "function" && define.amd) // AMD + return define([], mod); + else // Plain browser env + this.CodeMirror = mod(); +})(function() { + "use strict"; + + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + var userAgent = navigator.userAgent; + var platform = navigator.platform; + + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + + var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var windows = /win/i.test(platform); + + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror(place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) + this.display.wrapper.className += " CodeMirror-wrap"; + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; + + var cm = this; + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || cm.hasFocus()) + setTimeout(bind(onFocus, this), 20); + else + onBlur(this); + + for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) + optionHandlers[opt](this, options[opt], Init); + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + display.lineDiv.style.textRendering = "auto"; + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display(place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState(cm) { + cm.doc.iter(function(line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function(){updateScrollbars(cm);}, 100); + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function(line) { + if (lineIsHidden(cm.doc, line)) return 0; + + var widgetsHeight = 0; + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + + if (wrapping) + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + else + return widgetsHeight + th; + }; + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function(line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + function guttersChanged(cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function(){alignHorizontally(cm);}, 20); + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } + + function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; + } + + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength(line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; + } + + // Find the longest line in the document. + function findMaxLine(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function(line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; + } + + function NativeScrollbars(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); + + on(vert, "scroll", function() { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function() { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); + + this.checkedOverlay = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + + NativeScrollbars.prototype = copyObj({ + update: function(measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + + if (!this.checkedOverlay && measure.clientHeight > 0) { + if (sWidth == 0) this.overlayHack(); + this.checkedOverlay = true; + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function(pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + }, + setScrollTop: function(pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + }, + overlayHack: function() { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.minHeight = this.vert.style.minWidth = w; + var self = this; + var barMouseDown = function(e) { + if (e_target(e) != self.vert && e_target(e) != self.horiz) + operation(self.cm, onMouseDown)(e); + }; + on(this.vert, "mousedown", barMouseDown); + on(this.horiz, "mousedown", barMouseDown); + }, + clear: function() { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + } + }, NativeScrollbars.prototype); + + function NullScrollbars() {} + + NullScrollbars.prototype = copyObj({ + update: function() { return {bottom: 0, right: 0}; }, + setScrollLeft: function() {}, + setScrollTop: function() {}, + clear: function() {} + }, NullScrollbars.prototype); + + CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; + + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function() { + if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); + }); + node.setAttribute("cm-not-content", "true"); + }, function(pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + function updateScrollbars(cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + updateHeightsInViewport(cm); + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; + } + + // LINE NUMBERS + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) + view[i].gutter.style.left = left; + var align = view[i].alignable; + if (align) for (var j = 0; j < align.length; j++) + align[j].style.left = left; + } + if (cm.options.fixedGutter) + display.gutters.style.left = (comp + gutterW) + "px"; + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; + } + return false; + } + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } + + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + + // DISPLAY DRAWING + + function DisplayUpdate(cm, viewport, force) { + var display = cm.display; + + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + } + + DisplayUpdate.prototype.signal = function(emitter, type) { + if (hasHandler(emitter, type)) + this.events.push(arguments); + }; + DisplayUpdate.prototype.finish = function() { + for (var i = 0; i < this.events.length; i++) + signal.apply(null, this.events[i]); + }; + + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + return false; + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + return false; + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + + display.updateLineNumbers = null; + + return true; + } + + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + break; + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + update.finish(); + } + } + + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + var total = measure.docHeight + cm.display.barHeight; + cm.display.heightForcer.style.top = total + "px"; + cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) for (var j = 0; j < cur.rest.length; j++) + updateWidgetHeight(cur.rest[j]); + } + } + } + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) + line.widgets[i].height = line.widgets[i].node.offsetHeight; + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + node.style.display = "none"; + else + node.parentNode.removeChild(node); + return next; + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; + } + + function updateLineBackground(lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses(lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + else if (lineView.node != lineView.text) + lineView.node.className = ""; + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) + gutterWrap.className += " " + lineView.line.gutterClass; + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") + lineView.node.removeChild(node); + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; + + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); + } + + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) + wrap.insertBefore(node, lineView.gutter || lineView.text); + else + wrap.appendChild(node); + signalLater(widget, "redraw"); + } + } + + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // POSITION OBJECT + + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; + + function copyPos(x) {return Pos(x.line, x.ch);} + function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } + + // INPUT HANDLING + + function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } + } + + function isReadOnly(cm) { + return cm.options.readOnly || cm.doc.cantEdit; + } + + // This will be set to an array of strings when copying, so that, + // when pasting, we know what kind of selections the copied text + // was made out of. + var lastCopied = null; + + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; + + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = doc.splitLines(inserted), multiPaste = null; + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.length == 0) { + multiPaste = []; + for (var i = 0; i < lastCopied.length; i++) + multiPaste.push(doc.splitLines(lastCopied[i])); + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function(l) { return [l]; }); + } + } + + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + from = Pos(from.line, from.ch - deleted); + else if (cm.state.overwrite && !paste) // Handle overwrite + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + triggerElectric(cm, inserted); + + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; + } + + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + if (!isReadOnly(cm) && !cm.options.disableInput) + runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } + } + + function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + indented = indentLine(cm, range.head.line, "smart"); + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line); + } + } + + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges}; + } + + function disableBrowserMagic(field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } + + // TEXTAREA INPUT STYLE + + function TextareaInput(cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + }; + + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function() { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); + + on(te, "paste", function(e) { + if (handlePaste(e, cm)) return true; + + cm.state.pasteIncoming = true; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") cm.state.cutIncoming = true; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function(e) { + if (eventInWidget(display, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function(e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); + + on(te, "compositionstart", function() { + var start = cm.getCursor("from"); + if (input.composing) input.composing.range.clear() + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function() { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, + + prepareSelection: function() { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result; + }, + + showSelection: function(drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function(typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, + + getField: function() { return this.textarea; }, + + supportsTouch: function() { return false; }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function() { this.textarea.blur(); }, + + resetPosition: function() { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + + receivedFocus: function() { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function() { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function() { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function() { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} + else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function() { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) + return false; + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + + var self = this; + runInOp(cm, function() { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true; + }, + + ensurePolled: function() { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, + + onKeyPress: function() { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, + + onContextMenu: function(e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + + var oldCSS = te.style.cssText; + input.wrapper.style.position = "absolute"; + te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + input.contextMenuPending = false; + input.wrapper.style.position = "relative"; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function() { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") + operation(cm, commands.selectAll)(cm); + else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, + + readOnlyChanged: function(val) { + if (!val) this.reset(); + }, + + setUneditable: nothing, + + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE + + function ContentEditableInput(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + disableBrowserMagic(div); + + on(div, "paste", function(e) { handlePaste(e, cm); }) + + on(div, "compositionstart", function(e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + }); + on(div, "compositionupdate", function(e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function(e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) + ours.data = e.data; + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function() { + if (!ours.handled) + input.applyComposition(ours); + if (input.composing == ours) + input.composing = null; + }, 50); + }); + + on(div, "touchstart", function() { + input.forceCompositionEnd(); + }); + + on(div, "input", function() { + if (input.composing) return; + if (isReadOnly(cm) || !input.pollContent()) + runInOp(input.cm, function() {regChange(cm);}); + }); + + function onCopyCut(e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.operation(function() { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function() { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, + + prepareSelection: function() { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; + }, + + showSelection: function(info) { + if (!info || !this.cm.display.view.length) return; + if (info.focus) this.showPrimarySelection(); + this.showMultipleSelections(info); + }, + + showPrimarySelection: function() { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) + return; + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + sel.removeAllRanges(); + sel.addRange(rng); + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); + }, + + startGracePeriod: function() { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function() { + input.gracePeriod = false; + if (input.selectionChanged()) + input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); + }, 20); + }, + + showMultipleSelections: function(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }, + + rememberSelection: function() { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function() { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function() { this.div.blur(); }, + getField: function() { return this.div; }, + + supportsTouch: function() { return true; }, + + receivedFocus: function() { + var input = this; + if (this.selectionInEditor()) + this.pollSelection(); + else + runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }, + + selectionChanged: function() { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, + + pollSelection: function() { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) runInOp(cm, function() { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); + } + }, + + pollContent: function() { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; + + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } + + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } + else break; + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + ++cutFront; + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + ++cutEnd; + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function() { + this.forceCompositionEnd(); + }, + reset: function() { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function() { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function(composing) { + if (isReadOnly(this.cm)) + operation(this.cm, regChange)(this.cm) + else if (composing.data && composing.data != composing.startData) + operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); + }, + + setUneditable: function(node) { + node.contentEditable = "false" + }, + + onKeyPress: function(e) { + e.preventDefault(); + if (!isReadOnly(this.cm)) + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + readOnlyChanged: function(val) { + this.div.contentEditable = String(val != "nocursor") + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + + function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) + return locateNodeInLineView(lineView, node, offset); + } + } + + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) + return badPos(Pos(found.line, found.ch - dist), bad); + else + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) + return badPos(Pos(found.line, found.ch + dist), bad); + else + dist += after.textContent.length; + } + } + + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(); + function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) + text += getBetween(cm.doc, range.from, range.to).join(lineSep); + return; + } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) + walk(node.childNodes[i]); + if (/^(pre|div|p)$/i.test(node.nodeName)) + closing = true; + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += lineSep; + closing = false; + } + text += val; + } + } + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function() { return this.ranges[this.primIndex]; }, + equals: function(other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; + } + return true; + }, + deepCopy: function() { + for (var out = [], i = 0; i < this.ranges.length; i++) + out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); + return new Selection(out, this.primIndex); + }, + somethingSelected: function() { + for (var i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].empty()) return true; + return false; + }, + contains: function(pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + return i; + } + return -1; + } + }; + + function Range(anchor, head) { + this.anchor = anchor; this.head = head; + } + + Range.prototype = { + from: function() { return minPos(this.anchor, this.head); }, + to: function() { return maxPos(this.anchor, this.head); }, + empty: function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + } + }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos(doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + else return pos; + } + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray(doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } + + // SELECTION UPDATES + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } + } + + // Extend the primary selection range, discard the rest. + function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections(doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) + out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange(doc, sel) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); + } + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + else return sel; + } + + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + sel = filterSelectionChange(doc, sel); + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) + ensureCursorVisible(doc.cm); + } + + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic(doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find(dir < 0 ? -1 : 1); + if (cmp(newPos, curPos) == 0) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + } + return curPos; + } + } + + // SELECTION DRAWING + + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection(cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) + drawSelectionCursor(cm, range.head, curFragment); + if (!collapsed) + drawSelectionRange(cm, range, selFragment); + } + return result; + } + + // Draws a cursor for the given range + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + // Draws the given range as a highlighted selection + function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + + function add(left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + start = leftPos; + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + end = rightPos; + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) + display.blinker = setInterval(function() { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + else if (cm.options.cursorBlinkRate < 0) + display.cursorDiv.style.visibility = "hidden"; + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = tooLong ? state : copyState(doc.mode, state); + } else { + if (line.text.length <= cm.options.maxHighlightLength) + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) runInOp(cm, function() { + for (var i = 0; i < changedLines.length; i++) + regLineChange(cm, changedLines[i], "text"); + }); + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function(line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop;} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH(display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } + + function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) + heights.push((cur.bottom + next.top) / 2 - rect.top); + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + return {map: lineView.measure.map, cache: lineView.measure.cache}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineView.rest[i] == line) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineNo(lineView.rest[i]) > lineN) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + return cm.display.view[findViewIndex(cm, lineN)]; + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + return ext; + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) + view = updateExternalMeasurement(cm, line); + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) + prepared.rect = prepared.view.text.getBoundingClientRect(); + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + collapse = bias; + if (bias == "left" && start == 0) + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + if (bias == "right" && start == mEnd - mStart) + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = nullRect; + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = node.getBoundingClientRect(); + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) + rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; + else + rect = nullRect; + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) + if (mid < heights[i]) break; + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + return rect; + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + lineView.measure.caches[i] = {}; + } + } + + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) + clearLineMeasurementCacheFor(cm.display.view[i]); + } + + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem(cm, lineObj, rect, context) { + if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem(cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords(cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo(line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + lineN = lineNo(lineObj = mergedPos.to.line); + else + return found; + } + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + else wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight(display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth(display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) + callbacks[i].call(null); + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation(cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } + finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) + group.ops[i].cm.curOp = null; + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations(group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R1(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W1(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R2(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W2(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_finish(ops[i]); + } + + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) + op.preparedSelection = display.input.prepareSelection(); + } + + function endOperation_W2(op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); + cm.display.maxLineChanged = false; + } + + if (op.preparedSelection) + cm.display.input.showSelection(op.preparedSelection); + if (op.updatedDisplay) + setDocumentHeight(cm, op.barMeasure); + if (op.updatedDisplay || op.startHeight != cm.doc.height) + updateScrollbars(cm, op.barMeasure); + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) + cm.display.input.reset(op.typing); + if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); + } + + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + display.wheelStartX = display.wheelStartY = null; + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) for (var i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide"); + if (unhidden) for (var i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); + + if (display.wrapper.offsetHeight) + doc.scrollTop = cm.display.scroller.scrollTop; + + // Fire change events, and delayed event handlers + if (op.changeObjs) + signal(cm, "changes", cm, op.changeObjs); + if (op.update) + op.update.finish(); + } + + // Run the given function in an operation + function runInOp(cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } + finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm, f) { + return function() { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } + finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp(f) { + return function() { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } + finally { endOperation(this); } + }; + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } + finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView(doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange(cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + display.updateLineNumbers = from; + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + resetView(cm); + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) + ext.lineN += lendiff; + else if (from < ext.lineN + ext.size) + display.externalMeasured = null; + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + display.externalMeasured = null; + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + return {index: index, lineN: newN}; + for (var i = 0, n = cm.display.viewFrom; i < index; i++) + n += view[i].size; + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + else if (display.viewFrom < from) + display.view = display.view.slice(findViewIndex(cm, from)); + display.viewFrom = from; + if (display.viewTo < to) + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + else if (display.viewTo > to) + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + on(d.scroller, "dblclick", operation(cm, function(e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + else + on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + }; + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function(e) { + if (!isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function() { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function(e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + range = new Range(pos, pos); + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + range = cm.findWordAt(pos); + else // Triple tap + range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function() { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, + start: function(e){onDragStart(cm, e);}, + drop: operation(cm, onDrop), + leave: function() {clearDragCursor(cm);} + }; + + var inp = d.input.getField(); + on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged(cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize(cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + return; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + return true; + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } + catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown(e) { + var cm = this, display = cm.display; + if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function(){display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + cm.state.selectingText(e); + else if (start) + leftButtonDown(cm, e, start); + else if (e_target(e) == display.scroller) + e_preventDefault(e); + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function() {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown(cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + leftButtonStartDrag(cm, e, start, modifier); + else + leftButtonSelect(cm, e, start, type, modifier); + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function(e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) + extendSelection(cm.doc, start); + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + setTimeout(function() {document.body.focus(); display.input.focus();}, 20); + else + display.input.focus(); + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) + ourRange = ranges[ourIndex]; + else + ourRange = new Range(start, start); + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, word.anchor, word.head); + else + ourRange = word; + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, line.anchor, line.head); + else + ourRange = line; + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) + ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + else if (text.length > leftPos) + ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") + var range = cm.findWordAt(pos); + else + var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) setTimeout(operation(cm, function() { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function(e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent(cm, e, type, prevent, signalfn) { + try { var mX = e.clientX, mY = e.clientY; } + catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalfn(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true, signalLater); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + return; + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function(file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + return; + + var reader = new FileReader; + reader.onload = operation(cm, function() { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = ""; + text[i] = content; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function() {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) + var selected = cm.listSelections(); + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) for (var i = 0; i < selected.length; ++i) + replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } + catch(e){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) return; + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1/3; + + var wheelEventDelta = function(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function() { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function() { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") + cm.state.keySeq = name; + if (result == "handled") + signalLater(cm, "keyHandled", cm, name, e); + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function(b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + return doHandleBinding(cm, b); + }); + } else { + return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); + } + } + + // Handle a key from the keypress event + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function(b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + cm.replaceSelection("", null, "cut"); + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + showCrossHair(cm); + } + + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp(e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress(e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function() { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus(cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + if (signalDOMEvent(cm, e, "contextmenu")) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false, signal); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function(change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange(doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos(pos, old, nw) { + if (pos.line == old.line) + return Pos(nw.line, pos.ch - old.ch + nw.ch); + else + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function() { this.canceled = true; } + }; + if (update) obj.update = function(from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) + makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + break; + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } + else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc(doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function(range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + regLineChange(doc.cm, l, "gutter"); + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function(line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) + signalCursorActivity(cm); + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function(line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) + regChange(cm); + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + regLineChange(cm, from.line, "text"); + else + regChange(cm, from.line, to.line + 1, lendiff); + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange(doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code == "string") code = doc.splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow(cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) + result.scrollLeft = 0; + else if (x1 < screenleft) + result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); + else if (x2 > screenw + screenleft - 3) + result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos(cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) + cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; + if (top != null) + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + } + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function() { + for (var i = kill.length - 1; i >= 0; i--) + replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine() { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus();}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + operation(this, optionHandlers[option])(this, value, old); + }, + + getOption: function(option) {return this.options[option];}, + getDoc: function() {return this.doc;}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function(how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) + indentLine(this, j, how); + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function(pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) + found.push(cur.val); + } + return found; + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start == "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function(line, mode) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function() { return textHeight(this.display); }, + defaultCharWidth: function() { return charWidth(this.display); }, + + setGutterMarker: methodOp(function(line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function(line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function(gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function(line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function(line) { + if (typeof line == "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + top = pos.top - node.offsetHeight; + else if (pos.bottom + node.offsetHeight <= vspace) + top = pos.bottom; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) + scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + return commands[cmd].call(null, this); + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), + + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function(dir, unit) { + var cm = this; + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); + else + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) + doc.replaceSelection("", null, "+delete"); + else + deleteNearSelection(this, function(range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + }), + + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function(dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function(range) { + if (collapse) + return dir < 0 ? range.from() : range.to(); + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) + addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); + return pos; + }, sel_move); + if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) + doc.sel.ranges[i].goalColumn = goals[i]; + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function(ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} + : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + else + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { return this.display.input.getField() == activeElt(); }, + + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function(width, height) { + var cm = this; + function interpret(val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) + if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function(f){return runInOp(this, f);}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + estimateLineHeights(this); + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function(){return this.display.input.getField();}, + getWrapperElement: function(){return this.display.wrapper;}, + getScrollerElement: function(){return this.display.scroller;}, + getGutterElement: function(){return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) optionHandlers[name] = + notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function(cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function(cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function(cm, val) { + cm.doc.lineSep = val; + if (!val) return; + var newBreaks = [], lineNo = cm.doc.first; + cm.doc.iter(function(line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) break; + pos = found + val.length; + newBreaks.push(Pos(lineNo, found)); + } + lineNo++; + }); + for (var i = newBreaks.length - 1; i >= 0; i--) + replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) + }); + option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function() { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function(cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function(cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function(cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function(cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function(cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + } + cm.display.input.readOnlyChanged(val) + }); + option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function(cm){cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function(cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function(cm, val) { + cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) + mode.dependencies = Array.prototype.slice.call(arguments, 2); + modes[name] = mode; + }; + + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function(options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) for (var prop in spec.modeProps) + modeObj[prop] = spec.modeProps[prop]; + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function(name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function(mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function(cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function(cm) { + deleteNearSelection(cm, function(range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) + return {from: range.head, to: Pos(range.head.line + 1, 0)}; + else + return {from: range.head, to: Pos(range.head.line, len)}; + } else { + return {from: range.from(), to: range.to()}; + } + }); + }, + deleteLine: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + undoSelection: function(cm) {cm.undoSelection();}, + redoSelection: function(cm) {cm.redoSelection();}, + goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function(cm) { + cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function(cm) { + cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function(cm) {cm.moveV(-1, "line");}, + goLineDown: function(cm) {cm.moveV(1, "line");}, + goPageUp: function(cm) {cm.moveV(-1, "page");}, + goPageDown: function(cm) {cm.moveV(1, "page");}, + goCharLeft: function(cm) {cm.moveH(-1, "char");}, + goCharRight: function(cm) {cm.moveH(1, "char");}, + goColumnLeft: function(cm) {cm.moveH(-1, "column");}, + goColumnRight: function(cm) {cm.moveH(1, "column");}, + goWordLeft: function(cm) {cm.moveH(-1, "word");}, + goGroupRight: function(cm) {cm.moveH(1, "group");}, + goGroupLeft: function(cm) {cm.moveH(-1, "group");}, + goWordRight: function(cm) {cm.moveH(1, "word");}, + delCharBefore: function(cm) {cm.deleteH(-1, "char");}, + delCharAfter: function(cm) {cm.deleteH(1, "char");}, + delWordBefore: function(cm) {cm.deleteH(-1, "word");}, + delWordAfter: function(cm) {cm.deleteH(1, "word");}, + delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function(cm) {cm.deleteH(1, "group");}, + indentAuto: function(cm) {cm.indentSelection("smart");}, + indentMore: function(cm) {cm.indentSelection("add");}, + indentLess: function(cm) {cm.indentSelection("subtract");}, + insertTab: function(cm) {cm.replaceSelection("\t");}, + insertSoftTab: function(cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); + } + cm.replaceSelections(spaces); + }, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function(cm) { + runInOp(cm, function() { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function(cm) { + runInOp(cm, function() { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + } + ensureCursorVisible(cm); + }); + }, + toggleOverwrite: function(cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "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", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.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" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "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": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function(keymap) { + var copy = {}; + for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + return lookupKey(key, map.fallthrough, handle, context); + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) + options.tabindex = textarea.tabIndex; + if (!options.placeholder && textarea.placeholder) + options.placeholder = textarea.placeholder; + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function(cm) { + cm.save = save; + cm.getTextArea = function() { return textarea; }; + cm.toTextArea = function() { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) + updateLineHeight(line, textHeight(cm.display)); + } + if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function(side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function() { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function() { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) + updateLineHeight(line, line.height + dHeight); + } + }); + }; + + TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + return marker; + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + sawCollapsedSpans = true; + } + + if (marker.addToHistory) + addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function(line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + updateMaxLine = true; + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) + doc.clearHistory(); + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) + regChange(cm, from.line, to.line + 1); + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) + markers[i].parent = this; + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + this.markers[i].clear(); + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function(doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + if (doc.linked[i].isParent) return; + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function(m) { return m.parent; }); + } + + function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers(markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc];; + linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor(spans, marker) { + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan(spans, span) { + for (var r, i = 0; i < spans.length; ++i) + if (spans[i] != span) (r || (r = [])).push(spans[i]); + return r; + } + // Add a span to a line. + function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore(old, startCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange(doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); + for (var i = 0; i < gap; ++i) + newMarkers.push(gapMarkers); + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + spans.splice(i--, 1); + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + if (oldCur[k].marker == span.marker) continue spans; + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function(line) { + if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + (markers || (markers = [])).push(mark); + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + newParts.push({from: p.from, to: m.from}); + if (dto > 0 || !mk.inclusiveRight && !dto) + newParts.push({from: m.to, to: p.to}); + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.detachLine(line); + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.attachLine(line); + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + found = sp.marker; + } + return found; + } + function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || + fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) + return true; + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + line = merged.find(-1, true).line; + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) + line = merged.find(1, true).line; + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + return true; + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) + return true; + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { + if (options) for (var opt in options) if (options.hasOwnProperty(opt)) + this[opt] = options[opt]; + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + addToScrollPos(cm, null, diff); + } + + LineWidget.prototype.clear = function() { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) runInOp(cm, function() { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + }; + LineWidget.prototype.changed = function() { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) runInOp(cm, function() { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + }; + + function widgetHeight(widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + if (widget.noHScroll) + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function(line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function() { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses(type, output) { + if (type) for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) + output[prop] = lineClass[2]; + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + output[prop] += " " + lineClass[2]; + } + return type; + } + + function callBlankLine(mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken(cm, pos, precise, asArray) { + function getObj(copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function(end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function(end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + st.splice(i, 1, end, st[i+1], i_end); + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)); + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); + line.stateAfter = state; + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol()) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) + builder.addToken = buildTokenBadBidi(builder.addToken, order); + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + if (line.styleClasses.textClass) + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) + builder.content.className = "cm-tab-wrap-hack"; + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + + return builder; + } + + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); + txt.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces(old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi(inner, order) { + return function(builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + widget = builder.content.appendChild(document.createElement("span")); + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i+=2) + builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = []; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + collapsed = sp; + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) + buildCollapsedSpan(builder, 0, foundBookmarks[j]); + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null;} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + for (var i = start, result = []; i < end; ++i) + result.push(new Line(text[i], spansFor(i), estimateHeight)); + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + if (op(this.lines[at])) return true; + } + }; + + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size; }, + removeInner: function(at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function(at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + + if (typeof text == "string") text = this.splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function(line) {return lineNo(line);}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function() {return this.size;}, + firstLine: function() {return this.first;}, + lastLine: function() {return this.first + this.size - 1;}, + + clipPos: function(pos) {return clipPos(this, pos);}, + + getCursor: function(start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function() { return this.sel.ranges; }, + somethingSelected: function() {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads, options)); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + extendSelections(this, map(this.sel.ranges, f), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function(lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + else return lines.join(lineSep || this.lineSeparator()); + }, + getSelections: function(lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) + dup[i] = code; + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) + makeChange(this, changes[i]); + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function(val) {this.extend = val;}, + getExtending: function() {return this.extend;}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration);}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function(widget) { widget.clear(); }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + markers.push(span.marker.parent || span.marker); + } + return markers; + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function(line) { + var spans = line.markedSpans; + if (spans) for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(lineNo == from.line && from.ch > span.to || + span.from == null && lineNo != from.line|| + lineNo == to.line && span.from > to.ch) && + (!filter || filter(span.marker))) + found.push(span.marker.parent || span.marker); + } + ++lineNo; + }); + return found; + }, + getAllMarks: function() { + var markers = []; + this.iter(function(line) { + var sps = line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) + if (sps[i].from != null) markers.push(sps[i].marker); + }); + return markers; + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first; + this.iter(function(line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function(options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode;}, + getEditor: function() {return this.cm;}, + + splitLines: function(str) { + if (this.lineSep) return str.split(this.lineSep); + return splitLinesAuto(str); + }, + lineSeparator: function() { return this.lineSep || "\n"; } + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc(cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function(line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function(line) { out.push(line.text); }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo(line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder(line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) + pushSelectionToHistory(doc.sel, hist.done); + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + hist.done[hist.done.length - 1] = sel; + else + pushSelectionToHistory(sel, hist.done); + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) + clearSelectionEvents(hist.undone); + } + + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) + dest.push(sel); + } + + // Used to store marked span information in the history. + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { + if (line.markedSpans) + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans(spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } + else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) + nw.push(removeClearedSpans(found[i])); + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function(e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target(e) {return e.target || e.srcElement;} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function(emitter, type, f) { + if (emitter.addEventListener) + emitter.addEventListener(type, f, false); + else if (emitter.attachEvent) + emitter.attachEvent("on" + type, f); + else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var noHandlers = [] + function getHandlers(emitter, type, copy) { + var arr = emitter._handlers && emitter._handlers[type] + if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers + else return arr || noHandlers + } + + var off = CodeMirror.off = function(emitter, type, f) { + if (emitter.removeEventListener) + emitter.removeEventListener(type, f, false); + else if (emitter.detachEvent) + emitter.detachEvent("on" + type, f); + else { + var handlers = getHandlers(emitter, type, false) + for (var i = 0; i < handlers.length; ++i) + if (handlers[i] == f) { handlers.splice(i, 1); break; } + } + }; + + var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type, true) + if (!handlers.length) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type, false) + if (!arr.length) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd(f) {return function(){f.apply(null, args);};}; + for (var i = 0; i < arr.length; ++i) + list.push(bnd(arr[i])); + } + + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) + set.push(arr[i]); + } + + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f);}; + ctor.prototype.off = function(type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed() {this.id = null;} + Delayed.prototype.set = function(ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + return n + (end - i); + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) + return pos + Math.min(skipped, goal - col); + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + spaceStrs.push(lst(spaceStrs) + " "); + return spaceStrs[n]; + } + + function lst(arr) { return arr[arr.length-1]; } + + var selectInput = function(node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; + else if (ie) // Suppress mysterious IE10 errors + selectInput = function(node) { try { node.select(); } catch(_e) {} }; + + function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + if (array[i] == elt) return i; + return -1; + } + function map(array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing() {} + + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + }; + + function copyObj(obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + target[prop] = obj[prop]; + return target; + } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + }; + function isWordChar(ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty(obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/fonts/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content == "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + else range = function(node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } + catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild); + return e; + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + child = child.parentNode; + if (parent.contains) + return parent.contains(child); + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt() { + var activeElement = document.activeElement; + while (activeElement && activeElement.root && activeElement.root.activeElement) + activeElement = activeElement.root.activeElement; + return activeElement; + } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) activeElt = function() { + try { return document.activeElement; } + catch(e) { return document.body; } + }; + + function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses(a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) + if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function() { + if (resizeTimer == null) resizeTimer = setTimeout(function() { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function() { + forEachCodeMirror(onBlur); + }); + } + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function(string){return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function(te) { + try { return te.selectionStart != te.selectionEnd; } + catch(e) { return false; } + } : function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function() { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = CodeMirror.keyNames = { + 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: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" + }; + (function() { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } + function bidiRight(part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight(line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd(cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel(order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt(order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } else { + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) + target = moveInLine(line, part.to, -1, byUnit); + else + target = moveInLine(line, part.from, 1, byUnit); + } + } + } + + function moveLogically(line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType(code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + else return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function(str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) + types.push(type = charType(str.charCodeAt(i))); + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i+1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i-1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) + order.unshift(new BidiSpan(1, order[0].to, order[0].to)); + if (order[0].level != lst(order).level) + order.push(new BidiSpan(order[0].level, len, len)); + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "5.8.0"; + + return CodeMirror; +}); diff --git a/nano/js/libraries/codemirror/mode/css/css.js b/nano/js/libraries/codemirror/mode/css/css.js new file mode 100644 index 00000000000..d07426473b2 --- /dev/null +++ b/nano/js/libraries/codemirror/mode/css/css.js @@ -0,0 +1,825 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var provided = parserConfig; + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + parserConfig.inline = provided.inline; + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + supportsAtComponent = parserConfig.supportsAtComponent === true; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]+/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || + (ch == "d" && stream.match("omain(")) || + (ch == "r" && stream.match("egexp("))) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "word"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: parserConfig.inline ? "block" : "top", + stateArg: null, + context: new Context(parserConfig.inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + cx = cx.prev; + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i]] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-clip", "background-color", + "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", + "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-position", "grid-auto-rows", "grid-column", "grid-column-end", + "grid-column-start", "grid-row", "grid-row-end", "grid-row-start", + "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marker-offset", "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "region-break-after", + "region-break-before", "region-break-inside", "region-fragment", + "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", + "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page", + "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "column", "column-reverse", "compact", "condensed", "contain", "content", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "malayalam", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", + "scroll", "scrollbar", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/\s*\{/)) + return [null, "{"]; + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); diff --git a/nano/js/libraries/codemirror/theme/lesser-dark.css b/nano/js/libraries/codemirror/theme/lesser-dark.css new file mode 100644 index 00000000000..690c183d7b4 --- /dev/null +++ b/nano/js/libraries/codemirror/theme/lesser-dark.css @@ -0,0 +1,47 @@ +/* +http://lesscss.org/ dark theme +Ported to CodeMirror by Peter Kroon +*/ +.cm-s-lesser-dark { + line-height: 1.3em; +} +.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; } +.cm-s-lesser-dark div.CodeMirror-selected { background: #45443B; } /* 33322B*/ +.cm-s-lesser-dark .CodeMirror-line::selection, .cm-s-lesser-dark .CodeMirror-line > span::selection, .cm-s-lesser-dark .CodeMirror-line > span > span::selection { background: rgba(69, 68, 59, .99); } +.cm-s-lesser-dark .CodeMirror-line::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span::-moz-selection, .cm-s-lesser-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(69, 68, 59, .99); } +.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white; } +.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/ + +.cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/ + +.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; } +.cm-s-lesser-dark .CodeMirror-guttermarker { color: #599eff; } +.cm-s-lesser-dark .CodeMirror-guttermarker-subtle { color: #777; } +.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; } + +.cm-s-lesser-dark span.cm-header { color: #a0a; } +.cm-s-lesser-dark span.cm-quote { color: #090; } +.cm-s-lesser-dark span.cm-keyword { color: #599eff; } +.cm-s-lesser-dark span.cm-atom { color: #C2B470; } +.cm-s-lesser-dark span.cm-number { color: #B35E4D; } +.cm-s-lesser-dark span.cm-def { color: white; } +.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; } +.cm-s-lesser-dark span.cm-variable-2 { color: #669199; } +.cm-s-lesser-dark span.cm-variable-3 { color: white; } +.cm-s-lesser-dark span.cm-property { color: #92A75C; } +.cm-s-lesser-dark span.cm-operator { color: #92A75C; } +.cm-s-lesser-dark span.cm-comment { color: #666; } +.cm-s-lesser-dark span.cm-string { color: #BCD279; } +.cm-s-lesser-dark span.cm-string-2 { color: #f50; } +.cm-s-lesser-dark span.cm-meta { color: #738C73; } +.cm-s-lesser-dark span.cm-qualifier { color: #555; } +.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; } +.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; } +.cm-s-lesser-dark span.cm-tag { color: #669199; } +.cm-s-lesser-dark span.cm-attribute { color: #00c; } +.cm-s-lesser-dark span.cm-hr { color: #999; } +.cm-s-lesser-dark span.cm-link { color: #00c; } +.cm-s-lesser-dark span.cm-error { color: #9d1e15; } + +.cm-s-lesser-dark .CodeMirror-activeline-background { background: #3C3A3A; } +.cm-s-lesser-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } diff --git a/nano/js/libraries/codemirror/theme/liquibyte.css b/nano/js/libraries/codemirror/theme/liquibyte.css new file mode 100644 index 00000000000..9db8bde739e --- /dev/null +++ b/nano/js/libraries/codemirror/theme/liquibyte.css @@ -0,0 +1,95 @@ +.cm-s-liquibyte.CodeMirror { + background-color: #000; + color: #fff; + line-height: 1.2em; + font-size: 1em; +} +.cm-s-liquibyte .CodeMirror-focused .cm-matchhighlight { + text-decoration: underline; + text-decoration-color: #0f0; + text-decoration-style: wavy; +} +.cm-s-liquibyte .cm-trailingspace { + text-decoration: line-through; + text-decoration-color: #f00; + text-decoration-style: dotted; +} +.cm-s-liquibyte .cm-tab { + text-decoration: line-through; + text-decoration-color: #404040; + text-decoration-style: dotted; +} +.cm-s-liquibyte .CodeMirror-gutters { background-color: #262626; border-right: 1px solid #505050; padding-right: 0.8em; } +.cm-s-liquibyte .CodeMirror-gutter-elt div { font-size: 1.2em; } +.cm-s-liquibyte .CodeMirror-guttermarker { } +.cm-s-liquibyte .CodeMirror-guttermarker-subtle { } +.cm-s-liquibyte .CodeMirror-linenumber { color: #606060; padding-left: 0; } +.cm-s-liquibyte .CodeMirror-cursor { border-left: 1px solid #eee; } + +.cm-s-liquibyte span.cm-comment { color: #008000; } +.cm-s-liquibyte span.cm-def { color: #ffaf40; font-weight: bold; } +.cm-s-liquibyte span.cm-keyword { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-builtin { color: #ffaf40; font-weight: bold; } +.cm-s-liquibyte span.cm-variable { color: #5967ff; font-weight: bold; } +.cm-s-liquibyte span.cm-string { color: #ff8000; } +.cm-s-liquibyte span.cm-number { color: #0f0; font-weight: bold; } +.cm-s-liquibyte span.cm-atom { color: #bf3030; font-weight: bold; } + +.cm-s-liquibyte span.cm-variable-2 { color: #007f7f; font-weight: bold; } +.cm-s-liquibyte span.cm-variable-3 { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-property { color: #999; font-weight: bold; } +.cm-s-liquibyte span.cm-operator { color: #fff; } + +.cm-s-liquibyte span.cm-meta { color: #0f0; } +.cm-s-liquibyte span.cm-qualifier { color: #fff700; font-weight: bold; } +.cm-s-liquibyte span.cm-bracket { color: #cc7; } +.cm-s-liquibyte span.cm-tag { color: #ff0; font-weight: bold; } +.cm-s-liquibyte span.cm-attribute { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-error { color: #f00; } + +.cm-s-liquibyte div.CodeMirror-selected { background-color: rgba(255, 0, 0, 0.25); } + +.cm-s-liquibyte span.cm-compilation { background-color: rgba(255, 255, 255, 0.12); } + +.cm-s-liquibyte .CodeMirror-activeline-background { background-color: rgba(0, 255, 0, 0.15); } + +/* Default styles for common addons */ +.cm-s-liquibyte .CodeMirror span.CodeMirror-matchingbracket { color: #0f0; font-weight: bold; } +.cm-s-liquibyte .CodeMirror span.CodeMirror-nonmatchingbracket { color: #f00; font-weight: bold; } +.CodeMirror-matchingtag { background-color: rgba(150, 255, 0, .3); } +/* Scrollbars */ +/* Simple */ +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div:hover, div.CodeMirror-simplescroll-vertical div:hover { + background-color: rgba(80, 80, 80, .7); +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div, div.CodeMirror-simplescroll-vertical div { + background-color: rgba(80, 80, 80, .3); + border: 1px solid #404040; + border-radius: 5px; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-vertical div { + border-top: 1px solid #404040; + border-bottom: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div { + border-left: 1px solid #404040; + border-right: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-vertical { + background-color: #262626; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal { + background-color: #262626; + border-top: 1px solid #404040; +} +/* Overlay */ +.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div, div.CodeMirror-overlayscroll-vertical div { + background-color: #404040; + border-radius: 5px; +} +.cm-s-liquibyte div.CodeMirror-overlayscroll-vertical div { + border: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div { + border: 1px solid #404040; +} diff --git a/nano/js/nano_base_helpers.js b/nano/js/nano_base_helpers.js index 28a41518010..3f93a63934e 100644 --- a/nano/js/nano_base_helpers.js +++ b/nano/js/nano_base_helpers.js @@ -239,6 +239,18 @@ NanoBaseHelpers = function () html += ''; + return html; + }, + cMirror: function(domID) { + if(!domID) + { + return "ERR - NO domID provided"; + } + + var html = '' return html; } }; diff --git a/nano/templates/code_mirror.tmpl b/nano/templates/code_mirror.tmpl new file mode 100644 index 00000000000..dce1bf6f43b --- /dev/null +++ b/nano/templates/code_mirror.tmpl @@ -0,0 +1,14 @@ +

HELLO

+ +
+ + + +
+ + {{:helper.cMirror("fSubmit")}} +
+ +
diff --git a/paradise.dme b/paradise.dme index d174397bbd5..3035a9e060c 100644 --- a/paradise.dme +++ b/paradise.dme @@ -1785,9 +1785,7 @@ #include "code\modules\research\xenoarchaeology\tools\tools_locater.dm" #include "code\modules\research\xenoarchaeology\tools\tools_pickaxe.dm" #include "code\modules\scripting\Errors.dm" -#include "code\modules\scripting\IDE.dm" #include "code\modules\scripting\Options.dm" -#include "code\modules\scripting\stack.dm" #include "code\modules\scripting\AST\AST Nodes.dm" #include "code\modules\scripting\AST\Blocks.dm" #include "code\modules\scripting\AST\Statements.dm"