As consumers demand "mass
+customization", the hardware of our robots is meeting the challenge by becoming
+more capable. They have more degrees of freedom, higher accuracy, greater
+speed, and additional sensors.In
+order to take advantage of this hardware, we need more sophisticated
+software.This is as it should be.
+It is easier to change a line of code than to change a transmission line of
+electricity or light.
+
+
+
+
Software
+
+
Unfortunately the cost of
+software development can be quite high, especially if that cost is not
+amortized over the manufacture of many copies of the same thing. The operators
+of these robots may be factory workers, mechanical engineers or even home users
+for personal manufacturing. With the luxury of professional programmers not
+available, we must make "end user programming environments" that facilitate
+part customization, fixing build-environment specific bugs and ultimately,
+design of whole new parts.
+
+
+
+
3D printers are perhaps the
+most common "manufacturing robot" in homes, but they typically use just
+one-material and one-process for manufacturing. Complex products will need
+multiple materials and multiple processes (CNC, laser cutting, sintering, pick
+and place, assembly, etc.).
+
+
+
+
As the complexity of the
+build processes grows, so too must the job description. A conventional "app"
+with a few buttons can't accommodate the breadth of customization necessary. A
+user will need to interact at multiple levels that will permit an
+ever-increasing control over complex procedures. Ultimately we need the full
+power of a general purpose programming language. Our build process" description
+looks less like a list of numbers and more like a full-fledged program.
+
+
+
+
Robots
+
+
The Dexter Development
+Environment was designed to program the rather adept "Dexter" robot. It is a
+5-axis arm designed for table or ceiling mounting. Dexter contains a
+general-purpose processer that runs Linux as well as an FPGA supercomputer for
+high-speed parallel operations.
+
+
+
+
As flexible as Dexter is,
+complex multi-robot builds may involve not just multiple robots, but robots of
+different kinds. DDE"s architecture
+accommodates multiple kinds of robots that can perform in concert. The simplest
+robot kind that DDE supports is called "Brain". It can't perform physical
+operations on its own, but it can direct other robots to do so, just as an
+orchestra conductor doesn"t play an instrument, but directs others that do.
+
+
+
+
The "Serial" robot is a
+non-specific robot controller that drives processes through a serial port, such
+as the USB port in a laptop.It has
+been used to control an Arduino. We might think of a Serial robot as a sort of
+general purpose percussionist, who can play a variety of instruments dependent
+upon the piece to be played (or rather built.)
+
+
+
+
The "Human" robot is perhaps
+the most controversial yet conceptually interesting. Complex jobs may not be
+able to be fully automated. The Human robot has an instruction set that includes
+operations only a person can perform. These are either a textual description of
+a task, or some choice that the human operator needs to make. The important
+idea is that an instruction for a human can be stuck on a do-list and treated
+just like any other kind of instruction. We can thus synchronize human tasks
+and automated tasks in one coherent environment.
+
+
+
+
The Human robot is the singer
+in our orchestra. It does not need an instrument to perform its part. We can
+even use DDE jobs to coordinate multiple humans, a chorus if you will!
+
+
+
+
Unlike a typical musical
+performance, we don't require the person to memorize their part. Text, menus, other
+graphical widgets and even speech can be used to make life easy for the singer
+of the band. Our conductor tells the singer when to start singing, though the
+singer must tell the conductor when she is done. This allows the person to take
+as much time as the task requires, giving her maximum flexibility to perform
+her best.
+
+
+
+
+
+
An
+example of "lyrics" that DDE presents to the "singer".
+
+
+
+
Self Teaching
+
+
If this complex software
+environment is to be effectively used, it must be understood by its users. DDE utilizes a variety of media for
+explaining itself to users. Thus
+DDE performs the role of "music teacher", though not so much for training
+performers as training composers, who write the score (do-list) for each
+instrument (robot). Because a do-list is a carefully ordered sequence of
+instructions that must be synchronized with other instruments, our instructions
+bear more than a passing resemblance to notes in an actual score.
+
+
+
+
Above we see the 4 panes of
+DDE. The upper left pane is the code editor. It can contain any JavaScript. The
+content in this screen shot was inserted from an example on the Jobs menu
+(shown expanded). A job feeds the instructions on its do-list to a robot. This insertion
+comes not just with the code, but with comments explaining the code's
+functionality (in brown text).This
+particular example contains two jobs that coordinate by "synchronizing" at each
+of their "sync_point" instructions.
+
+
+
+
+
Every character in the editor
+has help available by clicking on it. Here we clicked on "sync_point".Concise help appears in the Output pane
+in the lower left. The blue text in this help is a link to extended
+documentation from the reference manual, shown in the Documentation pane in the
+upper right. The lower right is the Simulation pane, which shows a graphical
+simulation of the robot under control, or mimics a real robot.
+
+
+
+
Orchestras usually have
+scores with every note written out ahead of the performance. However, our real-world
+builds need to be more flexible than that. Robot sensors can detect anomalies
+that may need to be addressed during the build, just as professional musicians
+can cover up for each other's mistakes. Since the do-list can contain arbitrary
+JavaScript, it can actually generate new instructions on the fly, much as a
+jazz improviser composes on the spot. One of DDE's instruction types is
+literally a JavaScript "generator". It can produce a stream of instructions
+who's length needn't even set before the generator starts producing
+instructions, perhaps like some stage-hogging lead guitarist.
+
+
+
+
A Natural Language Application
+
+
We can take advantage of
+DDE's window system programming, speech generation & recognition, natural
+language parsing capability and AI reasoning to make easy-to-program, as well
+as easy-to-use interfaces to sophisticated applications. In this example, we
+use Google's speech I/O and the MIT InfoLab Group's English parser (named
+START) to build an application that lets a user create a knowledge base and ask
+questions about it, with a speech interface. The high level interface is:
+
+
+
+
+
+
+
+
If a user
+presses Click to talk before saying
+each of the above example sentences, they will create a knowledge base and get
+speech feedback after each sentence, ending with "Robot is useful because robot
+have hand."
+
+
+
+
Levels of Programming
+
+
Our base
+level of programming for this application is JavaScript. We layer on DDE
+utilities, makingaccess to I/O and
+parsing easier in the next level up. Finally we use a knowledge base and
+reasoning for our natural language interface. If a user needs functionality not
+available at a high level, they can drop down a level, remaining in the same development environment, to gain increased
+breadth at the expense of using a lower level language.
+
+
+
+
It is
+important to understand that the above English sentences are, literally, code.They create a program with a definitive
+behavior that we can access via asking questions.
+
+
+
+
Debugging
+
+
The majority
+of a programmer's time is not spent typing in code, it is in debugging that
+code. Analogously, the majority of our natural language coder's time will not
+be spent speaking the code, it will be in debugging.
+
+
+
+
A winning
+strategy for developing working code quickly is to get feedback from our
+development environment incrementally as we build our application.As we construct our "Robot Knowledge
+Base Application",the development
+environment gives us feedback after each sentence. For the two sentences that
+add knowledge to the knowledge base, "A robot has a hand." and "If a
+robot has a hand, a robot is useful.",
+our development environment responds with "OK" and "Got it."
+(Identical acknowledgement in English is boring an unnatural!) This informs our
+natural language coder that their utterances are syntactically correct.
+
+
+
+
If we
+consider that the goal of our app is to answer the final question, the
+intermediate questions are probing the semantic validity of the knowledge base
+being built.They take the place of
+"print statements" in traditional programming. However, as you can see, they
+are much higher level than print statements. They don't need to be embedded
+inside some complex algorithm, and they produce output in a very understandable
+way. For instance "Does a robot have a hand?" is responded to with "Yes, a robot
+has a hand".
+
+
+
+
Knowledge Base Debugging
+
+
Applications
+that rely on knowledge bases have a special kind of bug: bugs in the knowledge
+base itself. We therefore need to be especially careful to inform the natural
+language coder what's in that (potentially huge) knowledge base, but only with what's
+relevant at the moment.
+
+
+
+
Here's a
+dialog our app supports:
+
+
+
+
Human: A robot has a hand.
+
+
DevEnv: OK.
+
+
Human: A robot has a hand.
+
+
DevEnv: I already know that.
+
+
+
+
Our
+application responds to the first sentence with "OK" but the 2nd
+sentence with "I already know that." This informs our natural language coder about
+redundancy, much as a fellow human would in a conversation. Furthermore, our
+app does not stick into the knowledge base the same knowledge twice.
DevEnv: Sorry, robot is useful, is
+only true under certain conditions.
+
+
+
+
Human: A robot has a hand.
+
+
DevEnv: Got it.
+
+
+
+
Human: Why is a robot useful?
+
+
DevEnv: Robot is useful because
+robot have hand.
+
+
+
+
+
+
Notice that
+there are three different responses to the Human's question of "Why is a robot
+useful?". Each informs the user about what is in the knowledge base at time
+time of the ask, giving clues about one of the most common bugs: missing
+knowledge.
+
+
+
+
Conclusion
+
+
Dexter Development
+Environment lets uses "print" a part from a design contained in Jobs that have
+do-lists. But this rather passive interaction is analogous to an audience member
+at a concert. Via end-user programming techniques, we enable the user to
+orchestrate the process, ultimately giving them control of even the low-level
+instructions in the process. With the "Human" robot, we can synchronize what
+machines do best with what people can do best by providing appropriately timed
+instructions, similar to real-time lyric presentation in a Karaoke bar.
+The complexity of composing build-scripts can be mitigated by DDE's
+self-teaching techniques and the AI of natural language processing plus
+knowledge base management that we've only just begun (apologies to
+the Carpenters).
adjust the current joints 2 pots until the points form a circle.
" +
+ "
Wait until points stop drawing (about 30 seconds)
" +
+ "
click in the center of the circle.
" +
+ "
click the green button
" +
+ "
repeat for the next joint.
",
+ user_data_variable_name: "measurement_axis",
+ initial_value: 0,
+ min: 0,
+ max: 5,
+ step: 1,
+ }))
+ retCMD.push(function () {if (this.user_data.measurement_axis != 5){ return new_eye_window()}})
+ retCMD.push(function () {return Dexter.move_all_joints(0, 0, 0, 0, 0)})
+ retCMD.push(function () {if (this.user_data.measurement_axis != 5){ return smLinex(AxisTable [this.user_data.measurement_axis][4], this.user_data.measurement_axis)}})
+ retCMD.push(function () {if (this.user_data.measurement_axis != 5){ return scan_axis()}})
+ return retCMD
+
+}
+
+function init_view_eye(){ //can't eval this until Dexter properly defined.
+ new Dexter({name: "basic_move_test_dex", ip_address: "192.168.1.144", port: 50000,
+ enable_heartbeat: false, simulate: false})
+ new Job({name: "BasicMoveTest2", robot: Robot.basic_move_test_dex, keep_history: false,
+ inter_do_item_dur: 5,
+ do_list: [ Dexter.move_all_joints(0, 0, 0, 0, 0),
+ make_ins("S", "J1BoundryHigh",648000),
+ make_ins("S", "J1BoundryLow",-648000),
+ make_ins("S", "J2BoundryLow",-350000),
+ make_ins("S", "J2BoundryHigh",350000),
+ make_ins("S", "J3BoundryLow",-570000),
+ make_ins("S", "J3BoundryHigh",570000),
+ make_ins("S", "J4BoundryLow",-390000),
+ make_ins("S", "J4BoundryHigh",390000),
+ make_ins("S", "J5BoundryLow",-680000),
+ make_ins("S", "J5BoundryHigh",680000),
+
+ make_ins("S", "MaxSpeed",200000),
+ make_ins("S", "Acceleration",1),
+ make_ins("S", "StartSpeed",7500),
+ scan_axis(),
+ function () {return centers_output()},
+ make_ins("S", "MaxSpeed",300000),
+ make_ins("S", "Acceleration",1),
+ make_ins("S", "StartSpeed",500),
+ Dexter.move_all_joints(0, 0, 0, 0, 0)
+ ]})
+}
+// Job.BasicMoveTest2.start()
+
+
+/*
+var centers_string = undefined
+
+file_content("AdcCenters.txt", function (str) {centers_string = str})
+
+out (centers_string)
+
+write_file("AdcCenters.txt", centers_string) */
+
+
+
diff --git a/app_builder.js b/app_builder.js
new file mode 100644
index 00000000..015620c8
--- /dev/null
+++ b/app_builder.js
@@ -0,0 +1,764 @@
+/* Created by Fry on 2/1/16.*/
+
+function ab(){} //just a namespace
+
+//in sandbox
+ab.window_names = [] //don't put this in the init as we want it to persist accross tasks, whe user clicks New task
+
+ab.init = function(){
+ // these are per training window use and get reinited when new training window is opened
+ ab.window_name = ""
+ ab.input_names = []
+ ab.button_name_to_action_map = {}
+ ab.has_items = false //we might have only static text in which case, ab.input_names.length == 0
+}
+
+ab.post_creation_window_init = function(){
+ var vals = {} //we don't have any as we're just initing
+ var new_win_default_name = "window_" + (ab.window_names.length + 1)
+ dex.set_in_window(undefined, "window_name", "value", new_win_default_name)
+ ab.fill_in_action_names(vals)
+}
+
+ab.actions = function(){
+ var result = ['out("clicked on " + vals.clicked_button_value)', 'out(vals)']
+ for (var wn of ab.window_names){
+ result.push(wn + "()")
+ }
+ return result
+}
+
+ab.handle_fn_start = function(vals, always_add_function_header){
+ //returns empty string unless the "function ..." code needed, in which case it returns it
+ var fn_start = ""
+ if(always_add_function_header || (ab.input_names.length == 0)){
+ ab.window_name = vals.window_name
+ fn_start = "function " + ab.clean_name(vals.window_name) + "(){ //window \n" +
+ " show_window({content:`\n"
+ }
+ return fn_start
+}
+
+
+ab.insert_etc = function(pure_code, code, vals, can_have_action){
+ Editor.insert(code)
+ ab.has_items = true //includes not just inputs but static text too. important to know that "something's been added"
+ var inp_name = vals.input_name
+ if (vals.clicked_button_value != "Button"){
+ inp_name = ab.clean_name(inp_name)
+ }
+ var elt_to_add_to_input_names = inp_name //ab.clean_name(vals.input_name)
+ if (!can_have_action){
+ elt_to_add_to_input_names = [elt_to_add_to_input_names, "cant_have_action"]
+ }
+ ab.input_names.push(elt_to_add_to_input_names)
+ //dex.train_number_of_insertions += 1 //the next index
+ //dex.train_action_name_to_pure_code[clean_action_or_task_name(vals.action_name)] = pure_code //for Do action button
+ //var action_options = ""
+ //for(var act of dex.train_action_names){
+ // action_options += "
" + act + "
"
+ //}
+ //dex.set_in_window(vals.window_index, "do_action_action_names", "innerHTML", action_options)
+ //dex.set_in_window(vals.window_index, "repeat_from_action_names", "innerHTML", action_options)
+ // dex.set_in_window(vals.window_index, "repeat_through_action_names", "innerHTML", action_options)
+
+ var new_input_name_default = "input_" + (ab.input_names.length + 1) //make this 1 based so that the instruction "click to add the 1st action ..." will make most sense.
+ dex.set_in_window(vals.window_index, "input_name", "value", new_input_name_default)
+ ab.replace_top_instruction_line(vals)
+ ab.show_window(vals)
+}
+
+ab.code_for_handle_fn = function(vals) {
+ var code = "function handle_" + vals.window_name + "_input(vals){\n"
+ var cond_keyword = "if"
+ //for (var inp_name of ab.input_names){
+ for (var inp_name in ab.button_name_to_action_map){
+ if (typeof(inp_name) == "string"){
+ var inp_code = ' ' + cond_keyword + '(vals.clicked_button_value == "' + inp_name + '"){\n' +
+ ' ' + ab.button_name_to_action_map[inp_name] +
+ '\n }\n'
+ code += inp_code
+ cond_keyword = "else if"
+ }
+ //else inp_name looks like ["some_static_text_name", "cant_have_action"]
+ }
+ code += "}\n\n"
+ return code
+}
+
+
+ab.replace_top_instruction_line = function(vals, text){
+ if (text == null){
+ var index = ab.input_names.length + 1
+ var index_string = integer_to_ordinal(index)
+ text = "Click on a button below to add the " + index_string + " input to this window."
+ }
+ text = "" + text + ""
+ dex.set_in_window(vals.window_index, "top_instruction_line", "innerHTML", text)
+}
+
+
+
+ab.fill_in_action_names = function(vals){ //just called by New task
+ /* var task_options = ""
+ for (var task of dex.train_task_names){ //train_task_names whne this is called in new Task,
+ //has just been extended with vals.task_name but
+ //don't worry about recursion because we are now
+ //getting OUT of the cur task and into a new one.
+ task_options += "
"
+ }
+ dex.set_in_window(vals.window_index, "task_names_datalist", "innerHTML", task_options)
+ */
+ var new_val = ab.actions()
+ dex.set_in_window(vals.window_index, "actions", "combo_box_options", new_val)
+ //dex.set_in_window(vals.window_index, "format_action", "combo_box_options", new_val)
+
+}
+
+ab.clean_name = function(name){
+ name = name.trim()
+ name = name.replace(/ /g, " ") //replace 3 spaces with 1
+ name = name.replace(/ /g, " ") //replace 2 spaces with 1
+ name = name.replace(/ /g, "_") //replace 1 space with underscore
+ return name
+}
+
+ab.semi_clean_name = function(name){
+ name = name.trim()
+ name = name.replace(/ /g, " ") //replace 3 spaces with 1
+ name = name.replace(/ /g, " ") //replace 2 spaces with 1
+ //name = name.replace(/ /g, "_") //replace 1 space with underscore
+ return name
+}
+
+//in sandbox
+function handle_ab(vals){ //not dex.handle_train because then I can't use the name in the show_window 2nd arg.
+ //don't insert fn_start UNTIL the user does the first real action insert, so as making canceling easier
+ var can_have_action = true
+ var always_add_function_head = false
+ if (vals.clicked_button_value == "New line"){
+ can_have_action = false
+ var pure_code = ' \n'
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Horizontal line"){
+ can_have_action = false
+ var pure_code = ''
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Horizontal space"){
+ can_have_action = false
+ var pure_code = ''
+ var code = ab.handle_fn_start(vals) + pure_code + "\n" //"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+
+ else if (vals.clicked_button_value == "Format"){
+ var text
+ if (vals.format_kind == "static text"){
+ can_have_action = false
+ text = vals.format_text.replace(/\n/g, " ")
+ }
+ else if (vals.format_kind == "bullet points"){
+ can_have_action = false
+ text = vals.format_text.replace(/\n/g, "
")
+ text = "
" + text + "
"
+ }
+ else if (vals.format_kind == "numbered points"){
+ can_have_action = false
+ text = vals.format_text.replace(/\n/g, "
")
+ text = "
" + text + "
"
+ }
+ else if (vals.format_kind == "table"){
+ can_have_action = false
+ text = vals.format_text.replace(/,\n/g, "\n") //remove extra comma at end of line so as to have a canonical format.
+ if (text.endsWith(",")){ text = text.substring(0, text.length - 1)} //trailing comma is bad.
+ text = text.replace(/\n/g, "\n
")
+ text = text.replace(/\,/g, "
")
+ text = "
\n
" + text + "
\n
\n"
+ }
+ else if (vals.format_kind == "table: top row bold"){
+ can_have_action = false
+ text = vals.format_text.replace(/\,\n/g, "\n")
+ if (text.endsWith(",")){ text = text.substring(0, text.length - 1)} //trailing comma is bad.
+ var first_return_pos = text.indexOf("\n")
+ var first_row = ""
+ var other_rows = ""
+ if (first_return_pos == -1) {
+ first_row = text
+ }
+ else {
+ first_row = text.substring(0, first_return_pos)
+ other_rows = text.substring(first_return_pos + 1)
+ }
+ first_row = "
') //this is the only thing diferent (added) from the "table: top row bold" def
+ }
+ text = first_row + other_rows + "
\n"
+ }
+ else if (vals.format_kind == "single_line_input"){
+ text = vals.input_name + ': '
+ }
+ else if (vals.format_kind == "multi_line_input"){
+ text = '"
+ }
+ else if (vals.format_kind == "radio buttons"){
+ var lines = vals.format_text.split("\n")
+ text = ""
+ for (var line of lines){
+ var sel = ""
+ if (line.endsWith("selected")){
+ sel = " checked" //radio and checkbox need "checked" but select tag needs "selected". HTML was not designed. I make them all consistent with "selected"
+ line = line.substring(0, line.length - 8)
+ }
+ line = line.trim()
+ var but = '' +
+ line + " \n"
+ text += but
+ }
+ }
+ else if (vals.format_kind == "select"){
+ var lines = vals.format_text.split("\n")
+ text = '\n"
+ }
+ else if (vals.format_kind == "combo box"){
+ var lines = vals.format_text.split("\n")
+ text = '
\n'
+ for (var line of lines){
+ var sel = ""
+ if (line.endsWith("selected")){
+ sel = " selected" //radio and checkbox need "checked" but select tag needs "selected". HTML was not designed. I make them all consistent with "selected"
+ line = line.substring(0, line.length - 8)
+ }
+ line = line.trim()
+ var but = '
' +
+ line + "
\n"
+ text += but
+ }
+ text += "
\n"
+ }
+ else if (vals.format_kind == "details hierarchy"){
+ can_have_action = false //turns off saving of clicking on the menu title, but not the underlying items.
+ if(vals.format_text.length == 0){
+ out("No text in the textarea to make a details hierarchy out of.", "red")
+ return
+ }
+ else{
+ text = dex.make_details_items(0, 0, vals.format_text.split("\n"))
+ }
+ }
+ else if (vals.format_kind == "menu"){
+ can_have_action = false //turns off saving of clicking on the menu title, but not the underlying items.
+ text = '
\n
' + vals.input_name + "▼\n"
+ /*text = text + "
\n"
+ for (var item of vals.format_text.split("\n")){
+ text += "
" + item + "
\n"
+ }
+ text = text + "
\n"*/
+ if (vals.format_text != ""){ //because split of empty string returns [""] ie 1 item
+ always_add_function_head = (ab.input_names.length == 0) //only needed for menu because make_menu_items adds to input_names
+ text += dex.make_menu_items(0, 0, vals.format_text.split("\n"), vals.actions)
+ }
+ text += "
\n
"
+ }
+ var font_weight = 200
+ var font_style = "normal" //could be italic
+ if (vals.font_style == "bold") { font_weight = 700 }
+ else if (vals.font_style == "italic"){ font_style = "italic" }
+ var pure_code = '\n' +
+ text + '' //todo fails to set color, etc of menu items.
+ var code = ab.handle_fn_start(vals, always_add_function_head) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Button"){
+ var name = ab.semi_clean_name(vals.input_name) //dontreplace single spaces with underscore
+ vals.input_name = name
+ ab.button_name_to_action_map[vals.input_name] = vals.actions
+ var kind = vals.button_kind
+ var pure_code
+ if (kind == "close window"){
+ pure_code = ''
+ }
+ else if (kind == "don't close"){
+ pure_code = ''
+ }
+ else if (kind == "underlined link") {
+ var href_val = "#"
+ var act = vals.actions
+ if (act.indexOf("(") == -1){ //assume action is a url
+ href_val = act
+ }
+ pure_code = '' + vals.input_name + ''
+ }
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Number"){
+ //infer optimal width by looking at initial, min and max. a min or max is more important than initial for determining width
+ var most_chars = 1
+ var any_non_nans = false
+ var initial_only = false
+ var val = vals.number_initial
+ var str
+ if (val) {
+ str = val.toString()
+ most_chars = Math.max(most_chars, str.length)
+ any_non_nans = true
+ initial_only = true
+ }
+ val = vals.number_min
+ if (val) {
+ str = val.toString()
+ most_chars = Math.max(most_chars, str.length)
+ any_non_nans = true
+ initial_only = false
+ }
+ val = vals.number_max
+ if (val) {
+ str = val.toString()
+ most_chars = Math.max(most_chars, str.length)
+ any_non_nans = true
+ initial_only = false
+ }
+ val = vals.number_step
+ if (val) {
+ str = val.toString()
+ if (str.indexOf(".") != -1) { most_chars += (str.length - 1) } //got decimal points. Not perfect but will get us closer.
+ }
+ if (initial_only) {most_chars = most_chars + 3} //will be at least 4 giving us -999 thru 9999
+ else if (!any_non_nans) {most_chars = 5 }
+ var width = 15 + (most_chars * 7) //the widget takes up a certain constant amount of pixels
+ var pure_code = vals.input_name + ''
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Checkbox"){
+ var checked = ""
+ if (vals.checkbox_checked) { checked = ' checked="checked"' }
+ var pure_code = '" + vals.input_name
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Color"){
+ var pure_code = vals.input_name +
+ ': '
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ else if (vals.clicked_button_value == "Datetime"){
+ var pure_code
+ if (vals.datetime_type == "year"){
+ pure_code = vals.input_name +
+ ': '
+ }
+ else {
+ pure_code = vals.input_name +
+ ': '
+ }
+ var code = ab.handle_fn_start(vals) + pure_code + "\n"
+ ab.insert_etc(pure_code, code, vals, can_have_action)
+ }
+ //______________________________________________
+ else if (vals.clicked_button_value == "Undo"){
+ if (ab.input_names.length == 0){
+ out("Sorry, there are no more input items in the currently being made window to undo.",
+ "red")
+ }
+ else {
+ var last_input_name = ab.input_names.pop()
+ if (Array.isArray(last_input_name)){
+ last_input_name = last_input_name[0]
+ }
+ delete ab.button_name_to_action_map[last_input_name]
+ Editor.undo()
+ dex.set_in_window(vals.window_index, "input_name", "value", last_input_name)
+ //tricky figuring out what should go in the window's input name.
+ //consier hitting undo twice in a row.
+ //we like undo to leave the window in a state where we can click, say
+ //format button and have it do the same thing that you undid. (if it was added with format)
+ ab.replace_top_instruction_line(vals)
+ ab.show_window(vals)
+ }
+ }
+ else if (vals.clicked_button_value == "Show Window"){
+ ab.show_window(vals)
+ }
+ else if (vals.clicked_button_value == "New Window"){
+ if (ab.input_names.length > 0){ //otherwise we haven't made a real window so insert nothing as user was probably "just looking".
+ Editor.close_app_builder_temp_windows()
+ var win_name = ab.clean_name(vals.window_name)
+ var finish_win_code = dex.code_to_finish_window(vals)
+ var the_call = "// " + win_name + "() //eval to launch this window\n\n"
+ Editor.insert(finish_win_code + the_call)
+ //Editor.insert(win_name + "() //eval to launch this window\n\n")
+ var handle_fn_code = ab.code_for_handle_fn(vals)
+ Editor.insert_before_fn_def(win_name, handle_fn_code)
+ ab.window_names.push(win_name)
+ }
+ ab.launch()
+ }
+ else if (vals.clicked_button_value == "Done"){
+ if (ab.input_names.length > 0){ //otherwise we haven't made a real window so insert nothing as user was probably "just looking".
+ Editor.close_app_builder_temp_windows()
+ var win_name = ab.clean_name(vals.window_name)
+ var finish_win_code = dex.code_to_finish_window(vals)
+ var the_call = win_name + "() //eval to launch this window\n\n"
+ Editor.insert(finish_win_code + the_call)
+ //Editor.insert(win_name + "() //eval to launch this window\n\n")
+ var handle_fn_code = ab.code_for_handle_fn(vals)
+ Editor.insert_before_fn_def(win_name, handle_fn_code)
+ ab.window_names.push(win_name)
+ }
+ }
+}
+
+ab.show_window = function (vals){
+ var handle_fn_code = ab.code_for_handle_fn(vals)
+ var end_main_fn_code = dex.code_to_finish_window(vals)
+ var win_name = vals.window_name
+ if (ab.input_names.length == 0){
+ //out("You haven't declared any window parts yet so there's nothing to show.")
+ Editor.close_app_builder_temp_windows() //might be none open which is ok
+ var start_main_fn_code = "function " + win_name + "(){" +
+ "show_window({window_class:'app_builder_temp_window', content:`"
+ var the_call = win_name + "()"
+ var full_code = handle_fn_code + start_main_fn_code + end_main_fn_code + the_call
+ eval(full_code)
+ }
+ else {
+ Editor.run_unfinished_app_builder_window(win_name, handle_fn_code, end_main_fn_code)
+ }
+}
+
+//in sandbox
+//makes a forrest of details
+dex.make_details_items = function(level, index, all_lines){
+ var result = ""
+ if (all_lines.length == index){
+ return ""
+ }
+ var this_level_ul_spaces = spaces((level * 4) + 2)
+ var this_level_li_spaces = spaces((level + 1) * 4)
+ result = "" //this_level_ul_spaces + "
\n"
+ for (var i = index; i < all_lines.length; i++){
+ index = i
+ var line = all_lines[i]
+ var line_indent = dex.initial_spaces(line)
+ if (line_indent == -1) {} //skip it
+ else if (line_indent < level) {
+ return result
+ }
+ else if (line_indent > level){
+ var sub_results = dex.make_details_items(level + 1, i, all_lines)
+ var menu_items_processed_count = sub_results.match(/margin-left\:/g).length
+ i = i + menu_items_processed_count - 1
+ result += sub_results + this_level_li_spaces + "\n"
+ }
+ else{
+ var line_trimmed = line.trim()
+ var margin_left = 20
+ if(level == 0) {margin_left = 0}
+ var new_item = ""
+ if (index == (all_lines.length - 1)) { //on the last line
+ new_item = this_level_li_spaces + '
● ' + line_trimmed + "
\n"
+ }
+ else if (dex.initial_spaces(all_lines[index + 1]) <= level){ //the next line is either at the same level as this one or up level(s)
+ new_item = this_level_li_spaces + '
● ' + line_trimmed + "
\n"
+ }
+ else {//recursing down a level on next iteration.
+ new_item = this_level_li_spaces + '' + line_trimmed + "\n"
+ }
+ result += new_item
+ /*var new_item = this_level_li_spaces + '' + line_trimmed + "\n"
+ if (index == (all_lines.length - 1)) { //on the last line
+ new_item += this_level_li_spaces + "\n"
+ }
+ else if (dex.initial_spaces(all_lines[index + 1]) <= level){ //the next line is either at the same level as this one or up level(s)
+ //if we have to recurse down a level on the next interation, then we must
+ //leave the closing tag off, otherwise, as in this case, put it on.
+ new_item += this_level_li_spaces + "\n"
+ }
+ else { //recursing down a level on next iteration. new item is '
\n"
+}
+
+//in sandbox
+dex.make_menu_items = function(level, index, all_lines, action_for_all_items){
+ var result = ""
+ if (all_lines.length == index){
+ return ""
+ }
+ var this_level_ul_spaces = spaces((level * 4) + 2)
+ var this_level_li_spaces = spaces((level + 1) * 4)
+ result = this_level_ul_spaces + "
\n"
+ for (var i = index; i < all_lines.length; i++){
+ index = i
+ var line = all_lines[i]
+ var line_indent = dex.initial_spaces(line)
+ if (line_indent == -1) {} //skip it
+ else if (line_indent < level) {
+ return result
+ }
+ else if (line_indent > level){
+ var sub_results = dex.make_menu_items(level + 1, i, all_lines, action_for_all_items)
+ var menu_items_processed_count = sub_results.match(/
/g).length
+ i = i + menu_items_processed_count - 1
+ result += sub_results + this_level_li_spaces + "
\n"
+ }
+ else{
+ var line_trimmed = line.trim()
+ var new_item = this_level_li_spaces + "
" + line_trimmed
+ ab.input_names.push(ab.clean_name(line_trimmed))
+ ab.button_name_to_action_map[line_trimmed] = action_for_all_items
+ if (index == (all_lines.length - 1)) { //on the last line
+ new_item += "
\n"
+ }
+ else if (dex.initial_spaces(all_lines[index + 1]) <= level){ //the next line is either at the same level as this one or up level(s)
+ //if we have to recurse down a level on the next interation, then we must
+ //leave the closing tag off, otherwise, as in this case, put it on.
+ new_item += "\n"
+ }
+ else { //recursing down a level on next iteration. new item is '
+`,
+ title: '' +
+ 'Application Builder',
+ width:480,
+ height:590,
+ x:540, //x and y positioned so that if you shrink this window, it will as much as pssible not occlude the most useful DDE info.
+ y:80,
+ callback: handle_ab //"handle_ab"
+})
+ setTimeout(function(){ab.post_creation_window_init()}, 100) //needed to init the combo box for actions
+}
+
+
+
diff --git a/build.js b/build.js
new file mode 100644
index 00000000..8a4cf71e
--- /dev/null
+++ b/build.js
@@ -0,0 +1,17 @@
+#!/usr/bin/env node
+const electronPackager = require('electron-packager');
+var options = { dir: './', // current directory is the source directory
+ out: './dist', //output folder
+ platform: 'darwin,win32', //,linux,win32', //OSes that we're making builds for. win32 just means "win", not 32 bit arch
+ arch: 'all', //hardware to produce builds for, darwin(mac) has just 1. wind32 has a 32 & a 64 bit. linux has 3
+ name: 'dexter_development_environment', //the name of the .app file produced
+ asar: true,
+ overwrite: true, //replace the prev created build files
+ prune: true //get rid of excess files
+ };
+electronPackager(options, (error, appPath) => {
+ if(error){ // something went wrong
+ throw error;
+ }
+ console.log(' Success! See ' + appPath);
+ });
\ No newline at end of file
diff --git a/build_dexter.zip b/build_dexter.zip
new file mode 100644
index 00000000..5a29c31c
Binary files /dev/null and b/build_dexter.zip differ
diff --git a/build_dexter/arm_body_subassembly.png b/build_dexter/arm_body_subassembly.png
new file mode 100644
index 00000000..27115ac1
Binary files /dev/null and b/build_dexter/arm_body_subassembly.png differ
diff --git a/build_dexter/build_dexter.html b/build_dexter/build_dexter.html
new file mode 100644
index 00000000..aff77a88
--- /dev/null
+++ b/build_dexter/build_dexter.html
@@ -0,0 +1,117 @@
+Build Dexter 1.0
+You can get Dexter as a kit to put together or fully assembled.
+Why Build Dexter?
+Most stores sell fully-assembled products. Those that don't often
+have a deservedly bad reputation for lousy documention including
+ambiguous prose, missing steps, low-rez gray on gray diagrams.
+We're bending over backwards to be different because there's
+a lot of advantages to building your own Dexter.
+
+
Cheaper.
+
It's the best way to understand the hardware.
+
You'll get ideas for designing and building your own stuff.
+
You'll become familar with the metric system in a literally tangible way.
+
Impress your friends, intimidate your enemies.
+
Become able to fix it when something goes wrong.
+
Looks good on a resume.
+
You'll own the Dexter in a deeper way.
+
Facilitate customization.
+
Help us improve the build process, which will help everyone following
+ in your footsteps.
+
+ Please take notes on anything you think can be improved and send them to us.
+ Your creativity required!
+
+Printing Dexter's Parts
+Dexter is a high performace, tight tolerances machine. Getting each part right
+is essential to ease of assembly and reliability once its finished. We are not
+recommended that attempting to build Dexter be your first 3D printed project.
+
+There are a zillion different 3D printers out there.
+Probably Dexter's parts can be printed on many of them but we haven't tested
+the vast majority of them. Our favorite printer now is Dremel's 3D40 Idea Builder.
+This is not a "cutting edge" printer, which is one of the things we like about it.
+A solid performer that gets the job done. Please share your experiences with us
+if you use a different printer.
+
+Dexter has {67} printable parts.
+There are a large number of other parts, mostly steel, aluminum, carbon fiber
+and electronics that are not printed, but are included in a kit.
+We have arranged parts into groups called "beds" that can all be printed at once.
+A bed has about 10 parts or so, reducing greatly the number of print jobs
+you'll have to run. Each bed corresponds roughly to a 'sub-assembly".
+
+Each bed must be printed with one material and a constant "in-fill" throughout
+the print. To save weight, a part has internal holes. the percentage of
+solid parts to the whole volume of a part is called its "infill".
+All beds for Dexter use 45% infill except for the differential sub-assembly that
+requires 100% infll for extra strength.
+
+The build plate files are configured to be able to be printed on a printer
+that can print 200mm x 150mm (x and x), which is most 3D printers now being used.
+The maximum height of a build plate is ???mm. PLA works well and is what
+we are now using. {Discuss ABS or other materials???}. You will need ???kg of
+PLA to print all the parts.
+
Testing Printed Parts
+Generally it is best to test all parts before assembling them.
+
Visually inspect for no cracks
+
Try to bend the part with your fingers. All parts should be rigid except for
+ the optical disk
+
Weigh the part and compre the weigth to its expected weight.
+ This is a clue about the "infill".
+
Measure the part's longest dimension and compare it to its expected length
+
Make sure any bolt holes are clear an cylindrical.
+
+
Fixing Broken Parts
+If your printer bed is smaller than 200mm x 150mm, or you need to print out
+just one part within a built plate, find the part in the single_parts folder,
+load its STL file into your printer and print just it.
+
+Assembling Dexter
+Tools
+
Expoxy Glue XXX ??? ???oz.
+
syringe for glue make and model??? homw many???
+
Needle nose pliers
+
???
+
+
+Arm Body Sub-Assembly
+This subassembly is the ???
+
+ Back Intersection part
+ Material: PLA
+ Length: ???mm
+ Weight: ???gm
+ Directions: Start the subassembly with this part.
+
+ Intersection part
+ Material: PLA
+ Length: ???mm
+ Weight: ???gm
+ Directions:
+
Put 1.5ml of glue on the cross-hatched area.
+
Place part glue side down on the Back Intersection like so:
+
+
Allow glue to dry for 1 minute before moving to next step.
+
+
+ 1 Inch Tube Intersection part
+
+ Top Body part
+
+ Bottom part
+
+
+Main Pivot Sub-Assembly
+
+Base Sub-Assembly
+
+External Gear Sub-Assembly
+
+Differential Sub-Assembly
+
+End Arm Sub-Assembly
+
+
+
+
diff --git a/build_mac_installer.js b/build_mac_installer.js
new file mode 100644
index 00000000..ec138e86
--- /dev/null
+++ b/build_mac_installer.js
@@ -0,0 +1,27 @@
+/**
+ * Created by Fry on 2/20/17.
+ */
+
+var sign = require('electron-osx-sign')
+sign({app: './dist/dexter_development_environment-darwin-x64/dexter_development_environment.app',
+ identity: 'cfry@hdrobotic.com',
+ platform: "darwin"
+ }
+ , function done (err) {
+ if (err) { console.log("Error while attempting to sign Mac app: " + err)}
+ }
+ )
+
+
+const electronInstallerDmg = require('electron-installer-dmg')
+electronInstallerDmg({
+ appPath: "./dist/dexter_development_environment-darwin-x64/dexter_development_environment.app",
+ out: "./dist",
+ name: 'dexter_development_environment',
+ overwrite: true,
+ debug: true
+}, function done (err) {
+ if(err){
+ console.log("electronInstallerDMG errored with: " + err)
+ }
+})
diff --git a/build_win_installer.js b/build_win_installer.js
new file mode 100644
index 00000000..23be2187
--- /dev/null
+++ b/build_win_installer.js
@@ -0,0 +1,29 @@
+/**
+ * Created by Fry on 2/18/17.
+ */
+ //from https://www.christianengvall.se/electron-windows-installer/
+const createWindowsInstaller = require('electron-winstaller').createWindowsInstaller
+const path = require('path')
+
+function getInstallerConfig () {
+ console.log('creating windows installer')
+ const rootPath = path.join('./')
+ const outPath = path.join(rootPath, 'build_releases')
+
+ return Promise.resolve({
+ appDirectory: "./", //path.join(outPath, 'dexter_development_environment-win32-x64/'),
+ authors: 'Fry',
+ noMsi: true,
+ outputDirectory: path.join(outPath, 'windows-installer'),
+ exe: 'dexter_development_environment.exe', //the "input" file (name only) made by electron-packager
+ setupExe: 'dexter_development_environment.exe'
+ //setupIcon: path.join(rootPath, 'assets', 'icons', 'win', 'icon.ico')
+ })
+}
+
+getInstallerConfig()
+ .then(createWindowsInstaller)
+ .catch((error) => {
+ console.error(error.message || error)
+process.exit(1)
+})
diff --git a/calibration.js b/calibration.js
new file mode 100755
index 00000000..d24d4249
--- /dev/null
+++ b/calibration.js
@@ -0,0 +1,67 @@
+
+//we must have an int fn here because if we just let this eval upon load,
+//then Dexter might not be defined, then we get screwed up
+function init_calibration(){
+new Dexter({name: "calibration_dex", ip_address: "192.168.1.144", port: 50000, enable_heartbeat: false, simulate: false})
+return new Job({name: "calibration_job",
+ robot: Robot.calibration_dex,
+ do_list: [make_ins("w", 42,64),
+ make_ins("w", 42,0),
+ make_ins("w", 42,256),
+ make_ins("w", 42,0),
+ make_ins("w", 79, 50 ^ 200 ),
+ make_ins("w", 80, 50 ^ 200 ),
+ make_ins("w", 81, 50 ^ 200 ),
+ make_ins("S", "J1BoundryHigh",670000),
+ make_ins("S", "J1BoundryLow",-670000),
+ make_ins("S", "J2BoundryLow",-350000),
+ make_ins("S", "J2BoundryHigh",350000),
+ make_ins("S", "J3BoundryLow",-570000),
+ make_ins("S", "J3BoundryHigh",570000),
+ make_ins("S", "J4BoundryLow",-390000),
+ make_ins("S", "J4BoundryHigh",390000),
+ make_ins("S", "J5BoundryLow",-680000),
+ make_ins("S", "J5BoundryHigh",680000),
+ Dexter.move_all_joints(670000,0,0,0,0),
+ make_ins("w", 42,1),
+ Dexter.move_all_joints(-670000,0,0,0,0),
+ make_ins("w", 42,0),
+ Dexter.move_all_joints(0,0,0,0,0),
+ Dexter.move_all_joints(0,330000,0,0,0),
+ make_ins("w", 42,4),
+ Dexter.move_all_joints(0,-330000,0,0,0),
+ make_ins("w", 42,0),
+ Dexter.move_all_joints(0,0,0,0,0),
+ Dexter.move_all_joints(0,0,550000,0,0),
+ make_ins("w", 42,2),
+ Dexter.move_all_joints(0,0,-550000,0,0),
+ make_ins("w", 42,0),
+ Dexter.move_all_joints(0,0,0,0,0),
+ make_ins("S", "MaxSpeed", 80000),
+ Dexter.move_all_joints(0,0,0,370000,0),
+ make_ins("w", 42,1024),
+ Dexter.move_all_joints(0,0,0,-370000,0),
+ make_ins("w", 42,0),
+ Dexter.move_all_joints(0,0,0,0,680000),
+ make_ins("w", 42,2048),
+ Dexter.move_all_joints(0,0,0,0,-680000),
+ make_ins("w", 42,0),
+ Dexter.move_all_joints(0,0,0,0,0),
+ make_ins("S", "MaxSpeed", 240000),
+ Dexter.move_all_joints(100000,100000,100000,100000,100000),
+ Dexter.move_all_joints(0,0,0,0,0),
+ make_ins("S", "J1BoundryHigh",648000),
+ make_ins("S", "J1BoundryLow",-648000),
+ make_ins("S", "J2BoundryLow",-300000),
+ make_ins("S", "J2BoundryHigh",300000),
+ make_ins("S", "J3BoundryLow",-530000),
+ make_ins("S", "J3BoundryHigh",530000),
+ make_ins("S", "J4BoundryLow",-340000),
+ make_ins("S", "J4BoundryHigh",340000),
+ make_ins("S", "J5BoundryLow",-648000),
+ make_ins("S", "J5BoundryHigh",648000),
+ make_ins("w", 42,12448)
+ ]})
+}
+
+// Job.calibration_job.start()
diff --git a/codemirror/addon/comment/comment.js b/codemirror/addon/comment/comment.js
new file mode 100644
index 00000000..3aa46808
--- /dev/null
+++ b/codemirror/addon/comment/comment.js
@@ -0,0 +1,196 @@
+// 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";
+
+ var noOptions = {};
+ var nonWS = /[^\s\u00a0]/;
+ var Pos = CodeMirror.Pos;
+
+ function firstNonWS(str) {
+ var found = str.search(nonWS);
+ return found == -1 ? 0 : found;
+ }
+
+ CodeMirror.commands.toggleComment = function(cm) {
+ cm.toggleComment();
+ };
+
+ CodeMirror.defineExtension("toggleComment", function(options) {
+ if (!options) options = noOptions;
+ var cm = this;
+ var minLine = Infinity, ranges = this.listSelections(), mode = null;
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var from = ranges[i].from(), to = ranges[i].to();
+ if (from.line >= minLine) continue;
+ if (to.line >= minLine) to = Pos(minLine, 0);
+ minLine = from.line;
+ if (mode == null) {
+ if (cm.uncomment(from, to, options)) mode = "un";
+ else { cm.lineComment(from, to, options); mode = "line"; }
+ } else if (mode == "un") {
+ cm.uncomment(from, to, options);
+ } else {
+ cm.lineComment(from, to, options);
+ }
+ }
+ });
+
+ CodeMirror.defineExtension("lineComment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = self.getModeAt(from);
+ var commentString = options.lineComment || mode.lineComment;
+ if (!commentString) {
+ if (options.blockCommentStart || mode.blockCommentStart) {
+ options.fullLines = true;
+ self.blockComment(from, to, options);
+ }
+ return;
+ }
+ var firstLine = self.getLine(from.line);
+ if (firstLine == null) return;
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
+ var pad = options.padding == null ? " " : options.padding;
+ var blankLines = options.commentBlankLines || from.line == to.line;
+
+ self.operation(function() {
+ if (options.indent) {
+ var baseString = null;
+ for (var i = from.line; i < end; ++i) {
+ var line = self.getLine(i);
+ var whitespace = line.slice(0, firstNonWS(line));
+ if (baseString == null || baseString.length > whitespace.length) {
+ baseString = whitespace;
+ }
+ }
+ for (var i = from.line; i < end; ++i) {
+ var line = self.getLine(i), cut = baseString.length;
+ if (!blankLines && !nonWS.test(line)) continue;
+ if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
+ self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
+ }
+ } else {
+ for (var i = from.line; i < end; ++i) {
+ if (blankLines || nonWS.test(self.getLine(i)))
+ self.replaceRange(commentString + pad, Pos(i, 0));
+ }
+ }
+ });
+ });
+
+ CodeMirror.defineExtension("blockComment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = self.getModeAt(from);
+ var startString = options.blockCommentStart || mode.blockCommentStart;
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
+ if (!startString || !endString) {
+ if ((options.lineComment || mode.lineComment) && options.fullLines != false)
+ self.lineComment(from, to, options);
+ return;
+ }
+
+ var end = Math.min(to.line, self.lastLine());
+ if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
+
+ var pad = options.padding == null ? " " : options.padding;
+ if (from.line > end) return;
+
+ self.operation(function() {
+ if (options.fullLines != false) {
+ var lastLineHasText = nonWS.test(self.getLine(end));
+ self.replaceRange(pad + endString, Pos(end));
+ self.replaceRange(startString + pad, Pos(from.line, 0));
+ var lead = options.blockCommentLead || mode.blockCommentLead;
+ if (lead != null) for (var i = from.line + 1; i <= end; ++i)
+ if (i != end || lastLineHasText)
+ self.replaceRange(lead + pad, Pos(i, 0));
+ } else {
+ self.replaceRange(endString, to);
+ self.replaceRange(startString, from);
+ }
+ });
+ });
+
+ CodeMirror.defineExtension("uncomment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = self.getModeAt(from);
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
+
+ // Try finding line comments
+ var lineString = options.lineComment || mode.lineComment, lines = [];
+ var pad = options.padding == null ? " " : options.padding, didSomething;
+ lineComment: {
+ if (!lineString) break lineComment;
+ for (var i = start; i <= end; ++i) {
+ var line = self.getLine(i);
+ var found = line.indexOf(lineString);
+ if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
+ if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
+ if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
+ lines.push(line);
+ }
+ self.operation(function() {
+ for (var i = start; i <= end; ++i) {
+ var line = lines[i - start];
+ var pos = line.indexOf(lineString), endPos = pos + lineString.length;
+ if (pos < 0) continue;
+ if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
+ didSomething = true;
+ self.replaceRange("", Pos(i, pos), Pos(i, endPos));
+ }
+ });
+ if (didSomething) return true;
+ }
+
+ // Try block comments
+ var startString = options.blockCommentStart || mode.blockCommentStart;
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
+ if (!startString || !endString) return false;
+ var lead = options.blockCommentLead || mode.blockCommentLead;
+ var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
+ var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
+ if (close == -1 && start != end) {
+ endLine = self.getLine(--end);
+ close = endLine.lastIndexOf(endString);
+ }
+ if (open == -1 || close == -1 ||
+ !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
+ !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
+ return false;
+
+ // Avoid killing block comments completely outside the selection.
+ // Positions of the last startString before the start of the selection, and the first endString after it.
+ var lastStart = startLine.lastIndexOf(startString, from.ch);
+ var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
+ if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
+ // Positions of the first endString after the end of the selection, and the last startString before it.
+ firstEnd = endLine.indexOf(endString, to.ch);
+ var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
+ lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
+ if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;
+
+ self.operation(function() {
+ self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
+ Pos(end, close + endString.length));
+ var openEnd = open + startString.length;
+ if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
+ self.replaceRange("", Pos(start, open), Pos(start, openEnd));
+ if (lead) for (var i = start + 1; i <= end; ++i) {
+ var line = self.getLine(i), found = line.indexOf(lead);
+ if (found == -1 || nonWS.test(line.slice(0, found))) continue;
+ var foundEnd = found + lead.length;
+ if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
+ self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
+ }
+ });
+ return true;
+ });
+});
diff --git a/codemirror/addon/comment/continuecomment.js b/codemirror/addon/comment/continuecomment.js
new file mode 100644
index 00000000..b11d51e6
--- /dev/null
+++ b/codemirror/addon/comment/continuecomment.js
@@ -0,0 +1,85 @@
+// 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) {
+ var modes = ["clike", "css", "javascript"];
+
+ for (var i = 0; i < modes.length; ++i)
+ CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});
+
+ function continueComment(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), mode, inserts = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].head, token = cm.getTokenAt(pos);
+ if (token.type != "comment") return CodeMirror.Pass;
+ var modeHere = CodeMirror.innerMode(cm.getMode(), token.state).mode;
+ if (!mode) mode = modeHere;
+ else if (mode != modeHere) return CodeMirror.Pass;
+
+ var insert = null;
+ if (mode.blockCommentStart && mode.blockCommentContinue) {
+ var end = token.string.indexOf(mode.blockCommentEnd);
+ var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
+ if (end != -1 && end == token.string.length - mode.blockCommentEnd.length && pos.ch >= end) {
+ // Comment ended, don't continue it
+ } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
+ insert = full.slice(0, token.start);
+ if (!/^\s*$/.test(insert)) {
+ insert = "";
+ for (var j = 0; j < token.start; ++j) insert += " ";
+ }
+ } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
+ found + mode.blockCommentContinue.length > token.start &&
+ /^\s*$/.test(full.slice(0, found))) {
+ insert = full.slice(0, found);
+ }
+ if (insert != null) insert += mode.blockCommentContinue;
+ }
+ if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) {
+ var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
+ if (found > -1) {
+ insert = line.slice(0, found);
+ if (/\S/.test(insert)) insert = null;
+ else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
+ }
+ }
+ if (insert == null) return CodeMirror.Pass;
+ inserts[i] = "\n" + insert;
+ }
+
+ cm.operation(function() {
+ for (var i = ranges.length - 1; i >= 0; i--)
+ cm.replaceRange(inserts[i], ranges[i].from(), ranges[i].to(), "+insert");
+ });
+ }
+
+ function continueLineCommentEnabled(cm) {
+ var opt = cm.getOption("continueComments");
+ if (opt && typeof opt == "object")
+ return opt.continueLineComment !== false;
+ return true;
+ }
+
+ CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
+ if (prev && prev != CodeMirror.Init)
+ cm.removeKeyMap("continueComment");
+ if (val) {
+ var key = "Enter";
+ if (typeof val == "string")
+ key = val;
+ else if (typeof val == "object" && val.key)
+ key = val.key;
+ var map = {name: "continueComment"};
+ map[key] = continueComment;
+ cm.addKeyMap(map);
+ }
+ });
+});
diff --git a/codemirror/addon/dialog/dialog.css b/codemirror/addon/dialog/dialog.css
new file mode 100644
index 00000000..677c0783
--- /dev/null
+++ b/codemirror/addon/dialog/dialog.css
@@ -0,0 +1,32 @@
+.CodeMirror-dialog {
+ position: absolute;
+ left: 0; right: 0;
+ background: inherit;
+ z-index: 15;
+ padding: .1em .8em;
+ overflow: hidden;
+ color: inherit;
+}
+
+.CodeMirror-dialog-top {
+ border-bottom: 1px solid #eee;
+ top: 0;
+}
+
+.CodeMirror-dialog-bottom {
+ border-top: 1px solid #eee;
+ bottom: 0;
+}
+
+.CodeMirror-dialog input {
+ border: none;
+ outline: none;
+ background: transparent;
+ width: 20em;
+ color: inherit;
+ font-family: monospace;
+}
+
+.CodeMirror-dialog button {
+ font-size: 70%;
+}
diff --git a/codemirror/addon/dialog/dialog.js b/codemirror/addon/dialog/dialog.js
new file mode 100644
index 00000000..323b2007
--- /dev/null
+++ b/codemirror/addon/dialog/dialog.js
@@ -0,0 +1,157 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Open simple dialogs on top of an editor. Relies on dialog.css.
+
+(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) {
+ function dialogDiv(cm, template, bottom) {
+ var wrap = cm.getWrapperElement();
+ var dialog;
+ dialog = wrap.appendChild(document.createElement("div"));
+ if (bottom)
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
+ else
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
+
+ if (typeof template == "string") {
+ dialog.innerHTML = template;
+ } else { // Assuming it's a detached DOM element.
+ dialog.appendChild(template);
+ }
+ return dialog;
+ }
+
+ function closeNotification(cm, newVal) {
+ if (cm.state.currentNotificationClose)
+ cm.state.currentNotificationClose();
+ cm.state.currentNotificationClose = newVal;
+ }
+
+ CodeMirror.defineExtension("openDialog", function(template, callback, options) {
+ if (!options) options = {};
+
+ closeNotification(this, null);
+
+ var dialog = dialogDiv(this, template, options.bottom);
+ var closed = false, me = this;
+ function close(newVal) {
+ if (typeof newVal == 'string') {
+ inp.value = newVal;
+ } else {
+ if (closed) return;
+ closed = true;
+ dialog.parentNode.removeChild(dialog);
+ me.focus();
+
+ if (options.onClose) options.onClose(dialog);
+ }
+ }
+
+ var inp = dialog.getElementsByTagName("input")[0], button;
+ if (inp) {
+ if (options.value) {
+ inp.value = options.value;
+ if (options.selectValueOnOpen !== false) {
+ inp.select();
+ }
+ }
+
+ if (options.onInput)
+ CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
+ if (options.onKeyUp)
+ CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
+
+ CodeMirror.on(inp, "keydown", function(e) {
+ if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
+ if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
+ inp.blur();
+ CodeMirror.e_stop(e);
+ close();
+ }
+ if (e.keyCode == 13) callback(inp.value, e);
+ });
+
+ if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
+
+ inp.focus();
+ } else if (button = dialog.getElementsByTagName("button")[0]) {
+ CodeMirror.on(button, "click", function() {
+ close();
+ me.focus();
+ });
+
+ if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
+
+ button.focus();
+ }
+ return close;
+ });
+
+ CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
+ closeNotification(this, null);
+ var dialog = dialogDiv(this, template, options && options.bottom);
+ var buttons = dialog.getElementsByTagName("button");
+ var closed = false, me = this, blurring = 1;
+ function close() {
+ if (closed) return;
+ closed = true;
+ dialog.parentNode.removeChild(dialog);
+ me.focus();
+ }
+ buttons[0].focus();
+ for (var i = 0; i < buttons.length; ++i) {
+ var b = buttons[i];
+ (function(callback) {
+ CodeMirror.on(b, "click", function(e) {
+ CodeMirror.e_preventDefault(e);
+ close();
+ if (callback) callback(me);
+ });
+ })(callbacks[i]);
+ CodeMirror.on(b, "blur", function() {
+ --blurring;
+ setTimeout(function() { if (blurring <= 0) close(); }, 200);
+ });
+ CodeMirror.on(b, "focus", function() { ++blurring; });
+ }
+ });
+
+ /*
+ * openNotification
+ * Opens a notification, that can be closed with an optional timer
+ * (default 5000ms timer) and always closes on click.
+ *
+ * If a notification is opened while another is opened, it will close the
+ * currently opened one and open the new one immediately.
+ */
+ CodeMirror.defineExtension("openNotification", function(template, options) {
+ closeNotification(this, close);
+ var dialog = dialogDiv(this, template, options && options.bottom);
+ var closed = false, doneTimer;
+ var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
+
+ function close() {
+ if (closed) return;
+ closed = true;
+ clearTimeout(doneTimer);
+ dialog.parentNode.removeChild(dialog);
+ }
+
+ CodeMirror.on(dialog, 'click', function(e) {
+ CodeMirror.e_preventDefault(e);
+ close();
+ });
+
+ if (duration)
+ doneTimer = setTimeout(close, duration);
+
+ return close;
+ });
+});
diff --git a/codemirror/addon/display/autorefresh.js b/codemirror/addon/display/autorefresh.js
new file mode 100644
index 00000000..1e0e8504
--- /dev/null
+++ b/codemirror/addon/display/autorefresh.js
@@ -0,0 +1,47 @@
+// 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.defineOption("autoRefresh", false, function(cm, val) {
+ if (cm.state.autoRefresh) {
+ stopListening(cm, cm.state.autoRefresh)
+ cm.state.autoRefresh = null
+ }
+ if (val && cm.display.wrapper.offsetHeight == 0)
+ startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250})
+ })
+
+ function startListening(cm, state) {
+ function check() {
+ if (cm.display.wrapper.offsetHeight) {
+ stopListening(cm, state)
+ if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight)
+ cm.refresh()
+ } else {
+ state.timeout = setTimeout(check, state.delay)
+ }
+ }
+ state.timeout = setTimeout(check, state.delay)
+ state.hurry = function() {
+ clearTimeout(state.timeout)
+ state.timeout = setTimeout(check, 50)
+ }
+ CodeMirror.on(window, "mouseup", state.hurry)
+ CodeMirror.on(window, "keyup", state.hurry)
+ }
+
+ function stopListening(_cm, state) {
+ clearTimeout(state.timeout)
+ CodeMirror.off(window, "mouseup", state.hurry)
+ CodeMirror.off(window, "keyup", state.hurry)
+ }
+});
diff --git a/codemirror/addon/display/fullscreen.css b/codemirror/addon/display/fullscreen.css
new file mode 100644
index 00000000..437acd89
--- /dev/null
+++ b/codemirror/addon/display/fullscreen.css
@@ -0,0 +1,6 @@
+.CodeMirror-fullscreen {
+ position: fixed;
+ top: 0; left: 0; right: 0; bottom: 0;
+ height: auto;
+ z-index: 9;
+}
diff --git a/codemirror/addon/display/fullscreen.js b/codemirror/addon/display/fullscreen.js
new file mode 100644
index 00000000..cd3673b9
--- /dev/null
+++ b/codemirror/addon/display/fullscreen.js
@@ -0,0 +1,41 @@
+// 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.defineOption("fullScreen", false, function(cm, val, old) {
+ if (old == CodeMirror.Init) old = false;
+ if (!old == !val) return;
+ if (val) setFullscreen(cm);
+ else setNormal(cm);
+ });
+
+ function setFullscreen(cm) {
+ var wrap = cm.getWrapperElement();
+ cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
+ width: wrap.style.width, height: wrap.style.height};
+ wrap.style.width = "";
+ wrap.style.height = "auto";
+ wrap.className += " CodeMirror-fullscreen";
+ document.documentElement.style.overflow = "hidden";
+ cm.refresh();
+ }
+
+ function setNormal(cm) {
+ var wrap = cm.getWrapperElement();
+ wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
+ document.documentElement.style.overflow = "";
+ var info = cm.state.fullScreenRestore;
+ wrap.style.width = info.width; wrap.style.height = info.height;
+ window.scrollTo(info.scrollLeft, info.scrollTop);
+ cm.refresh();
+ }
+});
diff --git a/codemirror/addon/display/panel.js b/codemirror/addon/display/panel.js
new file mode 100644
index 00000000..ba29484d
--- /dev/null
+++ b/codemirror/addon/display/panel.js
@@ -0,0 +1,112 @@
+// 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) {
+ CodeMirror.defineExtension("addPanel", function(node, options) {
+ options = options || {};
+
+ if (!this.state.panels) initPanels(this);
+
+ var info = this.state.panels;
+ var wrapper = info.wrapper;
+ var cmWrapper = this.getWrapperElement();
+
+ if (options.after instanceof Panel && !options.after.cleared) {
+ wrapper.insertBefore(node, options.before.node.nextSibling);
+ } else if (options.before instanceof Panel && !options.before.cleared) {
+ wrapper.insertBefore(node, options.before.node);
+ } else if (options.replace instanceof Panel && !options.replace.cleared) {
+ wrapper.insertBefore(node, options.replace.node);
+ options.replace.clear();
+ } else if (options.position == "bottom") {
+ wrapper.appendChild(node);
+ } else if (options.position == "before-bottom") {
+ wrapper.insertBefore(node, cmWrapper.nextSibling);
+ } else if (options.position == "after-top") {
+ wrapper.insertBefore(node, cmWrapper);
+ } else {
+ wrapper.insertBefore(node, wrapper.firstChild);
+ }
+
+ var height = (options && options.height) || node.offsetHeight;
+ this._setSize(null, info.heightLeft -= height);
+ info.panels++;
+ return new Panel(this, node, options, height);
+ });
+
+ function Panel(cm, node, options, height) {
+ this.cm = cm;
+ this.node = node;
+ this.options = options;
+ this.height = height;
+ this.cleared = false;
+ }
+
+ Panel.prototype.clear = function() {
+ if (this.cleared) return;
+ this.cleared = true;
+ var info = this.cm.state.panels;
+ this.cm._setSize(null, info.heightLeft += this.height);
+ info.wrapper.removeChild(this.node);
+ if (--info.panels == 0) removePanels(this.cm);
+ };
+
+ Panel.prototype.changed = function(height) {
+ var newHeight = height == null ? this.node.offsetHeight : height;
+ var info = this.cm.state.panels;
+ this.cm._setSize(null, info.height += (newHeight - this.height));
+ this.height = newHeight;
+ };
+
+ function initPanels(cm) {
+ var wrap = cm.getWrapperElement();
+ var style = window.getComputedStyle ? window.getComputedStyle(wrap) : wrap.currentStyle;
+ var height = parseInt(style.height);
+ var info = cm.state.panels = {
+ setHeight: wrap.style.height,
+ heightLeft: height,
+ panels: 0,
+ wrapper: document.createElement("div")
+ };
+ wrap.parentNode.insertBefore(info.wrapper, wrap);
+ var hasFocus = cm.hasFocus();
+ info.wrapper.appendChild(wrap);
+ if (hasFocus) cm.focus();
+
+ cm._setSize = cm.setSize;
+ if (height != null) cm.setSize = function(width, newHeight) {
+ if (newHeight == null) return this._setSize(width, newHeight);
+ info.setHeight = newHeight;
+ if (typeof newHeight != "number") {
+ var px = /^(\d+\.?\d*)px$/.exec(newHeight);
+ if (px) {
+ newHeight = Number(px[1]);
+ } else {
+ info.wrapper.style.height = newHeight;
+ newHeight = info.wrapper.offsetHeight;
+ info.wrapper.style.height = "";
+ }
+ }
+ cm._setSize(width, info.heightLeft += (newHeight - height));
+ height = newHeight;
+ };
+ }
+
+ function removePanels(cm) {
+ var info = cm.state.panels;
+ cm.state.panels = null;
+
+ var wrap = cm.getWrapperElement();
+ info.wrapper.parentNode.replaceChild(wrap, info.wrapper);
+ wrap.style.height = info.setHeight;
+ cm.setSize = cm._setSize;
+ cm.setSize();
+ }
+});
diff --git a/codemirror/addon/display/placeholder.js b/codemirror/addon/display/placeholder.js
new file mode 100644
index 00000000..babddfb1
--- /dev/null
+++ b/codemirror/addon/display/placeholder.js
@@ -0,0 +1,60 @@
+// 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) {
+ CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.on("blur", onBlur);
+ cm.on("change", onChange);
+ onChange(cm);
+ } else if (!val && prev) {
+ cm.off("blur", onBlur);
+ cm.off("change", onChange);
+ clearPlaceholder(cm);
+ var wrapper = cm.getWrapperElement();
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
+ }
+
+ if (val && !cm.hasFocus()) onBlur(cm);
+ });
+
+ function clearPlaceholder(cm) {
+ if (cm.state.placeholder) {
+ cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
+ cm.state.placeholder = null;
+ }
+ }
+ function setPlaceholder(cm) {
+ clearPlaceholder(cm);
+ var elt = cm.state.placeholder = document.createElement("pre");
+ elt.style.cssText = "height: 0; overflow: visible";
+ elt.className = "CodeMirror-placeholder";
+ var placeHolder = cm.getOption("placeholder")
+ if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
+ elt.appendChild(placeHolder)
+ cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
+ }
+
+ function onBlur(cm) {
+ if (isEmpty(cm)) setPlaceholder(cm);
+ }
+ function onChange(cm) {
+ var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
+
+ if (empty) setPlaceholder(cm);
+ else clearPlaceholder(cm);
+ }
+
+ function isEmpty(cm) {
+ return (cm.lineCount() === 1) && (cm.getLine(0) === "");
+ }
+});
diff --git a/codemirror/addon/display/rulers.js b/codemirror/addon/display/rulers.js
new file mode 100644
index 00000000..01f65667
--- /dev/null
+++ b/codemirror/addon/display/rulers.js
@@ -0,0 +1,63 @@
+// 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.defineOption("rulers", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ clearRulers(cm);
+ cm.off("refresh", refreshRulers);
+ }
+ if (val && val.length) {
+ setRulers(cm);
+ cm.on("refresh", refreshRulers);
+ }
+ });
+
+ function clearRulers(cm) {
+ for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
+ var node = cm.display.lineSpace.childNodes[i];
+ if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
+ node.parentNode.removeChild(node);
+ }
+ }
+
+ function setRulers(cm) {
+ var val = cm.getOption("rulers");
+ var cw = cm.defaultCharWidth();
+ var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
+ var minH = cm.display.scroller.offsetHeight + 30;
+ for (var i = 0; i < val.length; i++) {
+ var elt = document.createElement("div");
+ elt.className = "CodeMirror-ruler";
+ var col, conf = val[i];
+ if (typeof conf == "number") {
+ col = conf;
+ } else {
+ col = conf.column;
+ if (conf.className) elt.className += " " + conf.className;
+ if (conf.color) elt.style.borderColor = conf.color;
+ if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;
+ if (conf.width) elt.style.borderLeftWidth = conf.width;
+ }
+ elt.style.left = (left + col * cw) + "px";
+ elt.style.top = "-50px";
+ elt.style.bottom = "-20px";
+ elt.style.minHeight = minH + "px";
+ cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
+ }
+ }
+
+ function refreshRulers(cm) {
+ clearRulers(cm);
+ setRulers(cm);
+ }
+});
diff --git a/codemirror/addon/edit/closebrackets.js b/codemirror/addon/edit/closebrackets.js
new file mode 100644
index 00000000..f3006976
--- /dev/null
+++ b/codemirror/addon/edit/closebrackets.js
@@ -0,0 +1,195 @@
+// 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) {
+ var defaults = {
+ pairs: "()[]{}''\"\"",
+ triples: "",
+ explode: "[]{}"
+ };
+
+ var Pos = CodeMirror.Pos;
+
+ CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.removeKeyMap(keyMap);
+ cm.state.closeBrackets = null;
+ }
+ if (val) {
+ cm.state.closeBrackets = val;
+ cm.addKeyMap(keyMap);
+ }
+ });
+
+ function getOption(conf, name) {
+ if (name == "pairs" && typeof conf == "string") return conf;
+ if (typeof conf == "object" && conf[name] != null) return conf[name];
+ return defaults[name];
+ }
+
+ var bind = defaults.pairs + "`";
+ var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
+ for (var i = 0; i < bind.length; i++)
+ keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));
+
+ function handler(ch) {
+ return function(cm) { return handleChar(cm, ch); };
+ }
+
+ function getConfig(cm) {
+ var deflt = cm.state.closeBrackets;
+ if (!deflt) return null;
+ var mode = cm.getModeAt(cm.getCursor());
+ return mode.closeBrackets || deflt;
+ }
+
+ function handleBackspace(cm) {
+ var conf = getConfig(cm);
+ if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var pairs = getOption(conf, "pairs");
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var around = charsAround(cm, ranges[i].head);
+ if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
+ }
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var cur = ranges[i].head;
+ cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
+ }
+ }
+
+ function handleEnter(cm) {
+ var conf = getConfig(cm);
+ var explode = conf && getOption(conf, "explode");
+ if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var around = charsAround(cm, ranges[i].head);
+ if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
+ }
+ cm.operation(function() {
+ cm.replaceSelection("\n\n", null);
+ cm.execCommand("goCharLeft");
+ ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ var line = ranges[i].head.line;
+ cm.indentLine(line, null, true);
+ cm.indentLine(line + 1, null, true);
+ }
+ });
+ }
+
+ function contractSelection(sel) {
+ var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
+ return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
+ head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
+ }
+
+ function handleChar(cm, ch) {
+ var conf = getConfig(cm);
+ if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var pairs = getOption(conf, "pairs");
+ var pos = pairs.indexOf(ch);
+ if (pos == -1) return CodeMirror.Pass;
+ var triples = getOption(conf, "triples");
+
+ var identical = pairs.charAt(pos + 1) == ch;
+ var ranges = cm.listSelections();
+ var opening = pos % 2 == 0;
+
+ var type, next;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i], cur = range.head, curType;
+ var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
+ if (opening && !range.empty()) {
+ curType = "surround";
+ } else if ((identical || !opening) && next == ch) {
+ if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
+ curType = "skipThree";
+ else
+ curType = "skip";
+ } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
+ cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
+ (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
+ curType = "addFour";
+ } else if (identical) {
+ if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both";
+ else return CodeMirror.Pass;
+ } else if (opening && (cm.getLine(cur.line).length == cur.ch ||
+ isClosingBracket(next, pairs) ||
+ /\s/.test(next))) {
+ curType = "both";
+ } else {
+ return CodeMirror.Pass;
+ }
+ if (!type) type = curType;
+ else if (type != curType) return CodeMirror.Pass;
+ }
+
+ var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
+ var right = pos % 2 ? ch : pairs.charAt(pos + 1);
+ cm.operation(function() {
+ if (type == "skip") {
+ cm.execCommand("goCharRight");
+ } else if (type == "skipThree") {
+ for (var i = 0; i < 3; i++)
+ cm.execCommand("goCharRight");
+ } else if (type == "surround") {
+ var sels = cm.getSelections();
+ for (var i = 0; i < sels.length; i++)
+ sels[i] = left + sels[i] + right;
+ cm.replaceSelections(sels, "around");
+ sels = cm.listSelections().slice();
+ for (var i = 0; i < sels.length; i++)
+ sels[i] = contractSelection(sels[i]);
+ cm.setSelections(sels);
+ } else if (type == "both") {
+ cm.replaceSelection(left + right, null);
+ cm.triggerElectric(left + right);
+ cm.execCommand("goCharLeft");
+ } else if (type == "addFour") {
+ cm.replaceSelection(left + left + left + left, "before");
+ cm.execCommand("goCharRight");
+ }
+ });
+ }
+
+ function isClosingBracket(ch, pairs) {
+ var pos = pairs.lastIndexOf(ch);
+ return pos > -1 && pos % 2 == 1;
+ }
+
+ function charsAround(cm, pos) {
+ var str = cm.getRange(Pos(pos.line, pos.ch - 1),
+ Pos(pos.line, pos.ch + 1));
+ return str.length == 2 ? str : null;
+ }
+
+ // Project the token type that will exists after the given char is
+ // typed, and use it to determine whether it would cause the start
+ // of a string token.
+ function enteringString(cm, pos, ch) {
+ var line = cm.getLine(pos.line);
+ var token = cm.getTokenAt(pos);
+ if (/\bstring2?\b/.test(token.type)) return false;
+ var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
+ stream.pos = stream.start = token.start;
+ for (;;) {
+ var type1 = cm.getMode().token(stream, token.state);
+ if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
+ stream.start = stream.pos;
+ }
+ }
+});
diff --git a/codemirror/addon/edit/closetag.js b/codemirror/addon/edit/closetag.js
new file mode 100644
index 00000000..a518da3e
--- /dev/null
+++ b/codemirror/addon/edit/closetag.js
@@ -0,0 +1,169 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+/**
+ * Tag-closer extension for CodeMirror.
+ *
+ * This extension adds an "autoCloseTags" option that can be set to
+ * either true to get the default behavior, or an object to further
+ * configure its behavior.
+ *
+ * These are supported options:
+ *
+ * `whenClosing` (default true)
+ * Whether to autoclose when the '/' of a closing tag is typed.
+ * `whenOpening` (default true)
+ * Whether to autoclose the tag when the final '>' of an opening
+ * tag is typed.
+ * `dontCloseTags` (default is empty tags for HTML, none for XML)
+ * An array of tag names that should not be autoclosed.
+ * `indentTags` (default is block tags for HTML, none for XML)
+ * An array of tag names that should, when opened, cause a
+ * blank line to be added inside the tag, and the blank line and
+ * closing line to be indented.
+ *
+ * See demos/closetag.html for a usage example.
+ */
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"), require("../fold/xml-fold"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../fold/xml-fold"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
+ if (old != CodeMirror.Init && old)
+ cm.removeKeyMap("autoCloseTags");
+ if (!val) return;
+ var map = {name: "autoCloseTags"};
+ if (typeof val != "object" || val.whenClosing)
+ map["'/'"] = function(cm) { return autoCloseSlash(cm); };
+ if (typeof val != "object" || val.whenOpening)
+ map["'>'"] = function(cm) { return autoCloseGT(cm); };
+ cm.addKeyMap(map);
+ });
+
+ var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
+ "source", "track", "wbr"];
+ var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
+ "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
+
+ function autoCloseGT(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), replacements = [];
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var pos = ranges[i].head, tok = cm.getTokenAt(pos);
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
+ if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass;
+
+ var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html";
+ var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
+ var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
+
+ var tagName = state.tagName;
+ if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
+ var lowerTagName = tagName.toLowerCase();
+ // Don't process the '>' at the end of an end-tag or self-closing tag
+ if (!tagName ||
+ tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
+ tok.type == "tag" && state.type == "closeTag" ||
+ tok.string.indexOf("/") == (tok.string.length - 1) || // match something like
+ dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
+ closingTagExists(cm, tagName, pos, state, true))
+ return CodeMirror.Pass;
+
+ var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;
+ replacements[i] = {indent: indent,
+ text: ">" + (indent ? "\n\n" : "") + "" + tagName + ">",
+ newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
+ }
+
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var info = replacements[i];
+ cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
+ var sel = cm.listSelections().slice(0);
+ sel[i] = {head: info.newPos, anchor: info.newPos};
+ cm.setSelections(sel);
+ if (info.indent) {
+ cm.indentLine(info.newPos.line, null, true);
+ cm.indentLine(info.newPos.line + 1, null, true);
+ }
+ }
+ }
+
+ function autoCloseCurrent(cm, typingSlash) {
+ var ranges = cm.listSelections(), replacements = [];
+ var head = typingSlash ? "/" : "";
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var pos = ranges[i].head, tok = cm.getTokenAt(pos);
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
+ if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" ||
+ tok.start != pos.ch - 1))
+ return CodeMirror.Pass;
+ // Kludge to get around the fact that we are not in XML mode
+ // when completing in JS/CSS snippet in htmlmixed mode. Does not
+ // work for other XML embedded languages (there is no general
+ // way to go from a mixed mode to its current XML state).
+ var replacement;
+ if (inner.mode.name != "xml") {
+ if (cm.getMode().name == "htmlmixed" && inner.mode.name == "javascript")
+ replacement = head + "script";
+ else if (cm.getMode().name == "htmlmixed" && inner.mode.name == "css")
+ replacement = head + "style";
+ else
+ return CodeMirror.Pass;
+ } else {
+ if (!state.context || !state.context.tagName ||
+ closingTagExists(cm, state.context.tagName, pos, state))
+ return CodeMirror.Pass;
+ replacement = head + state.context.tagName;
+ }
+ if (cm.getLine(pos.line).charAt(tok.end) != ">") replacement += ">";
+ replacements[i] = replacement;
+ }
+ cm.replaceSelections(replacements);
+ ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++)
+ if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
+ cm.indentLine(ranges[i].head.line);
+ }
+
+ function autoCloseSlash(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ return autoCloseCurrent(cm, true);
+ }
+
+ CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };
+
+ function indexOf(collection, elt) {
+ if (collection.indexOf) return collection.indexOf(elt);
+ for (var i = 0, e = collection.length; i < e; ++i)
+ if (collection[i] == elt) return i;
+ return -1;
+ }
+
+ // If xml-fold is loaded, we use its functionality to try and verify
+ // whether a given tag is actually unclosed.
+ function closingTagExists(cm, tagName, pos, state, newTag) {
+ if (!CodeMirror.scanForClosingTag) return false;
+ var end = Math.min(cm.lastLine() + 1, pos.line + 500);
+ var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
+ if (!nextClose || nextClose.tag != tagName) return false;
+ var cx = state.context;
+ // If the immediate wrapping context contains onCx instances of
+ // the same tag, a closing tag only exists if there are at least
+ // that many closing tags of that type following.
+ for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx;
+ pos = nextClose.to;
+ for (var i = 1; i < onCx; i++) {
+ var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
+ if (!next || next.tag != tagName) return false;
+ pos = next.to;
+ }
+ return true;
+ }
+});
diff --git a/codemirror/addon/edit/continuelist.js b/codemirror/addon/edit/continuelist.js
new file mode 100644
index 00000000..df5179fe
--- /dev/null
+++ b/codemirror/addon/edit/continuelist.js
@@ -0,0 +1,51 @@
+// 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";
+
+ var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
+ emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
+ unorderedListRE = /[*+-]\s/;
+
+ CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), replacements = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].head;
+ var eolState = cm.getStateAfter(pos.line);
+ var inList = eolState.list !== false;
+ var inQuote = eolState.quote !== 0;
+
+ var line = cm.getLine(pos.line), match = listRE.exec(line);
+ if (!ranges[i].empty() || (!inList && !inQuote) || !match) {
+ cm.execCommand("newlineAndIndent");
+ return;
+ }
+ if (emptyListRE.test(line)) {
+ cm.replaceRange("", {
+ line: pos.line, ch: 0
+ }, {
+ line: pos.line, ch: pos.ch + 1
+ });
+ replacements[i] = "\n";
+ } else {
+ var indent = match[1], after = match[5];
+ var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
+ ? match[2]
+ : (parseInt(match[3], 10) + 1) + match[4];
+
+ replacements[i] = "\n" + indent + bullet + after;
+ }
+ }
+
+ cm.replaceSelections(replacements);
+ };
+});
diff --git a/codemirror/addon/edit/matchbrackets.js b/codemirror/addon/edit/matchbrackets.js
new file mode 100644
index 00000000..70e1ae18
--- /dev/null
+++ b/codemirror/addon/edit/matchbrackets.js
@@ -0,0 +1,120 @@
+// 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) {
+ var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
+ (document.documentMode == null || document.documentMode < 8);
+
+ var Pos = CodeMirror.Pos;
+
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
+
+ function findMatchingBracket(cm, where, strict, config) {
+ var line = cm.getLineHandle(where.line), pos = where.ch - 1;
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
+ if (!match) return null;
+ var dir = match.charAt(1) == ">" ? 1 : -1;
+ if (strict && (dir > 0) != (pos == where.ch)) return null;
+ var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
+
+ var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
+ if (found == null) return null;
+ return {from: Pos(where.line, pos), to: found && found.pos,
+ match: found && found.ch == match.charAt(0), forward: dir > 0};
+ }
+
+ // bracketRegex is used to specify which type of bracket to scan
+ // should be a regexp, e.g. /[[\]]/
+ //
+ // Note: If "where" is on an open bracket, then this bracket is ignored.
+ //
+ // Returns false when no bracket was found, null when it reached
+ // maxScanLines and gave up
+ function scanForBracket(cm, where, dir, style, config) {
+ var maxScanLen = (config && config.maxScanLineLength) || 10000;
+ var maxScanLines = (config && config.maxScanLines) || 1000;
+
+ var stack = [];
+ var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
+ var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
+ : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
+ for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
+ var line = cm.getLine(lineNo);
+ if (!line) continue;
+ var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
+ if (line.length > maxScanLen) continue;
+ if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
+ for (; pos != end; pos += dir) {
+ var ch = line.charAt(pos);
+ if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
+ var match = matching[ch];
+ if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
+ else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
+ else stack.pop();
+ }
+ }
+ }
+ return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
+ }
+
+ function matchBrackets(cm, autoclear, config) {
+ // Disable brace matching in long lines, since it'll cause hugely slow updates
+ var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
+ var marks = [], ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
+ if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
+ var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
+ marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
+ if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
+ marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
+ }
+ }
+
+ if (marks.length) {
+ // Kludge to work around the IE bug from issue #1193, where text
+ // input stops going to the textare whever this fires.
+ if (ie_lt8 && cm.state.focused) cm.focus();
+
+ var clear = function() {
+ cm.operation(function() {
+ for (var i = 0; i < marks.length; i++) marks[i].clear();
+ });
+ };
+ if (autoclear) setTimeout(clear, 800);
+ else return clear;
+ }
+ }
+
+ var currentlyHighlighted = null;
+ function doMatchBrackets(cm) {
+ cm.operation(function() {
+ if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
+ currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
+ });
+ }
+
+ CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init)
+ cm.off("cursorActivity", doMatchBrackets);
+ if (val) {
+ cm.state.matchBrackets = typeof val == "object" ? val : {};
+ cm.on("cursorActivity", doMatchBrackets);
+ }
+ });
+
+ CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
+ CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
+ return findMatchingBracket(this, pos, strict, config);
+ });
+ CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
+ return scanForBracket(this, pos, dir, style, config);
+ });
+});
diff --git a/codemirror/addon/edit/matchtags.js b/codemirror/addon/edit/matchtags.js
new file mode 100644
index 00000000..fb1911a8
--- /dev/null
+++ b/codemirror/addon/edit/matchtags.js
@@ -0,0 +1,66 @@
+// 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"), require("../fold/xml-fold"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../fold/xml-fold"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.off("cursorActivity", doMatchTags);
+ cm.off("viewportChange", maybeUpdateMatch);
+ clear(cm);
+ }
+ if (val) {
+ cm.state.matchBothTags = typeof val == "object" && val.bothTags;
+ cm.on("cursorActivity", doMatchTags);
+ cm.on("viewportChange", maybeUpdateMatch);
+ doMatchTags(cm);
+ }
+ });
+
+ function clear(cm) {
+ if (cm.state.tagHit) cm.state.tagHit.clear();
+ if (cm.state.tagOther) cm.state.tagOther.clear();
+ cm.state.tagHit = cm.state.tagOther = null;
+ }
+
+ function doMatchTags(cm) {
+ cm.state.failedTagMatch = false;
+ cm.operation(function() {
+ clear(cm);
+ if (cm.somethingSelected()) return;
+ var cur = cm.getCursor(), range = cm.getViewport();
+ range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
+ var match = CodeMirror.findMatchingTag(cm, cur, range);
+ if (!match) return;
+ if (cm.state.matchBothTags) {
+ var hit = match.at == "open" ? match.open : match.close;
+ if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
+ }
+ var other = match.at == "close" ? match.open : match.close;
+ if (other)
+ cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
+ else
+ cm.state.failedTagMatch = true;
+ });
+ }
+
+ function maybeUpdateMatch(cm) {
+ if (cm.state.failedTagMatch) doMatchTags(cm);
+ }
+
+ CodeMirror.commands.toMatchingTag = function(cm) {
+ var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
+ if (found) {
+ var other = found.at == "close" ? found.open : found.close;
+ if (other) cm.extendSelection(other.to, other.from);
+ }
+ };
+});
diff --git a/codemirror/addon/edit/trailingspace.js b/codemirror/addon/edit/trailingspace.js
new file mode 100644
index 00000000..fa7b56be
--- /dev/null
+++ b/codemirror/addon/edit/trailingspace.js
@@ -0,0 +1,27 @@
+// 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) {
+ CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
+ if (prev == CodeMirror.Init) prev = false;
+ if (prev && !val)
+ cm.removeOverlay("trailingspace");
+ else if (!prev && val)
+ cm.addOverlay({
+ token: function(stream) {
+ for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
+ if (i > stream.pos) { stream.pos = i; return null; }
+ stream.pos = l;
+ return "trailingspace";
+ },
+ name: "trailingspace"
+ });
+ });
+});
diff --git a/codemirror/addon/fold/brace-fold.js b/codemirror/addon/fold/brace-fold.js
new file mode 100644
index 00000000..1605f6c2
--- /dev/null
+++ b/codemirror/addon/fold/brace-fold.js
@@ -0,0 +1,105 @@
+// 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.registerHelper("fold", "brace", function(cm, start) {
+ var line = start.line, lineText = cm.getLine(line);
+ var startCh, tokenType;
+
+ function findOpening(openCh) {
+ for (var at = start.ch, pass = 0;;) {
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
+ if (found == -1) {
+ if (pass == 1) break;
+ pass = 1;
+ at = lineText.length;
+ continue;
+ }
+ if (pass == 1 && found < start.ch) break;
+ tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
+ if (!/^(comment|string)/.test(tokenType)) return found + 1;
+ at = found - 1;
+ }
+ }
+
+ var startToken = "{", endToken = "}", startCh = findOpening("{");
+ if (startCh == null) {
+ startToken = "[", endToken = "]";
+ startCh = findOpening("[");
+ }
+
+ if (startCh == null) return;
+ var count = 1, lastLine = cm.lastLine(), end, endCh;
+ outer: for (var i = line; i <= lastLine; ++i) {
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
+ for (;;) {
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
+ if (nextOpen < 0) nextOpen = text.length;
+ if (nextClose < 0) nextClose = text.length;
+ pos = Math.min(nextOpen, nextClose);
+ if (pos == text.length) break;
+ if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
+ if (pos == nextOpen) ++count;
+ else if (!--count) { end = i; endCh = pos; break outer; }
+ }
+ ++pos;
+ }
+ }
+ if (end == null || line == end && endCh == startCh) return;
+ return {from: CodeMirror.Pos(line, startCh),
+ to: CodeMirror.Pos(end, endCh)};
+});
+
+CodeMirror.registerHelper("fold", "import", function(cm, start) {
+ function hasImport(line) {
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+ if (start.type != "keyword" || start.string != "import") return null;
+ // Now find closing semicolon, return its position
+ for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
+ var text = cm.getLine(i), semi = text.indexOf(";");
+ if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
+ }
+ }
+
+ var start = start.line, has = hasImport(start), prev;
+ if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
+ return null;
+ for (var end = has.end;;) {
+ var next = hasImport(end.line + 1);
+ if (next == null) break;
+ end = next.end;
+ }
+ return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
+});
+
+CodeMirror.registerHelper("fold", "include", function(cm, start) {
+ function hasInclude(line) {
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+ if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
+ }
+
+ var start = start.line, has = hasInclude(start);
+ if (has == null || hasInclude(start - 1) != null) return null;
+ for (var end = start;;) {
+ var next = hasInclude(end + 1);
+ if (next == null) break;
+ ++end;
+ }
+ return {from: CodeMirror.Pos(start, has + 1),
+ to: cm.clipPos(CodeMirror.Pos(end))};
+});
+
+});
diff --git a/codemirror/addon/fold/comment-fold.js b/codemirror/addon/fold/comment-fold.js
new file mode 100644
index 00000000..60fa3e43
--- /dev/null
+++ b/codemirror/addon/fold/comment-fold.js
@@ -0,0 +1,59 @@
+// 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.registerGlobalHelper("fold", "comment", function(mode) {
+ return mode.blockCommentStart && mode.blockCommentEnd;
+}, function(cm, start) {
+ var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
+ if (!startToken || !endToken) return;
+ var line = start.line, lineText = cm.getLine(line);
+
+ var startCh;
+ for (var at = start.ch, pass = 0;;) {
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
+ if (found == -1) {
+ if (pass == 1) return;
+ pass = 1;
+ at = lineText.length;
+ continue;
+ }
+ if (pass == 1 && found < start.ch) return;
+ if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&
+ (lineText.slice(found - endToken.length, found) == endToken ||
+ !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {
+ startCh = found + startToken.length;
+ break;
+ }
+ at = found - 1;
+ }
+
+ var depth = 1, lastLine = cm.lastLine(), end, endCh;
+ outer: for (var i = line; i <= lastLine; ++i) {
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
+ for (;;) {
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
+ if (nextOpen < 0) nextOpen = text.length;
+ if (nextClose < 0) nextClose = text.length;
+ pos = Math.min(nextOpen, nextClose);
+ if (pos == text.length) break;
+ if (pos == nextOpen) ++depth;
+ else if (!--depth) { end = i; endCh = pos; break outer; }
+ ++pos;
+ }
+ }
+ if (end == null || line == end && endCh == startCh) return;
+ return {from: CodeMirror.Pos(line, startCh),
+ to: CodeMirror.Pos(end, endCh)};
+});
+
+});
diff --git a/codemirror/addon/fold/foldcode.js b/codemirror/addon/fold/foldcode.js
new file mode 100644
index 00000000..62911f93
--- /dev/null
+++ b/codemirror/addon/fold/foldcode.js
@@ -0,0 +1,149 @@
+// 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";
+
+ function doFold(cm, pos, options, force) {
+ if (options && options.call) {
+ var finder = options;
+ options = null;
+ } else {
+ var finder = getOption(cm, options, "rangeFinder");
+ }
+ if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
+ var minSize = getOption(cm, options, "minFoldSize");
+
+ function getRange(allowFolded) {
+ var range = finder(cm, pos);
+ if (!range || range.to.line - range.from.line < minSize) return null;
+ var marks = cm.findMarksAt(range.from);
+ for (var i = 0; i < marks.length; ++i) {
+ if (marks[i].__isFold && force !== "fold") {
+ if (!allowFolded) return null;
+ range.cleared = true;
+ marks[i].clear();
+ }
+ }
+ return range;
+ }
+
+ var range = getRange(true);
+ if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
+ pos = CodeMirror.Pos(pos.line - 1, 0);
+ range = getRange(false);
+ }
+ if (!range || range.cleared || force === "unfold") return;
+
+ var myWidget = makeWidget(cm, options);
+ CodeMirror.on(myWidget, "mousedown", function(e) {
+ myRange.clear();
+ CodeMirror.e_preventDefault(e);
+ });
+ var myRange = cm.markText(range.from, range.to, {
+ replacedWith: myWidget,
+ clearOnEnter: true,
+ __isFold: true
+ });
+ myRange.on("clear", function(from, to) {
+ CodeMirror.signal(cm, "unfold", cm, from, to);
+ });
+ CodeMirror.signal(cm, "fold", cm, range.from, range.to);
+ }
+
+ function makeWidget(cm, options) {
+ var widget = getOption(cm, options, "widget");
+ if (typeof widget == "string") {
+ var text = document.createTextNode(widget);
+ widget = document.createElement("span");
+ widget.appendChild(text);
+ widget.className = "CodeMirror-foldmarker";
+ }
+ return widget;
+ }
+
+ // Clumsy backwards-compatible interface
+ CodeMirror.newFoldFunction = function(rangeFinder, widget) {
+ return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
+ };
+
+ // New-style interface
+ CodeMirror.defineExtension("foldCode", function(pos, options, force) {
+ doFold(this, pos, options, force);
+ });
+
+ CodeMirror.defineExtension("isFolded", function(pos) {
+ var marks = this.findMarksAt(pos);
+ for (var i = 0; i < marks.length; ++i)
+ if (marks[i].__isFold) return true;
+ });
+
+ CodeMirror.commands.toggleFold = function(cm) {
+ cm.foldCode(cm.getCursor());
+ };
+ CodeMirror.commands.fold = function(cm) {
+ cm.foldCode(cm.getCursor(), null, "fold");
+ };
+ CodeMirror.commands.unfold = function(cm) {
+ cm.foldCode(cm.getCursor(), null, "unfold");
+ };
+ CodeMirror.commands.foldAll = function(cm) {
+ cm.operation(function() {
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
+ });
+ };
+ CodeMirror.commands.unfoldAll = function(cm) {
+ cm.operation(function() {
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
+ });
+ };
+
+ CodeMirror.registerHelper("fold", "combine", function() {
+ var funcs = Array.prototype.slice.call(arguments, 0);
+ return function(cm, start) {
+ for (var i = 0; i < funcs.length; ++i) {
+ var found = funcs[i](cm, start);
+ if (found) return found;
+ }
+ };
+ });
+
+ CodeMirror.registerHelper("fold", "auto", function(cm, start) {
+ var helpers = cm.getHelpers(start, "fold");
+ for (var i = 0; i < helpers.length; i++) {
+ var cur = helpers[i](cm, start);
+ if (cur) return cur;
+ }
+ });
+
+ var defaultOptions = {
+ rangeFinder: CodeMirror.fold.auto,
+ widget: "\u2194",
+ minFoldSize: 0,
+ scanUp: false
+ };
+
+ CodeMirror.defineOption("foldOptions", null);
+
+ function getOption(cm, options, name) {
+ if (options && options[name] !== undefined)
+ return options[name];
+ var editorOptions = cm.options.foldOptions;
+ if (editorOptions && editorOptions[name] !== undefined)
+ return editorOptions[name];
+ return defaultOptions[name];
+ }
+
+ CodeMirror.defineExtension("foldOption", function(options, name) {
+ return getOption(this, options, name);
+ });
+});
diff --git a/codemirror/addon/fold/foldgutter.css b/codemirror/addon/fold/foldgutter.css
new file mode 100644
index 00000000..ad19ae2d
--- /dev/null
+++ b/codemirror/addon/fold/foldgutter.css
@@ -0,0 +1,20 @@
+.CodeMirror-foldmarker {
+ color: blue;
+ text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
+ font-family: arial;
+ line-height: .3;
+ cursor: pointer;
+}
+.CodeMirror-foldgutter {
+ width: .7em;
+}
+.CodeMirror-foldgutter-open,
+.CodeMirror-foldgutter-folded {
+ cursor: pointer;
+}
+.CodeMirror-foldgutter-open:after {
+ content: "\25BE";
+}
+.CodeMirror-foldgutter-folded:after {
+ content: "\25B8";
+}
diff --git a/codemirror/addon/fold/foldgutter.js b/codemirror/addon/fold/foldgutter.js
new file mode 100644
index 00000000..ed7bd87d
--- /dev/null
+++ b/codemirror/addon/fold/foldgutter.js
@@ -0,0 +1,146 @@
+// 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"), require("./foldcode"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./foldcode"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.clearGutter(cm.state.foldGutter.options.gutter);
+ cm.state.foldGutter = null;
+ cm.off("gutterClick", onGutterClick);
+ cm.off("change", onChange);
+ cm.off("viewportChange", onViewportChange);
+ cm.off("fold", onFold);
+ cm.off("unfold", onFold);
+ cm.off("swapDoc", updateInViewport);
+ }
+ if (val) {
+ cm.state.foldGutter = new State(parseOptions(val));
+ updateInViewport(cm);
+ cm.on("gutterClick", onGutterClick);
+ cm.on("change", onChange);
+ cm.on("viewportChange", onViewportChange);
+ cm.on("fold", onFold);
+ cm.on("unfold", onFold);
+ cm.on("swapDoc", updateInViewport);
+ }
+ });
+
+ var Pos = CodeMirror.Pos;
+
+ function State(options) {
+ this.options = options;
+ this.from = this.to = 0;
+ }
+
+ function parseOptions(opts) {
+ if (opts === true) opts = {};
+ if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
+ if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
+ if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
+ return opts;
+ }
+
+ function isFolded(cm, line) {
+ var marks = cm.findMarksAt(Pos(line));
+ for (var i = 0; i < marks.length; ++i)
+ if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
+ }
+
+ function marker(spec) {
+ if (typeof spec == "string") {
+ var elt = document.createElement("div");
+ elt.className = spec + " CodeMirror-guttermarker-subtle";
+ return elt;
+ } else {
+ return spec.cloneNode(true);
+ }
+ }
+
+ function updateFoldInfo(cm, from, to) {
+ var opts = cm.state.foldGutter.options, cur = from;
+ var minSize = cm.foldOption(opts, "minFoldSize");
+ var func = cm.foldOption(opts, "rangeFinder");
+ cm.eachLine(from, to, function(line) {
+ var mark = null;
+ if (isFolded(cm, cur)) {
+ mark = marker(opts.indicatorFolded);
+ } else {
+ var pos = Pos(cur, 0);
+ var range = func && func(cm, pos);
+ if (range && range.to.line - range.from.line >= minSize)
+ mark = marker(opts.indicatorOpen);
+ }
+ cm.setGutterMarker(line, opts.gutter, mark);
+ ++cur;
+ });
+ }
+
+ function updateInViewport(cm) {
+ var vp = cm.getViewport(), state = cm.state.foldGutter;
+ if (!state) return;
+ cm.operation(function() {
+ updateFoldInfo(cm, vp.from, vp.to);
+ });
+ state.from = vp.from; state.to = vp.to;
+ }
+
+ function onGutterClick(cm, line, gutter) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ if (gutter != opts.gutter) return;
+ var folded = isFolded(cm, line);
+ if (folded) folded.clear();
+ else cm.foldCode(Pos(line, 0), opts.rangeFinder);
+ }
+
+ function onChange(cm) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ state.from = state.to = 0;
+ clearTimeout(state.changeUpdate);
+ state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
+ }
+
+ function onViewportChange(cm) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ clearTimeout(state.changeUpdate);
+ state.changeUpdate = setTimeout(function() {
+ var vp = cm.getViewport();
+ if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
+ updateInViewport(cm);
+ } else {
+ cm.operation(function() {
+ if (vp.from < state.from) {
+ updateFoldInfo(cm, vp.from, state.from);
+ state.from = vp.from;
+ }
+ if (vp.to > state.to) {
+ updateFoldInfo(cm, state.to, vp.to);
+ state.to = vp.to;
+ }
+ });
+ }
+ }, opts.updateViewportTimeSpan || 400);
+ }
+
+ function onFold(cm, from) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var line = from.line;
+ if (line >= state.from && line < state.to)
+ updateFoldInfo(cm, line, line + 1);
+ }
+});
diff --git a/codemirror/addon/fold/indent-fold.js b/codemirror/addon/fold/indent-fold.js
new file mode 100644
index 00000000..e29f15e9
--- /dev/null
+++ b/codemirror/addon/fold/indent-fold.js
@@ -0,0 +1,44 @@
+// 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.registerHelper("fold", "indent", function(cm, start) {
+ var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
+ if (!/\S/.test(firstLine)) return;
+ var getIndent = function(line) {
+ return CodeMirror.countColumn(line, null, tabSize);
+ };
+ var myIndent = getIndent(firstLine);
+ var lastLineInFold = null;
+ // Go through lines until we find a line that definitely doesn't belong in
+ // the block we're folding, or to the end.
+ for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
+ var curLine = cm.getLine(i);
+ var curIndent = getIndent(curLine);
+ if (curIndent > myIndent) {
+ // Lines with a greater indent are considered part of the block.
+ lastLineInFold = i;
+ } else if (!/\S/.test(curLine)) {
+ // Empty lines might be breaks within the block we're trying to fold.
+ } else {
+ // A non-empty line at an indent equal to or less than ours marks the
+ // start of another block.
+ break;
+ }
+ }
+ if (lastLineInFold) return {
+ from: CodeMirror.Pos(start.line, firstLine.length),
+ to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
+ };
+});
+
+});
diff --git a/codemirror/addon/fold/markdown-fold.js b/codemirror/addon/fold/markdown-fold.js
new file mode 100644
index 00000000..ce84c946
--- /dev/null
+++ b/codemirror/addon/fold/markdown-fold.js
@@ -0,0 +1,49 @@
+// 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.registerHelper("fold", "markdown", function(cm, start) {
+ var maxDepth = 100;
+
+ function isHeader(lineNo) {
+ var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0));
+ return tokentype && /\bheader\b/.test(tokentype);
+ }
+
+ function headerLevel(lineNo, line, nextLine) {
+ var match = line && line.match(/^#+/);
+ if (match && isHeader(lineNo)) return match[0].length;
+ match = nextLine && nextLine.match(/^[=\-]+\s*$/);
+ if (match && isHeader(lineNo + 1)) return nextLine[0] == "=" ? 1 : 2;
+ return maxDepth;
+ }
+
+ var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1);
+ var level = headerLevel(start.line, firstLine, nextLine);
+ if (level === maxDepth) return undefined;
+
+ var lastLineNo = cm.lastLine();
+ var end = start.line, nextNextLine = cm.getLine(end + 2);
+ while (end < lastLineNo) {
+ if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break;
+ ++end;
+ nextLine = nextNextLine;
+ nextNextLine = cm.getLine(end + 2);
+ }
+
+ return {
+ from: CodeMirror.Pos(start.line, firstLine.length),
+ to: CodeMirror.Pos(end, cm.getLine(end).length)
+ };
+});
+
+});
diff --git a/codemirror/addon/fold/xml-fold.js b/codemirror/addon/fold/xml-fold.js
new file mode 100644
index 00000000..504727f3
--- /dev/null
+++ b/codemirror/addon/fold/xml-fold.js
@@ -0,0 +1,182 @@
+// 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";
+
+ var Pos = CodeMirror.Pos;
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
+
+ var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
+ var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
+ var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
+
+ function Iter(cm, line, ch, range) {
+ this.line = line; this.ch = ch;
+ this.cm = cm; this.text = cm.getLine(line);
+ this.min = range ? range.from : cm.firstLine();
+ this.max = range ? range.to - 1 : cm.lastLine();
+ }
+
+ function tagAt(iter, ch) {
+ var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
+ return type && /\btag\b/.test(type);
+ }
+
+ function nextLine(iter) {
+ if (iter.line >= iter.max) return;
+ iter.ch = 0;
+ iter.text = iter.cm.getLine(++iter.line);
+ return true;
+ }
+ function prevLine(iter) {
+ if (iter.line <= iter.min) return;
+ iter.text = iter.cm.getLine(--iter.line);
+ iter.ch = iter.text.length;
+ return true;
+ }
+
+ function toTagEnd(iter) {
+ for (;;) {
+ var gt = iter.text.indexOf(">", iter.ch);
+ if (gt == -1) { if (nextLine(iter)) continue; else return; }
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
+ var lastSlash = iter.text.lastIndexOf("/", gt);
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+ iter.ch = gt + 1;
+ return selfClose ? "selfClose" : "regular";
+ }
+ }
+ function toTagStart(iter) {
+ for (;;) {
+ var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
+ if (lt == -1) { if (prevLine(iter)) continue; else return; }
+ if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
+ xmlTagStart.lastIndex = lt;
+ iter.ch = lt;
+ var match = xmlTagStart.exec(iter.text);
+ if (match && match.index == lt) return match;
+ }
+ }
+
+ function toNextTag(iter) {
+ for (;;) {
+ xmlTagStart.lastIndex = iter.ch;
+ var found = xmlTagStart.exec(iter.text);
+ if (!found) { if (nextLine(iter)) continue; else return; }
+ if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
+ iter.ch = found.index + found[0].length;
+ return found;
+ }
+ }
+ function toPrevTag(iter) {
+ for (;;) {
+ var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
+ if (gt == -1) { if (prevLine(iter)) continue; else return; }
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
+ var lastSlash = iter.text.lastIndexOf("/", gt);
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+ iter.ch = gt + 1;
+ return selfClose ? "selfClose" : "regular";
+ }
+ }
+
+ function findMatchingClose(iter, tag) {
+ var stack = [];
+ for (;;) {
+ var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
+ if (!next || !(end = toTagEnd(iter))) return;
+ if (end == "selfClose") continue;
+ if (next[1]) { // closing tag
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
+ stack.length = i;
+ break;
+ }
+ if (i < 0 && (!tag || tag == next[2])) return {
+ tag: next[2],
+ from: Pos(startLine, startCh),
+ to: Pos(iter.line, iter.ch)
+ };
+ } else { // opening tag
+ stack.push(next[2]);
+ }
+ }
+ }
+ function findMatchingOpen(iter, tag) {
+ var stack = [];
+ for (;;) {
+ var prev = toPrevTag(iter);
+ if (!prev) return;
+ if (prev == "selfClose") { toTagStart(iter); continue; }
+ var endLine = iter.line, endCh = iter.ch;
+ var start = toTagStart(iter);
+ if (!start) return;
+ if (start[1]) { // closing tag
+ stack.push(start[2]);
+ } else { // opening tag
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
+ stack.length = i;
+ break;
+ }
+ if (i < 0 && (!tag || tag == start[2])) return {
+ tag: start[2],
+ from: Pos(iter.line, iter.ch),
+ to: Pos(endLine, endCh)
+ };
+ }
+ }
+ }
+
+ CodeMirror.registerHelper("fold", "xml", function(cm, start) {
+ var iter = new Iter(cm, start.line, 0);
+ for (;;) {
+ var openTag = toNextTag(iter), end;
+ if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
+ if (!openTag[1] && end != "selfClose") {
+ var start = Pos(iter.line, iter.ch);
+ var close = findMatchingClose(iter, openTag[2]);
+ return close && {from: start, to: close.from};
+ }
+ }
+ });
+ CodeMirror.findMatchingTag = function(cm, pos, range) {
+ var iter = new Iter(cm, pos.line, pos.ch, range);
+ if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
+ var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
+ var start = end && toTagStart(iter);
+ if (!end || !start || cmp(iter, pos) > 0) return;
+ var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
+ if (end == "selfClose") return {open: here, close: null, at: "open"};
+
+ if (start[1]) { // closing tag
+ return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
+ } else { // opening tag
+ iter = new Iter(cm, to.line, to.ch, range);
+ return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
+ }
+ };
+
+ CodeMirror.findEnclosingTag = function(cm, pos, range) {
+ var iter = new Iter(cm, pos.line, pos.ch, range);
+ for (;;) {
+ var open = findMatchingOpen(iter);
+ if (!open) break;
+ var forward = new Iter(cm, pos.line, pos.ch, range);
+ var close = findMatchingClose(forward, open.tag);
+ if (close) return {open: open, close: close};
+ }
+ };
+
+ // Used by addon/edit/closetag.js
+ CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
+ var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
+ return findMatchingClose(iter, name);
+ };
+});
diff --git a/codemirror/addon/hint/anyword-hint.js b/codemirror/addon/hint/anyword-hint.js
new file mode 100644
index 00000000..dae78e2e
--- /dev/null
+++ b/codemirror/addon/hint/anyword-hint.js
@@ -0,0 +1,41 @@
+// 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";
+
+ var WORD = /[\w$]+/, RANGE = 500;
+
+ CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
+ var word = options && options.word || WORD;
+ var range = options && options.range || RANGE;
+ var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
+ var end = cur.ch, start = end;
+ while (start && word.test(curLine.charAt(start - 1))) --start;
+ var curWord = start != end && curLine.slice(start, end);
+
+ var list = options && options.list || [], seen = {};
+ var re = new RegExp(word.source, "g");
+ for (var dir = -1; dir <= 1; dir += 2) {
+ var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
+ for (; line != endLine; line += dir) {
+ var text = editor.getLine(line), m;
+ while (m = re.exec(text)) {
+ if (line == cur.line && m[0] === curWord) continue;
+ if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
+ seen[m[0]] = true;
+ list.push(m[0]);
+ }
+ }
+ }
+ }
+ return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
+ });
+});
diff --git a/codemirror/addon/hint/css-hint.js b/codemirror/addon/hint/css-hint.js
new file mode 100644
index 00000000..22642727
--- /dev/null
+++ b/codemirror/addon/hint/css-hint.js
@@ -0,0 +1,60 @@
+// 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"), require("../../mode/css/css"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../../mode/css/css"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var pseudoClasses = {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};
+
+ CodeMirror.registerHelper("hint", "css", function(cm) {
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur);
+ var inner = CodeMirror.innerMode(cm.getMode(), token.state);
+ if (inner.mode.name != "css") return;
+
+ if (token.type == "keyword" && "!important".indexOf(token.string) == 0)
+ return {list: ["!important"], from: CodeMirror.Pos(cur.line, token.start),
+ to: CodeMirror.Pos(cur.line, token.end)};
+
+ var start = token.start, end = cur.ch, word = token.string.slice(0, end - start);
+ if (/[^\w$_-]/.test(word)) {
+ word = ""; start = end = cur.ch;
+ }
+
+ var spec = CodeMirror.resolveMode("text/css");
+
+ var result = [];
+ function add(keywords) {
+ for (var name in keywords)
+ if (!word || name.lastIndexOf(word, 0) == 0)
+ result.push(name);
+ }
+
+ var st = inner.state.state;
+ if (st == "pseudo" || token.type == "variable-3") {
+ add(pseudoClasses);
+ } else if (st == "block" || st == "maybeprop") {
+ add(spec.propertyKeywords);
+ } else if (st == "prop" || st == "parens" || st == "at" || st == "params") {
+ add(spec.valueKeywords);
+ add(spec.colorKeywords);
+ } else if (st == "media" || st == "media_parens") {
+ add(spec.mediaTypes);
+ add(spec.mediaFeatures);
+ }
+
+ if (result.length) return {
+ list: result,
+ from: CodeMirror.Pos(cur.line, start),
+ to: CodeMirror.Pos(cur.line, end)
+ };
+ });
+});
diff --git a/codemirror/addon/hint/html-hint.js b/codemirror/addon/hint/html-hint.js
new file mode 100644
index 00000000..c6769bca
--- /dev/null
+++ b/codemirror/addon/hint/html-hint.js
@@ -0,0 +1,348 @@
+// 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"), require("./xml-hint"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./xml-hint"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" ");
+ var targets = ["_blank", "_self", "_top", "_parent"];
+ var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
+ var methods = ["get", "post", "put", "delete"];
+ var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
+ var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech",
+ "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait",
+ "orientation:landscape", "device-height: [X]", "device-width: [X]"];
+ var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags
+
+ var data = {
+ a: {
+ attrs: {
+ href: null, ping: null, type: null,
+ media: media,
+ target: targets,
+ hreflang: langs
+ }
+ },
+ abbr: s,
+ acronym: s,
+ address: s,
+ applet: s,
+ area: {
+ attrs: {
+ alt: null, coords: null, href: null, target: null, ping: null,
+ media: media, hreflang: langs, type: null,
+ shape: ["default", "rect", "circle", "poly"]
+ }
+ },
+ article: s,
+ aside: s,
+ audio: {
+ attrs: {
+ src: null, mediagroup: null,
+ crossorigin: ["anonymous", "use-credentials"],
+ preload: ["none", "metadata", "auto"],
+ autoplay: ["", "autoplay"],
+ loop: ["", "loop"],
+ controls: ["", "controls"]
+ }
+ },
+ b: s,
+ base: { attrs: { href: null, target: targets } },
+ basefont: s,
+ bdi: s,
+ bdo: s,
+ big: s,
+ blockquote: { attrs: { cite: null } },
+ body: s,
+ br: s,
+ button: {
+ attrs: {
+ form: null, formaction: null, name: null, value: null,
+ autofocus: ["", "autofocus"],
+ disabled: ["", "autofocus"],
+ formenctype: encs,
+ formmethod: methods,
+ formnovalidate: ["", "novalidate"],
+ formtarget: targets,
+ type: ["submit", "reset", "button"]
+ }
+ },
+ canvas: { attrs: { width: null, height: null } },
+ caption: s,
+ center: s,
+ cite: s,
+ code: s,
+ col: { attrs: { span: null } },
+ colgroup: { attrs: { span: null } },
+ command: {
+ attrs: {
+ type: ["command", "checkbox", "radio"],
+ label: null, icon: null, radiogroup: null, command: null, title: null,
+ disabled: ["", "disabled"],
+ checked: ["", "checked"]
+ }
+ },
+ data: { attrs: { value: null } },
+ datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } },
+ datalist: { attrs: { data: null } },
+ dd: s,
+ del: { attrs: { cite: null, datetime: null } },
+ details: { attrs: { open: ["", "open"] } },
+ dfn: s,
+ dir: s,
+ div: s,
+ dl: s,
+ dt: s,
+ em: s,
+ embed: { attrs: { src: null, type: null, width: null, height: null } },
+ eventsource: { attrs: { src: null } },
+ fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } },
+ figcaption: s,
+ figure: s,
+ font: s,
+ footer: s,
+ form: {
+ attrs: {
+ action: null, name: null,
+ "accept-charset": charsets,
+ autocomplete: ["on", "off"],
+ enctype: encs,
+ method: methods,
+ novalidate: ["", "novalidate"],
+ target: targets
+ }
+ },
+ frame: s,
+ frameset: s,
+ h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,
+ head: {
+ attrs: {},
+ children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
+ },
+ header: s,
+ hgroup: s,
+ hr: s,
+ html: {
+ attrs: { manifest: null },
+ children: ["head", "body"]
+ },
+ i: s,
+ iframe: {
+ attrs: {
+ src: null, srcdoc: null, name: null, width: null, height: null,
+ sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
+ seamless: ["", "seamless"]
+ }
+ },
+ img: {
+ attrs: {
+ alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
+ crossorigin: ["anonymous", "use-credentials"]
+ }
+ },
+ input: {
+ attrs: {
+ alt: null, dirname: null, form: null, formaction: null,
+ height: null, list: null, max: null, maxlength: null, min: null,
+ name: null, pattern: null, placeholder: null, size: null, src: null,
+ step: null, value: null, width: null,
+ accept: ["audio/*", "video/*", "image/*"],
+ autocomplete: ["on", "off"],
+ autofocus: ["", "autofocus"],
+ checked: ["", "checked"],
+ disabled: ["", "disabled"],
+ formenctype: encs,
+ formmethod: methods,
+ formnovalidate: ["", "novalidate"],
+ formtarget: targets,
+ multiple: ["", "multiple"],
+ readonly: ["", "readonly"],
+ required: ["", "required"],
+ type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
+ "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
+ "file", "submit", "image", "reset", "button"]
+ }
+ },
+ ins: { attrs: { cite: null, datetime: null } },
+ kbd: s,
+ keygen: {
+ attrs: {
+ challenge: null, form: null, name: null,
+ autofocus: ["", "autofocus"],
+ disabled: ["", "disabled"],
+ keytype: ["RSA"]
+ }
+ },
+ label: { attrs: { "for": null, form: null } },
+ legend: s,
+ li: { attrs: { value: null } },
+ link: {
+ attrs: {
+ href: null, type: null,
+ hreflang: langs,
+ media: media,
+ sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
+ }
+ },
+ map: { attrs: { name: null } },
+ mark: s,
+ menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
+ meta: {
+ attrs: {
+ content: null,
+ charset: charsets,
+ name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
+ "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
+ }
+ },
+ meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
+ nav: s,
+ noframes: s,
+ noscript: s,
+ object: {
+ attrs: {
+ data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
+ typemustmatch: ["", "typemustmatch"]
+ }
+ },
+ ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } },
+ optgroup: { attrs: { disabled: ["", "disabled"], label: null } },
+ option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } },
+ output: { attrs: { "for": null, form: null, name: null } },
+ p: s,
+ param: { attrs: { name: null, value: null } },
+ pre: s,
+ progress: { attrs: { value: null, max: null } },
+ q: { attrs: { cite: null } },
+ rp: s,
+ rt: s,
+ ruby: s,
+ s: s,
+ samp: s,
+ script: {
+ attrs: {
+ type: ["text/javascript"],
+ src: null,
+ async: ["", "async"],
+ defer: ["", "defer"],
+ charset: charsets
+ }
+ },
+ section: s,
+ select: {
+ attrs: {
+ form: null, name: null, size: null,
+ autofocus: ["", "autofocus"],
+ disabled: ["", "disabled"],
+ multiple: ["", "multiple"]
+ }
+ },
+ small: s,
+ source: { attrs: { src: null, type: null, media: null } },
+ span: s,
+ strike: s,
+ strong: s,
+ style: {
+ attrs: {
+ type: ["text/css"],
+ media: media,
+ scoped: null
+ }
+ },
+ sub: s,
+ summary: s,
+ sup: s,
+ table: s,
+ tbody: s,
+ td: { attrs: { colspan: null, rowspan: null, headers: null } },
+ textarea: {
+ attrs: {
+ dirname: null, form: null, maxlength: null, name: null, placeholder: null,
+ rows: null, cols: null,
+ autofocus: ["", "autofocus"],
+ disabled: ["", "disabled"],
+ readonly: ["", "readonly"],
+ required: ["", "required"],
+ wrap: ["soft", "hard"]
+ }
+ },
+ tfoot: s,
+ th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
+ thead: s,
+ time: { attrs: { datetime: null } },
+ title: s,
+ tr: s,
+ track: {
+ attrs: {
+ src: null, label: null, "default": null,
+ kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
+ srclang: langs
+ }
+ },
+ tt: s,
+ u: s,
+ ul: s,
+ "var": s,
+ video: {
+ attrs: {
+ src: null, poster: null, width: null, height: null,
+ crossorigin: ["anonymous", "use-credentials"],
+ preload: ["auto", "metadata", "none"],
+ autoplay: ["", "autoplay"],
+ mediagroup: ["movie"],
+ muted: ["", "muted"],
+ controls: ["", "controls"]
+ }
+ },
+ wbr: s
+ };
+
+ var globalAttrs = {
+ accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ "class": null,
+ contenteditable: ["true", "false"],
+ contextmenu: null,
+ dir: ["ltr", "rtl", "auto"],
+ draggable: ["true", "false", "auto"],
+ dropzone: ["copy", "move", "link", "string:", "file:"],
+ hidden: ["hidden"],
+ id: null,
+ inert: ["inert"],
+ itemid: null,
+ itemprop: null,
+ itemref: null,
+ itemscope: ["itemscope"],
+ itemtype: null,
+ lang: ["en", "es"],
+ spellcheck: ["true", "false"],
+ style: null,
+ tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ title: null,
+ translate: ["yes", "no"],
+ onclick: null,
+ rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"]
+ };
+ function populate(obj) {
+ for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))
+ obj.attrs[attr] = globalAttrs[attr];
+ }
+
+ populate(s);
+ for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)
+ populate(data[tag]);
+
+ CodeMirror.htmlSchema = data;
+ function htmlHint(cm, options) {
+ var local = {schemaInfo: data};
+ if (options) for (var opt in options) local[opt] = options[opt];
+ return CodeMirror.hint.xml(cm, local);
+ }
+ CodeMirror.registerHelper("hint", "html", htmlHint);
+});
diff --git a/codemirror/addon/hint/javascript-hint.js b/codemirror/addon/hint/javascript-hint.js
new file mode 100644
index 00000000..7bcbf4a0
--- /dev/null
+++ b/codemirror/addon/hint/javascript-hint.js
@@ -0,0 +1,146 @@
+// 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) {
+ var Pos = CodeMirror.Pos;
+
+ function forEach(arr, f) {
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+ }
+
+ function arrayContains(arr, item) {
+ if (!Array.prototype.indexOf) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === item) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return arr.indexOf(item) != -1;
+ }
+
+ function scriptHint(editor, keywords, getToken, options) {
+ // Find the token at the cursor
+ var cur = editor.getCursor(), token = getToken(editor, cur);
+ if (/\b(?:string|comment)\b/.test(token.type)) return;
+ token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;
+
+ // If it's not a 'word-style' token, ignore the token.
+ if (!/^[\w$_]*$/.test(token.string)) {
+ token = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+ type: token.string == "." ? "property" : null};
+ } else if (token.end > cur.ch) {
+ token.end = cur.ch;
+ token.string = token.string.slice(0, cur.ch - token.start);
+ }
+
+ var tprop = token;
+ // If it is a property, find out what it is a property of.
+ while (tprop.type == "property") {
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
+ if (tprop.string != ".") return;
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
+ if (!context) var context = [];
+ context.push(tprop);
+ }
+ return {list: getCompletions(token, context, keywords, options),
+ from: Pos(cur.line, token.start),
+ to: Pos(cur.line, token.end)};
+ }
+
+ function javascriptHint(editor, options) {
+ return scriptHint(editor, javascriptKeywords,
+ function (e, cur) {return e.getTokenAt(cur);},
+ options);
+ };
+ CodeMirror.registerHelper("hint", "javascript", javascriptHint);
+
+ function getCoffeeScriptToken(editor, cur) {
+ // This getToken, it is for coffeescript, imitates the behavior of
+ // getTokenAt method in javascript.js, that is, returning "property"
+ // type and treat "." as indepenent token.
+ var token = editor.getTokenAt(cur);
+ if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
+ token.end = token.start;
+ token.string = '.';
+ token.type = "property";
+ }
+ else if (/^\.[\w$_]*$/.test(token.string)) {
+ token.type = "property";
+ token.start++;
+ token.string = token.string.replace(/\./, '');
+ }
+ return token;
+ }
+
+ function coffeescriptHint(editor, options) {
+ return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
+ }
+ CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);
+
+ var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
+ "toUpperCase toLowerCase split concat match replace search").split(" ");
+ var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
+ "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
+ var funcProps = "prototype apply call bind".split(" ");
+ var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
+ "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
+ var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
+ "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
+
+ function getCompletions(token, context, keywords, options) {
+ var found = [], start = token.string, global = options && options.globalScope || window;
+ function maybeAdd(str) {
+ if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
+ }
+ function gatherCompletions(obj) {
+ if (typeof obj == "string") forEach(stringProps, maybeAdd);
+ else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
+ else if (obj instanceof Function) forEach(funcProps, maybeAdd);
+ for (var name in obj) maybeAdd(name);
+ }
+
+ if (context && context.length) {
+ // If this is a property, see if it belongs to some object we can
+ // find in the current environment.
+ var obj = context.pop(), base;
+ if (obj.type && obj.type.indexOf("variable") === 0) {
+ if (options && options.additionalContext)
+ base = options.additionalContext[obj.string];
+ if (!options || options.useGlobalScope !== false)
+ base = base || global[obj.string];
+ } else if (obj.type == "string") {
+ base = "";
+ } else if (obj.type == "atom") {
+ base = 1;
+ } else if (obj.type == "function") {
+ if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
+ (typeof global.jQuery == 'function'))
+ base = global.jQuery();
+ else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function'))
+ base = global._();
+ }
+ while (base != null && context.length)
+ base = base[context.pop().string];
+ if (base != null) gatherCompletions(base);
+ } else {
+ // If not, just look in the global object and any local scope
+ // (reading into JS mode internals to get at the local and global variables)
+ for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
+ for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
+ if (!options || options.useGlobalScope !== false)
+ gatherCompletions(global);
+ forEach(keywords, maybeAdd);
+ }
+ return found;
+ }
+});
diff --git a/codemirror/addon/hint/show-hint.css b/codemirror/addon/hint/show-hint.css
new file mode 100644
index 00000000..924e638f
--- /dev/null
+++ b/codemirror/addon/hint/show-hint.css
@@ -0,0 +1,38 @@
+.CodeMirror-hints {
+ position: absolute;
+ z-index: 10;
+ overflow: hidden;
+ list-style: none;
+
+ margin: 0;
+ padding: 2px;
+
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ border-radius: 3px;
+ border: 1px solid silver;
+
+ background: white;
+ font-size: 90%;
+ font-family: monospace;
+
+ max-height: 20em;
+ overflow-y: auto;
+}
+
+.CodeMirror-hint {
+ margin: 0;
+ padding: 0 4px;
+ border-radius: 2px;
+ max-width: 19em;
+ overflow: hidden;
+ white-space: pre;
+ color: black;
+ cursor: pointer;
+}
+
+li.CodeMirror-hint-active {
+ background: #08f;
+ color: white;
+}
diff --git a/codemirror/addon/hint/show-hint.js b/codemirror/addon/hint/show-hint.js
new file mode 100644
index 00000000..cbe3b39a
--- /dev/null
+++ b/codemirror/addon/hint/show-hint.js
@@ -0,0 +1,440 @@
+// 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";
+
+ var HINT_ELEMENT_CLASS = "CodeMirror-hint";
+ var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
+
+ // This is the old interface, kept around for now to stay
+ // backwards-compatible.
+ CodeMirror.showHint = function(cm, getHints, options) {
+ if (!getHints) return cm.showHint(options);
+ if (options && options.async) getHints.async = true;
+ var newOpts = {hint: getHints};
+ if (options) for (var prop in options) newOpts[prop] = options[prop];
+ return cm.showHint(newOpts);
+ };
+
+ CodeMirror.defineExtension("showHint", function(options) {
+ options = parseOptions(this, this.getCursor("start"), options);
+ var selections = this.listSelections()
+ if (selections.length > 1) return;
+ // By default, don't allow completion when something is selected.
+ // A hint function can have a `supportsSelection` property to
+ // indicate that it can handle selections.
+ if (this.somethingSelected()) {
+ if (!options.hint.supportsSelection) return;
+ // Don't try with cross-line selections
+ for (var i = 0; i < selections.length; i++)
+ if (selections[i].head.line != selections[i].anchor.line) return;
+ }
+
+ if (this.state.completionActive) this.state.completionActive.close();
+ var completion = this.state.completionActive = new Completion(this, options);
+ if (!completion.options.hint) return;
+
+ CodeMirror.signal(this, "startCompletion", this);
+ completion.update(true);
+ });
+
+ function Completion(cm, options) {
+ this.cm = cm;
+ this.options = options;
+ this.widget = null;
+ this.debounce = 0;
+ this.tick = 0;
+ this.startPos = this.cm.getCursor("start");
+ this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
+
+ var self = this;
+ cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
+ }
+
+ var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
+ return setTimeout(fn, 1000/60);
+ };
+ var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
+
+ Completion.prototype = {
+ close: function() {
+ if (!this.active()) return;
+ this.cm.state.completionActive = null;
+ this.tick = null;
+ this.cm.off("cursorActivity", this.activityFunc);
+
+ if (this.widget && this.data) CodeMirror.signal(this.data, "close");
+ if (this.widget) this.widget.close();
+ CodeMirror.signal(this.cm, "endCompletion", this.cm);
+ },
+
+ active: function() {
+ return this.cm.state.completionActive == this;
+ },
+
+ pick: function(data, i) {
+ var completion = data.list[i];
+ if (completion.hint) completion.hint(this.cm, data, completion);
+ else this.cm.replaceRange(getText(completion), completion.from || data.from,
+ completion.to || data.to, "complete");
+ CodeMirror.signal(data, "pick", completion);
+ this.close();
+ },
+
+ cursorActivity: function() {
+ if (this.debounce) {
+ cancelAnimationFrame(this.debounce);
+ this.debounce = 0;
+ }
+
+ var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
+ if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
+ pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
+ (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
+ this.close();
+ } else {
+ var self = this;
+ this.debounce = requestAnimationFrame(function() {self.update();});
+ if (this.widget) this.widget.disable();
+ }
+ },
+
+ update: function(first) {
+ if (this.tick == null) return;
+ if (!this.options.hint.async) {
+ this.finishUpdate(this.options.hint(this.cm, this.options), first);
+ } else {
+ var myTick = ++this.tick, self = this;
+ this.options.hint(this.cm, function(data) {
+ if (self.tick == myTick) self.finishUpdate(data, first);
+ }, this.options);
+ }
+ },
+
+ finishUpdate: function(data, first) {
+ if (this.data) CodeMirror.signal(this.data, "update");
+ if (data && this.data && CodeMirror.cmpPos(data.from, this.data.from)) data = null;
+ this.data = data;
+
+ var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
+ if (this.widget) this.widget.close();
+ if (data && data.list.length) {
+ if (picked && data.list.length == 1) {
+ this.pick(data, 0);
+ } else {
+ this.widget = new Widget(this, data);
+ CodeMirror.signal(data, "shown");
+ }
+ }
+ }
+ };
+
+ function parseOptions(cm, pos, options) {
+ var editor = cm.options.hintOptions;
+ var out = {};
+ for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
+ if (editor) for (var prop in editor)
+ if (editor[prop] !== undefined) out[prop] = editor[prop];
+ if (options) for (var prop in options)
+ if (options[prop] !== undefined) out[prop] = options[prop];
+ if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
+ return out;
+ }
+
+ function getText(completion) {
+ if (typeof completion == "string") return completion;
+ else return completion.text;
+ }
+
+ function buildKeyMap(completion, handle) {
+ var baseMap = {
+ Up: function() {handle.moveFocus(-1);},
+ Down: function() {handle.moveFocus(1);},
+ PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
+ PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
+ Home: function() {handle.setFocus(0);},
+ End: function() {handle.setFocus(handle.length - 1);},
+ Enter: handle.pick,
+ Tab: handle.pick,
+ Esc: handle.close
+ };
+ var custom = completion.options.customKeys;
+ var ourMap = custom ? {} : baseMap;
+ function addBinding(key, val) {
+ var bound;
+ if (typeof val != "string")
+ bound = function(cm) { return val(cm, handle); };
+ // This mechanism is deprecated
+ else if (baseMap.hasOwnProperty(val))
+ bound = baseMap[val];
+ else
+ bound = val;
+ ourMap[key] = bound;
+ }
+ if (custom)
+ for (var key in custom) if (custom.hasOwnProperty(key))
+ addBinding(key, custom[key]);
+ var extra = completion.options.extraKeys;
+ if (extra)
+ for (var key in extra) if (extra.hasOwnProperty(key))
+ addBinding(key, extra[key]);
+ return ourMap;
+ }
+
+ function getHintElement(hintsElement, el) {
+ while (el && el != hintsElement) {
+ if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
+ el = el.parentNode;
+ }
+ }
+
+ function Widget(completion, data) {
+ this.completion = completion;
+ this.data = data;
+ this.picked = false;
+ var widget = this, cm = completion.cm;
+
+ var hints = this.hints = document.createElement("ul");
+ hints.className = "CodeMirror-hints";
+ this.selectedHint = data.selectedHint || 0;
+
+ var completions = data.list;
+ for (var i = 0; i < completions.length; ++i) {
+ var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
+ var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
+ if (cur.className != null) className = cur.className + " " + className;
+ elt.className = className;
+ if (cur.render) cur.render(elt, data, cur);
+ else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
+ elt.hintId = i;
+ }
+
+ var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
+ var left = pos.left, top = pos.bottom, below = true;
+ hints.style.left = left + "px";
+ hints.style.top = top + "px";
+ // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
+ var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
+ var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
+ (completion.options.container || document.body).appendChild(hints);
+ var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
+ if (overlapY > 0) {
+ var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
+ if (curTop - height > 0) { // Fits above cursor
+ hints.style.top = (top = pos.top - height) + "px";
+ below = false;
+ } else if (height > winH) {
+ hints.style.height = (winH - 5) + "px";
+ hints.style.top = (top = pos.bottom - box.top) + "px";
+ var cursor = cm.getCursor();
+ if (data.from.ch != cursor.ch) {
+ pos = cm.cursorCoords(cursor);
+ hints.style.left = (left = pos.left) + "px";
+ box = hints.getBoundingClientRect();
+ }
+ }
+ }
+ var overlapX = box.right - winW;
+ if (overlapX > 0) {
+ if (box.right - box.left > winW) {
+ hints.style.width = (winW - 5) + "px";
+ overlapX -= (box.right - box.left) - winW;
+ }
+ hints.style.left = (left = pos.left - overlapX) + "px";
+ }
+
+ cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
+ moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
+ setFocus: function(n) { widget.changeActive(n); },
+ menuSize: function() { return widget.screenAmount(); },
+ length: completions.length,
+ close: function() { completion.close(); },
+ pick: function() { widget.pick(); },
+ data: data
+ }));
+
+ if (completion.options.closeOnUnfocus) {
+ var closingOnBlur;
+ cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
+ cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
+ }
+
+ var startScroll = cm.getScrollInfo();
+ cm.on("scroll", this.onScroll = function() {
+ var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
+ var newTop = top + startScroll.top - curScroll.top;
+ var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
+ if (!below) point += hints.offsetHeight;
+ if (point <= editor.top || point >= editor.bottom) return completion.close();
+ hints.style.top = newTop + "px";
+ hints.style.left = (left + startScroll.left - curScroll.left) + "px";
+ });
+
+ CodeMirror.on(hints, "dblclick", function(e) {
+ var t = getHintElement(hints, e.target || e.srcElement);
+ if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
+ });
+
+ CodeMirror.on(hints, "click", function(e) {
+ var t = getHintElement(hints, e.target || e.srcElement);
+ if (t && t.hintId != null) {
+ widget.changeActive(t.hintId);
+ if (completion.options.completeOnSingleClick) widget.pick();
+ }
+ });
+
+ CodeMirror.on(hints, "mousedown", function() {
+ setTimeout(function(){cm.focus();}, 20);
+ });
+
+ CodeMirror.signal(data, "select", completions[0], hints.firstChild);
+ return true;
+ }
+
+ Widget.prototype = {
+ close: function() {
+ if (this.completion.widget != this) return;
+ this.completion.widget = null;
+ this.hints.parentNode.removeChild(this.hints);
+ this.completion.cm.removeKeyMap(this.keyMap);
+
+ var cm = this.completion.cm;
+ if (this.completion.options.closeOnUnfocus) {
+ cm.off("blur", this.onBlur);
+ cm.off("focus", this.onFocus);
+ }
+ cm.off("scroll", this.onScroll);
+ },
+
+ disable: function() {
+ this.completion.cm.removeKeyMap(this.keyMap);
+ var widget = this;
+ this.keyMap = {Enter: function() { widget.picked = true; }};
+ this.completion.cm.addKeyMap(this.keyMap);
+ },
+
+ pick: function() {
+ this.completion.pick(this.data, this.selectedHint);
+ },
+
+ changeActive: function(i, avoidWrap) {
+ if (i >= this.data.list.length)
+ i = avoidWrap ? this.data.list.length - 1 : 0;
+ else if (i < 0)
+ i = avoidWrap ? 0 : this.data.list.length - 1;
+ if (this.selectedHint == i) return;
+ var node = this.hints.childNodes[this.selectedHint];
+ node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
+ node = this.hints.childNodes[this.selectedHint = i];
+ node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
+ if (node.offsetTop < this.hints.scrollTop)
+ this.hints.scrollTop = node.offsetTop - 3;
+ else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
+ this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
+ CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
+ },
+
+ screenAmount: function() {
+ return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
+ }
+ };
+
+ function applicableHelpers(cm, helpers) {
+ if (!cm.somethingSelected()) return helpers
+ var result = []
+ for (var i = 0; i < helpers.length; i++)
+ if (helpers[i].supportsSelection) result.push(helpers[i])
+ return result
+ }
+
+ function resolveAutoHints(cm, pos) {
+ var helpers = cm.getHelpers(pos, "hint"), words
+ if (helpers.length) {
+ var async = false, resolved
+ for (var i = 0; i < helpers.length; i++) if (helpers[i].async) async = true
+ if (async) {
+ resolved = function(cm, callback, options) {
+ var app = applicableHelpers(cm, helpers)
+ function run(i, result) {
+ if (i == app.length) return callback(null)
+ var helper = app[i]
+ if (helper.async) {
+ helper(cm, function(result) {
+ if (result) callback(result)
+ else run(i + 1)
+ }, options)
+ } else {
+ var result = helper(cm, options)
+ if (result) callback(result)
+ else run(i + 1)
+ }
+ }
+ run(0)
+ }
+ resolved.async = true
+ } else {
+ resolved = function(cm, options) {
+ var app = applicableHelpers(cm, helpers)
+ for (var i = 0; i < app.length; i++) {
+ var cur = app[i](cm, options)
+ if (cur && cur.list.length) return cur
+ }
+ }
+ }
+ resolved.supportsSelection = true
+ return resolved
+ } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
+ return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
+ } else if (CodeMirror.hint.anyword) {
+ return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
+ } else {
+ return function() {}
+ }
+ }
+
+ CodeMirror.registerHelper("hint", "auto", {
+ resolve: resolveAutoHints
+ });
+
+ CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur);
+ var to = CodeMirror.Pos(cur.line, token.end);
+ if (token.string && /\w/.test(token.string[token.string.length - 1])) {
+ var term = token.string, from = CodeMirror.Pos(cur.line, token.start);
+ } else {
+ var term = "", from = to;
+ }
+ var found = [];
+ for (var i = 0; i < options.words.length; i++) {
+ var word = options.words[i];
+ if (word.slice(0, term.length) == term)
+ found.push(word);
+ }
+
+ if (found.length) return {list: found, from: from, to: to};
+ });
+
+ CodeMirror.commands.autocomplete = CodeMirror.showHint;
+
+ var defaultOptions = {
+ hint: CodeMirror.hint.auto,
+ completeSingle: true,
+ alignWithWord: true,
+ closeCharacters: /[\s()\[\]{};:>,]/,
+ closeOnUnfocus: true,
+ completeOnSingleClick: true,
+ container: null,
+ customKeys: null,
+ extraKeys: null
+ };
+
+ CodeMirror.defineOption("hintOptions", null);
+});
diff --git a/codemirror/addon/hint/sql-hint.js b/codemirror/addon/hint/sql-hint.js
new file mode 100644
index 00000000..22124b58
--- /dev/null
+++ b/codemirror/addon/hint/sql-hint.js
@@ -0,0 +1,254 @@
+// 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"), require("../../mode/sql/sql"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var tables;
+ var defaultTable;
+ var keywords;
+ var CONS = {
+ QUERY_DIV: ";",
+ ALIAS_KEYWORD: "AS"
+ };
+ var Pos = CodeMirror.Pos;
+
+ function getKeywords(editor) {
+ var mode = editor.doc.modeOption;
+ if (mode === "sql") mode = "text/x-sql";
+ return CodeMirror.resolveMode(mode).keywords;
+ }
+
+ function getText(item) {
+ return typeof item == "string" ? item : item.text;
+ }
+
+ function getItem(list, item) {
+ if (!list.slice) return list[item];
+ for (var i = list.length - 1; i >= 0; i--) if (getText(list[i]) == item)
+ return list[i];
+ }
+
+ function shallowClone(object) {
+ var result = {};
+ for (var key in object) if (object.hasOwnProperty(key))
+ result[key] = object[key];
+ return result;
+ }
+
+ function match(string, word) {
+ var len = string.length;
+ var sub = getText(word).substr(0, len);
+ return string.toUpperCase() === sub.toUpperCase();
+ }
+
+ function addMatches(result, search, wordlist, formatter) {
+ for (var word in wordlist) {
+ if (!wordlist.hasOwnProperty(word)) continue;
+ if (wordlist.slice) word = wordlist[word];
+
+ if (match(search, word)) result.push(formatter(word));
+ }
+ }
+
+ function cleanName(name) {
+ // Get rid name from backticks(`) and preceding dot(.)
+ if (name.charAt(0) == ".") {
+ name = name.substr(1);
+ }
+ return name.replace(/`/g, "");
+ }
+
+ function insertBackticks(name) {
+ var nameParts = getText(name).split(".");
+ for (var i = 0; i < nameParts.length; i++)
+ nameParts[i] = "`" + nameParts[i] + "`";
+ var escaped = nameParts.join(".");
+ if (typeof name == "string") return escaped;
+ name = shallowClone(name);
+ name.text = escaped;
+ return name;
+ }
+
+ function nameCompletion(cur, token, result, editor) {
+ // Try to complete table, colunm names and return start position of completion
+ var useBacktick = false;
+ var nameParts = [];
+ var start = token.start;
+ var cont = true;
+ while (cont) {
+ cont = (token.string.charAt(0) == ".");
+ useBacktick = useBacktick || (token.string.charAt(0) == "`");
+
+ start = token.start;
+ nameParts.unshift(cleanName(token.string));
+
+ token = editor.getTokenAt(Pos(cur.line, token.start));
+ if (token.string == ".") {
+ cont = true;
+ token = editor.getTokenAt(Pos(cur.line, token.start));
+ }
+ }
+
+ // Try to complete table names
+ var string = nameParts.join(".");
+ addMatches(result, string, tables, function(w) {
+ return useBacktick ? insertBackticks(w) : w;
+ });
+
+ // Try to complete columns from defaultTable
+ addMatches(result, string, defaultTable, function(w) {
+ return useBacktick ? insertBackticks(w) : w;
+ });
+
+ // Try to complete columns
+ string = nameParts.pop();
+ var table = nameParts.join(".");
+
+ var alias = false;
+ var aliasTable = table;
+ // Check if table is available. If not, find table by Alias
+ if (!getItem(tables, table)) {
+ var oldTable = table;
+ table = findTableByAlias(table, editor);
+ if (table !== oldTable) alias = true;
+ }
+
+ var columns = getItem(tables, table);
+ if (columns && columns.columns)
+ columns = columns.columns;
+
+ if (columns) {
+ addMatches(result, string, columns, function(w) {
+ var tableInsert = table;
+ if (alias == true) tableInsert = aliasTable;
+ if (typeof w == "string") {
+ w = tableInsert + "." + w;
+ } else {
+ w = shallowClone(w);
+ w.text = tableInsert + "." + w.text;
+ }
+ return useBacktick ? insertBackticks(w) : w;
+ });
+ }
+
+ return start;
+ }
+
+ function eachWord(lineText, f) {
+ if (!lineText) return;
+ var excepted = /[,;]/g;
+ var words = lineText.split(" ");
+ for (var i = 0; i < words.length; i++) {
+ f(words[i]?words[i].replace(excepted, '') : '');
+ }
+ }
+
+ function convertCurToNumber(cur) {
+ // max characters of a line is 999,999.
+ return cur.line + cur.ch / Math.pow(10, 6);
+ }
+
+ function convertNumberToCur(num) {
+ return Pos(Math.floor(num), +num.toString().split('.').pop());
+ }
+
+ function findTableByAlias(alias, editor) {
+ var doc = editor.doc;
+ var fullQuery = doc.getValue();
+ var aliasUpperCase = alias.toUpperCase();
+ var previousWord = "";
+ var table = "";
+ var separator = [];
+ var validRange = {
+ start: Pos(0, 0),
+ end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
+ };
+
+ //add separator
+ var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
+ while(indexOfSeparator != -1) {
+ separator.push(doc.posFromIndex(indexOfSeparator));
+ indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
+ }
+ separator.unshift(Pos(0, 0));
+ separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
+
+ //find valid range
+ var prevItem = 0;
+ var current = convertCurToNumber(editor.getCursor());
+ for (var i=0; i< separator.length; i++) {
+ var _v = convertCurToNumber(separator[i]);
+ if (current > prevItem && current <= _v) {
+ validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
+ break;
+ }
+ prevItem = _v;
+ }
+
+ var query = doc.getRange(validRange.start, validRange.end, false);
+
+ for (var i = 0; i < query.length; i++) {
+ var lineText = query[i];
+ eachWord(lineText, function(word) {
+ var wordUpperCase = word.toUpperCase();
+ if (wordUpperCase === aliasUpperCase && getItem(tables, previousWord))
+ table = previousWord;
+ if (wordUpperCase !== CONS.ALIAS_KEYWORD)
+ previousWord = word;
+ });
+ if (table) break;
+ }
+ return table;
+ }
+
+ CodeMirror.registerHelper("hint", "sql", function(editor, options) {
+ tables = (options && options.tables) || {};
+ var defaultTableName = options && options.defaultTable;
+ var disableKeywords = options && options.disableKeywords;
+ defaultTable = defaultTableName && getItem(tables, defaultTableName);
+ keywords = keywords || getKeywords(editor);
+
+ if (defaultTableName && !defaultTable)
+ defaultTable = findTableByAlias(defaultTableName, editor);
+
+ defaultTable = defaultTable || [];
+
+ if (defaultTable.columns)
+ defaultTable = defaultTable.columns;
+
+ var cur = editor.getCursor();
+ var result = [];
+ var token = editor.getTokenAt(cur), start, end, search;
+ if (token.end > cur.ch) {
+ token.end = cur.ch;
+ token.string = token.string.slice(0, cur.ch - token.start);
+ }
+
+ if (token.string.match(/^[.`\w@]\w*$/)) {
+ search = token.string;
+ start = token.start;
+ end = token.end;
+ } else {
+ start = end = cur.ch;
+ search = "";
+ }
+ if (search.charAt(0) == "." || search.charAt(0) == "`") {
+ start = nameCompletion(cur, token, result, editor);
+ } else {
+ addMatches(result, search, tables, function(w) {return w;});
+ addMatches(result, search, defaultTable, function(w) {return w;});
+ if (!disableKeywords)
+ addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
+ }
+
+ return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
+ });
+});
diff --git a/codemirror/addon/hint/xml-hint.js b/codemirror/addon/hint/xml-hint.js
new file mode 100644
index 00000000..9b9baa0c
--- /dev/null
+++ b/codemirror/addon/hint/xml-hint.js
@@ -0,0 +1,110 @@
+// 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";
+
+ var Pos = CodeMirror.Pos;
+
+ function getHints(cm, options) {
+ var tags = options && options.schemaInfo;
+ var quote = (options && options.quoteChar) || '"';
+ if (!tags) return;
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur);
+ if (token.end > cur.ch) {
+ token.end = cur.ch;
+ token.string = token.string.slice(0, cur.ch - token.start);
+ }
+ var inner = CodeMirror.innerMode(cm.getMode(), token.state);
+ if (inner.mode.name != "xml") return;
+ var result = [], replaceToken = false, prefix;
+ var tag = /\btag\b/.test(token.type) && !/>$/.test(token.string);
+ var tagName = tag && /^\w/.test(token.string), tagStart;
+
+ if (tagName) {
+ var before = cm.getLine(cur.line).slice(Math.max(0, token.start - 2), token.start);
+ var tagType = /<\/$/.test(before) ? "close" : /<$/.test(before) ? "open" : null;
+ if (tagType) tagStart = token.start - (tagType == "close" ? 2 : 1);
+ } else if (tag && token.string == "<") {
+ tagType = "open";
+ } else if (tag && token.string == "") {
+ tagType = "close";
+ }
+
+ if (!tag && !inner.state.tagName || tagType) {
+ if (tagName)
+ prefix = token.string;
+ replaceToken = tagType;
+ var cx = inner.state.context, curTag = cx && tags[cx.tagName];
+ var childList = cx ? curTag && curTag.children : tags["!top"];
+ if (childList && tagType != "close") {
+ for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0)
+ result.push("<" + childList[i]);
+ } else if (tagType != "close") {
+ for (var name in tags)
+ if (tags.hasOwnProperty(name) && name != "!top" && name != "!attrs" && (!prefix || name.lastIndexOf(prefix, 0) == 0))
+ result.push("<" + name);
+ }
+ if (cx && (!prefix || tagType == "close" && cx.tagName.lastIndexOf(prefix, 0) == 0))
+ result.push("" + cx.tagName + ">");
+ } else {
+ // Attribute completion
+ var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;
+ var globalAttrs = tags["!attrs"];
+ if (!attrs && !globalAttrs) return;
+ if (!attrs) {
+ attrs = globalAttrs;
+ } else if (globalAttrs) { // Combine tag-local and global attributes
+ var set = {};
+ for (var nm in globalAttrs) if (globalAttrs.hasOwnProperty(nm)) set[nm] = globalAttrs[nm];
+ for (var nm in attrs) if (attrs.hasOwnProperty(nm)) set[nm] = attrs[nm];
+ attrs = set;
+ }
+ if (token.type == "string" || token.string == "=") { // A value
+ var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),
+ Pos(cur.line, token.type == "string" ? token.start : token.end));
+ var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
+ if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
+ if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget
+ if (token.type == "string") {
+ prefix = token.string;
+ var n = 0;
+ if (/['"]/.test(token.string.charAt(0))) {
+ quote = token.string.charAt(0);
+ prefix = token.string.slice(1);
+ n++;
+ }
+ var len = token.string.length;
+ if (/['"]/.test(token.string.charAt(len - 1))) {
+ quote = token.string.charAt(len - 1);
+ prefix = token.string.substr(n, len - 2);
+ }
+ replaceToken = true;
+ }
+ for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0)
+ result.push(quote + atValues[i] + quote);
+ } else { // An attribute name
+ if (token.type == "attribute") {
+ prefix = token.string;
+ replaceToken = true;
+ }
+ for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0))
+ result.push(attr);
+ }
+ }
+ return {
+ list: result,
+ from: replaceToken ? Pos(cur.line, tagStart == null ? token.start : tagStart) : cur,
+ to: replaceToken ? Pos(cur.line, token.end) : cur
+ };
+ }
+
+ CodeMirror.registerHelper("hint", "xml", getHints);
+});
diff --git a/codemirror/addon/lint/coffeescript-lint.js b/codemirror/addon/lint/coffeescript-lint.js
new file mode 100644
index 00000000..7e39428f
--- /dev/null
+++ b/codemirror/addon/lint/coffeescript-lint.js
@@ -0,0 +1,41 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js
+
+// declare global: coffeelint
+
+(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.registerHelper("lint", "coffeescript", function(text) {
+ var found = [];
+ var parseError = function(err) {
+ var loc = err.lineNumber;
+ found.push({from: CodeMirror.Pos(loc-1, 0),
+ to: CodeMirror.Pos(loc, 0),
+ severity: err.level,
+ message: err.message});
+ };
+ try {
+ var res = coffeelint.lint(text);
+ for(var i = 0; i < res.length; i++) {
+ parseError(res[i]);
+ }
+ } catch(e) {
+ found.push({from: CodeMirror.Pos(e.location.first_line, 0),
+ to: CodeMirror.Pos(e.location.last_line, e.location.last_column),
+ severity: 'error',
+ message: e.message});
+ }
+ return found;
+});
+
+});
diff --git a/codemirror/addon/lint/css-lint.js b/codemirror/addon/lint/css-lint.js
new file mode 100644
index 00000000..1f61b479
--- /dev/null
+++ b/codemirror/addon/lint/css-lint.js
@@ -0,0 +1,35 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Depends on csslint.js from https://github.com/stubbornella/csslint
+
+// declare global: CSSLint
+
+(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.registerHelper("lint", "css", function(text) {
+ var found = [];
+ if (!window.CSSLint) return found;
+ var results = CSSLint.verify(text), messages = results.messages, message = null;
+ for ( var i = 0; i < messages.length; i++) {
+ message = messages[i];
+ var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col;
+ found.push({
+ from: CodeMirror.Pos(startLine, startCol),
+ to: CodeMirror.Pos(endLine, endCol),
+ message: message.message,
+ severity : message.type
+ });
+ }
+ return found;
+});
+
+});
diff --git a/codemirror/addon/lint/html-lint.js b/codemirror/addon/lint/html-lint.js
new file mode 100644
index 00000000..1e841709
--- /dev/null
+++ b/codemirror/addon/lint/html-lint.js
@@ -0,0 +1,46 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Depends on htmlhint.js from http://htmlhint.com/js/htmlhint.js
+
+// declare global: HTMLHint
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"), require("htmlhint"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "htmlhint"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var defaultRules = {
+ "tagname-lowercase": true,
+ "attr-lowercase": true,
+ "attr-value-double-quotes": true,
+ "doctype-first": false,
+ "tag-pair": true,
+ "spec-char-escape": true,
+ "id-unique": true,
+ "src-not-empty": true,
+ "attr-no-duplication": true
+ };
+
+ CodeMirror.registerHelper("lint", "html", function(text, options) {
+ var found = [];
+ if (!window.HTMLHint) return found;
+ var messages = HTMLHint.verify(text, options && options.rules || defaultRules);
+ for (var i = 0; i < messages.length; i++) {
+ var message = messages[i];
+ var startLine = message.line - 1, endLine = message.line - 1, startCol = message.col - 1, endCol = message.col;
+ found.push({
+ from: CodeMirror.Pos(startLine, startCol),
+ to: CodeMirror.Pos(endLine, endCol),
+ message: message.message,
+ severity : message.type
+ });
+ }
+ return found;
+ });
+});
diff --git a/codemirror/addon/lint/javascript-lint.js b/codemirror/addon/lint/javascript-lint.js
new file mode 100644
index 00000000..d4f2ae9a
--- /dev/null
+++ b/codemirror/addon/lint/javascript-lint.js
@@ -0,0 +1,136 @@
+// 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";
+ // declare global: JSHINT
+
+ var bogus = [ "Dangerous comment" ];
+
+ var warnings = [ [ "Expected '{'",
+ "Statement body should be inside '{ }' braces." ] ];
+
+ var errors = [ "Missing semicolon", "Extra comma", "Missing property name",
+ "Unmatched ", " and instead saw", " is not defined",
+ "Unclosed string", "Stopping, unable to continue" ];
+
+ function validator(text, options) {
+ if (!window.JSHINT) return [];
+ JSHINT(text, options, options.globals);
+ var errors = JSHINT.data().errors, result = [];
+ if (errors) parseErrors(errors, result);
+ return result;
+ }
+
+ CodeMirror.registerHelper("lint", "javascript", validator);
+
+ function cleanup(error) {
+ // All problems are warnings by default
+ fixWith(error, warnings, "warning", true);
+ fixWith(error, errors, "error");
+
+ return isBogus(error) ? null : error;
+ }
+
+ function fixWith(error, fixes, severity, force) {
+ var description, fix, find, replace, found;
+
+ description = error.description;
+
+ for ( var i = 0; i < fixes.length; i++) {
+ fix = fixes[i];
+ find = (typeof fix === "string" ? fix : fix[0]);
+ replace = (typeof fix === "string" ? null : fix[1]);
+ found = description.indexOf(find) !== -1;
+
+ if (force || found) {
+ error.severity = severity;
+ }
+ if (found && replace) {
+ error.description = replace;
+ }
+ }
+ }
+
+ function isBogus(error) {
+ var description = error.description;
+ for ( var i = 0; i < bogus.length; i++) {
+ if (description.indexOf(bogus[i]) !== -1) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function parseErrors(errors, output) {
+ for ( var i = 0; i < errors.length; i++) {
+ var error = errors[i];
+ if (error) {
+ var linetabpositions, index;
+
+ linetabpositions = [];
+
+ // This next block is to fix a problem in jshint. Jshint
+ // replaces
+ // all tabs with spaces then performs some checks. The error
+ // positions (character/space) are then reported incorrectly,
+ // not taking the replacement step into account. Here we look
+ // at the evidence line and try to adjust the character position
+ // to the correct value.
+ if (error.evidence) {
+ // Tab positions are computed once per line and cached
+ var tabpositions = linetabpositions[error.line];
+ if (!tabpositions) {
+ var evidence = error.evidence;
+ tabpositions = [];
+ // ugggh phantomjs does not like this
+ // forEachChar(evidence, function(item, index) {
+ Array.prototype.forEach.call(evidence, function(item,
+ index) {
+ if (item === '\t') {
+ // First col is 1 (not 0) to match error
+ // positions
+ tabpositions.push(index + 1);
+ }
+ });
+ linetabpositions[error.line] = tabpositions;
+ }
+ if (tabpositions.length > 0) {
+ var pos = error.character;
+ tabpositions.forEach(function(tabposition) {
+ if (pos > tabposition) pos -= 1;
+ });
+ error.character = pos;
+ }
+ }
+
+ var start = error.character - 1, end = start + 1;
+ if (error.evidence) {
+ index = error.evidence.substring(start).search(/.\b/);
+ if (index > -1) {
+ end += index;
+ }
+ }
+
+ // Convert to format expected by validation service
+ error.description = error.reason;// + "(jshint)";
+ error.start = error.character;
+ error.end = end;
+ error = cleanup(error);
+
+ if (error)
+ output.push({message: error.description,
+ severity: error.severity,
+ from: CodeMirror.Pos(error.line - 1, start),
+ to: CodeMirror.Pos(error.line - 1, end)});
+ }
+ }
+ }
+});
diff --git a/codemirror/addon/lint/json-lint.js b/codemirror/addon/lint/json-lint.js
new file mode 100644
index 00000000..9dbb616b
--- /dev/null
+++ b/codemirror/addon/lint/json-lint.js
@@ -0,0 +1,31 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Depends on jsonlint.js from https://github.com/zaach/jsonlint
+
+// declare global: jsonlint
+
+(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.registerHelper("lint", "json", function(text) {
+ var found = [];
+ jsonlint.parseError = function(str, hash) {
+ var loc = hash.loc;
+ found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
+ to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
+ message: str});
+ };
+ try { jsonlint.parse(text); }
+ catch(e) {}
+ return found;
+});
+
+});
diff --git a/codemirror/addon/lint/lint.css b/codemirror/addon/lint/lint.css
new file mode 100644
index 00000000..414a9a0e
--- /dev/null
+++ b/codemirror/addon/lint/lint.css
@@ -0,0 +1,73 @@
+/* The lint marker gutter */
+.CodeMirror-lint-markers {
+ width: 16px;
+}
+
+.CodeMirror-lint-tooltip {
+ background-color: infobackground;
+ border: 1px solid black;
+ border-radius: 4px 4px 4px 4px;
+ color: infotext;
+ font-family: monospace;
+ font-size: 10pt;
+ overflow: hidden;
+ padding: 2px 5px;
+ position: fixed;
+ white-space: pre;
+ white-space: pre-wrap;
+ z-index: 100;
+ max-width: 600px;
+ opacity: 0;
+ transition: opacity .4s;
+ -moz-transition: opacity .4s;
+ -webkit-transition: opacity .4s;
+ -o-transition: opacity .4s;
+ -ms-transition: opacity .4s;
+}
+
+.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
+ background-position: left bottom;
+ background-repeat: repeat-x;
+}
+
+.CodeMirror-lint-mark-error {
+ background-image:
+ url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
+ ;
+}
+
+.CodeMirror-lint-mark-warning {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
+}
+
+.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
+ background-position: center center;
+ background-repeat: no-repeat;
+ cursor: pointer;
+ display: inline-block;
+ height: 16px;
+ width: 16px;
+ vertical-align: middle;
+ position: relative;
+}
+
+.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
+ padding-left: 18px;
+ background-position: top left;
+ background-repeat: no-repeat;
+}
+
+.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
+}
+
+.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
+}
+
+.CodeMirror-lint-marker-multiple {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
+ background-repeat: no-repeat;
+ background-position: right bottom;
+ width: 100%; height: 100%;
+}
diff --git a/codemirror/addon/lint/lint.js b/codemirror/addon/lint/lint.js
new file mode 100644
index 00000000..5afe49d0
--- /dev/null
+++ b/codemirror/addon/lint/lint.js
@@ -0,0 +1,231 @@
+// 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";
+ var GUTTER_ID = "CodeMirror-lint-markers";
+
+ function showTooltip(e, content) {
+ var tt = document.createElement("div");
+ tt.className = "CodeMirror-lint-tooltip";
+ tt.appendChild(content.cloneNode(true));
+ document.body.appendChild(tt);
+
+ function position(e) {
+ if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
+ tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
+ tt.style.left = (e.clientX + 5) + "px";
+ }
+ CodeMirror.on(document, "mousemove", position);
+ position(e);
+ if (tt.style.opacity != null) tt.style.opacity = 1;
+ return tt;
+ }
+ function rm(elt) {
+ if (elt.parentNode) elt.parentNode.removeChild(elt);
+ }
+ function hideTooltip(tt) {
+ if (!tt.parentNode) return;
+ if (tt.style.opacity == null) rm(tt);
+ tt.style.opacity = 0;
+ setTimeout(function() { rm(tt); }, 600);
+ }
+
+ function showTooltipFor(e, content, node) {
+ var tooltip = showTooltip(e, content);
+ function hide() {
+ CodeMirror.off(node, "mouseout", hide);
+ if (tooltip) { hideTooltip(tooltip); tooltip = null; }
+ }
+ var poll = setInterval(function() {
+ if (tooltip) for (var n = node;; n = n.parentNode) {
+ if (n && n.nodeType == 11) n = n.host;
+ if (n == document.body) return;
+ if (!n) { hide(); break; }
+ }
+ if (!tooltip) return clearInterval(poll);
+ }, 400);
+ CodeMirror.on(node, "mouseout", hide);
+ }
+
+ function LintState(cm, options, hasGutter) {
+ this.marked = [];
+ this.options = options;
+ this.timeout = null;
+ this.hasGutter = hasGutter;
+ this.onMouseOver = function(e) { onMouseOver(cm, e); };
+ this.waitingFor = 0
+ }
+
+ function parseOptions(_cm, options) {
+ if (options instanceof Function) return {getAnnotations: options};
+ if (!options || options === true) options = {};
+ return options;
+ }
+
+ function clearMarks(cm) {
+ var state = cm.state.lint;
+ if (state.hasGutter) cm.clearGutter(GUTTER_ID);
+ for (var i = 0; i < state.marked.length; ++i)
+ state.marked[i].clear();
+ state.marked.length = 0;
+ }
+
+ function makeMarker(labels, severity, multiple, tooltips) {
+ var marker = document.createElement("div"), inner = marker;
+ marker.className = "CodeMirror-lint-marker-" + severity;
+ if (multiple) {
+ inner = marker.appendChild(document.createElement("div"));
+ inner.className = "CodeMirror-lint-marker-multiple";
+ }
+
+ if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
+ showTooltipFor(e, labels, inner);
+ });
+
+ return marker;
+ }
+
+ function getMaxSeverity(a, b) {
+ if (a == "error") return a;
+ else return b;
+ }
+
+ function groupByLine(annotations) {
+ var lines = [];
+ for (var i = 0; i < annotations.length; ++i) {
+ var ann = annotations[i], line = ann.from.line;
+ (lines[line] || (lines[line] = [])).push(ann);
+ }
+ return lines;
+ }
+
+ function annotationTooltip(ann) {
+ var severity = ann.severity;
+ if (!severity) severity = "error";
+ var tip = document.createElement("div");
+ tip.className = "CodeMirror-lint-message-" + severity;
+ tip.appendChild(document.createTextNode(ann.message));
+ return tip;
+ }
+
+ function lintAsync(cm, getAnnotations, passOptions) {
+ var state = cm.state.lint
+ var id = ++state.waitingFor
+ function abort() {
+ id = -1
+ cm.off("change", abort)
+ }
+ cm.on("change", abort)
+ getAnnotations(cm.getValue(), function(annotations, arg2) {
+ cm.off("change", abort)
+ if (state.waitingFor != id) return
+ if (arg2 && annotations instanceof CodeMirror) annotations = arg2
+ updateLinting(cm, annotations)
+ }, passOptions, cm);
+ }
+
+ function startLinting(cm) {
+ var state = cm.state.lint, options = state.options;
+ var passOptions = options.options || options; // Support deprecated passing of `options` property in options
+ var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
+ if (!getAnnotations) return;
+ if (options.async || getAnnotations.async) {
+ lintAsync(cm, getAnnotations, passOptions)
+ } else {
+ updateLinting(cm, getAnnotations(cm.getValue(), passOptions, cm));
+ }
+ }
+
+ function updateLinting(cm, annotationsNotSorted) {
+ clearMarks(cm);
+ var state = cm.state.lint, options = state.options;
+
+ var annotations = groupByLine(annotationsNotSorted);
+
+ for (var line = 0; line < annotations.length; ++line) {
+ var anns = annotations[line];
+ if (!anns) continue;
+
+ var maxSeverity = null;
+ var tipLabel = state.hasGutter && document.createDocumentFragment();
+
+ for (var i = 0; i < anns.length; ++i) {
+ var ann = anns[i];
+ var severity = ann.severity;
+ if (!severity) severity = "error";
+ maxSeverity = getMaxSeverity(maxSeverity, severity);
+
+ if (options.formatAnnotation) ann = options.formatAnnotation(ann);
+ if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
+
+ if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
+ className: "CodeMirror-lint-mark-" + severity,
+ __annotation: ann
+ }));
+ }
+
+ if (state.hasGutter)
+ cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
+ state.options.tooltips));
+ }
+ if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
+ }
+
+ function onChange(cm) {
+ var state = cm.state.lint;
+ if (!state) return;
+ clearTimeout(state.timeout);
+ state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
+ }
+
+ function popupSpanTooltip(ann, e) {
+ var target = e.target || e.srcElement;
+ showTooltipFor(e, annotationTooltip(ann), target);
+ }
+
+ function onMouseOver(cm, e) {
+ var target = e.target || e.srcElement;
+ if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
+ var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
+ var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
+ for (var i = 0; i < spans.length; ++i) {
+ var ann = spans[i].__annotation;
+ if (ann) return popupSpanTooltip(ann, e);
+ }
+ }
+
+ CodeMirror.defineOption("lint", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ clearMarks(cm);
+ if (cm.state.lint.options.lintOnChange !== false)
+ cm.off("change", onChange);
+ CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
+ clearTimeout(cm.state.lint.timeout);
+ delete cm.state.lint;
+ }
+
+ if (val) {
+ var gutters = cm.getOption("gutters"), hasLintGutter = false;
+ for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
+ var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
+ if (state.options.lintOnChange !== false)
+ cm.on("change", onChange);
+ if (state.options.tooltips != false)
+ CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
+
+ startLinting(cm);
+ }
+ });
+
+ CodeMirror.defineExtension("performLint", function() {
+ if (this.state.lint) startLinting(this);
+ });
+});
diff --git a/codemirror/addon/lint/yaml-lint.js b/codemirror/addon/lint/yaml-lint.js
new file mode 100644
index 00000000..3f77e525
--- /dev/null
+++ b/codemirror/addon/lint/yaml-lint.js
@@ -0,0 +1,28 @@
+// 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";
+
+// Depends on js-yaml.js from https://github.com/nodeca/js-yaml
+
+// declare global: jsyaml
+
+CodeMirror.registerHelper("lint", "yaml", function(text) {
+ var found = [];
+ try { jsyaml.load(text); }
+ catch(e) {
+ var loc = e.mark;
+ found.push({ from: CodeMirror.Pos(loc.line, loc.column), to: CodeMirror.Pos(loc.line, loc.column), message: e.message });
+ }
+ return found;
+});
+
+});
diff --git a/codemirror/addon/merge/merge.css b/codemirror/addon/merge/merge.css
new file mode 100644
index 00000000..a6a80e43
--- /dev/null
+++ b/codemirror/addon/merge/merge.css
@@ -0,0 +1,112 @@
+.CodeMirror-merge {
+ position: relative;
+ border: 1px solid #ddd;
+ white-space: pre;
+}
+
+.CodeMirror-merge, .CodeMirror-merge .CodeMirror {
+ height: 350px;
+}
+
+.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
+.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
+.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
+.CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }
+
+.CodeMirror-merge-pane {
+ display: inline-block;
+ white-space: normal;
+ vertical-align: top;
+}
+.CodeMirror-merge-pane-rightmost {
+ position: absolute;
+ right: 0px;
+ z-index: 1;
+}
+
+.CodeMirror-merge-gap {
+ z-index: 2;
+ display: inline-block;
+ height: 100%;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ overflow: hidden;
+ border-left: 1px solid #ddd;
+ border-right: 1px solid #ddd;
+ position: relative;
+ background: #f8f8f8;
+}
+
+.CodeMirror-merge-scrolllock-wrap {
+ position: absolute;
+ bottom: 0; left: 50%;
+}
+.CodeMirror-merge-scrolllock {
+ position: relative;
+ left: -50%;
+ cursor: pointer;
+ color: #555;
+ line-height: 1;
+}
+
+.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
+ position: absolute;
+ left: 0; top: 0;
+ right: 0; bottom: 0;
+ line-height: 1;
+}
+
+.CodeMirror-merge-copy {
+ position: absolute;
+ cursor: pointer;
+ color: #44c;
+}
+
+.CodeMirror-merge-copy-reverse {
+ position: absolute;
+ cursor: pointer;
+ color: #44c;
+}
+
+.CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }
+.CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }
+
+.CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);
+ background-position: bottom left;
+ background-repeat: repeat-x;
+}
+
+.CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);
+ background-position: bottom left;
+ background-repeat: repeat-x;
+}
+
+.CodeMirror-merge-r-chunk { background: #ffffe0; }
+.CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }
+.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }
+.CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }
+
+.CodeMirror-merge-l-chunk { background: #eef; }
+.CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }
+.CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }
+.CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }
+
+.CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }
+.CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }
+.CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }
+
+.CodeMirror-merge-collapsed-widget:before {
+ content: "(...)";
+}
+.CodeMirror-merge-collapsed-widget {
+ cursor: pointer;
+ color: #88b;
+ background: #eef;
+ border: 1px solid #ddf;
+ font-size: 90%;
+ padding: 0 3px;
+ border-radius: 4px;
+}
+.CodeMirror-merge-collapsed-line .CodeMirror-gutter-elt { display: none; }
diff --git a/codemirror/addon/merge/merge.js b/codemirror/addon/merge/merge.js
new file mode 100644
index 00000000..830a5f02
--- /dev/null
+++ b/codemirror/addon/merge/merge.js
@@ -0,0 +1,772 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror")); // Note non-packaged dependency diff_match_patch
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "diff_match_patch"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+ var Pos = CodeMirror.Pos;
+ var svgNS = "http://www.w3.org/2000/svg";
+
+ function DiffView(mv, type) {
+ this.mv = mv;
+ this.type = type;
+ this.classes = type == "left"
+ ? {chunk: "CodeMirror-merge-l-chunk",
+ start: "CodeMirror-merge-l-chunk-start",
+ end: "CodeMirror-merge-l-chunk-end",
+ insert: "CodeMirror-merge-l-inserted",
+ del: "CodeMirror-merge-l-deleted",
+ connect: "CodeMirror-merge-l-connect"}
+ : {chunk: "CodeMirror-merge-r-chunk",
+ start: "CodeMirror-merge-r-chunk-start",
+ end: "CodeMirror-merge-r-chunk-end",
+ insert: "CodeMirror-merge-r-inserted",
+ del: "CodeMirror-merge-r-deleted",
+ connect: "CodeMirror-merge-r-connect"};
+ }
+
+ DiffView.prototype = {
+ constructor: DiffView,
+ init: function(pane, orig, options) {
+ this.edit = this.mv.edit;
+ (this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);
+ this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
+ this.orig.state.diffViews = [this];
+
+ this.diff = getDiff(asString(orig), asString(options.value));
+ this.chunks = getChunks(this.diff);
+ this.diffOutOfDate = this.dealigned = false;
+
+ this.showDifferences = options.showDifferences !== false;
+ this.forceUpdate = registerUpdate(this);
+ setScrollLock(this, true, false);
+ registerScroll(this);
+ },
+ setShowDifferences: function(val) {
+ val = val !== false;
+ if (val != this.showDifferences) {
+ this.showDifferences = val;
+ this.forceUpdate("full");
+ }
+ }
+ };
+
+ function ensureDiff(dv) {
+ if (dv.diffOutOfDate) {
+ dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
+ dv.chunks = getChunks(dv.diff);
+ dv.diffOutOfDate = false;
+ CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
+ }
+ }
+
+ var updating = false;
+ function registerUpdate(dv) {
+ var edit = {from: 0, to: 0, marked: []};
+ var orig = {from: 0, to: 0, marked: []};
+ var debounceChange, updatingFast = false;
+ function update(mode) {
+ updating = true;
+ updatingFast = false;
+ if (mode == "full") {
+ if (dv.svg) clear(dv.svg);
+ if (dv.copyButtons) clear(dv.copyButtons);
+ clearMarks(dv.edit, edit.marked, dv.classes);
+ clearMarks(dv.orig, orig.marked, dv.classes);
+ edit.from = edit.to = orig.from = orig.to = 0;
+ }
+ ensureDiff(dv);
+ if (dv.showDifferences) {
+ updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
+ updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
+ }
+ makeConnections(dv);
+
+ if (dv.mv.options.connect == "align")
+ alignChunks(dv);
+ updating = false;
+ }
+ function setDealign(fast) {
+ if (updating) return;
+ dv.dealigned = true;
+ set(fast);
+ }
+ function set(fast) {
+ if (updating || updatingFast) return;
+ clearTimeout(debounceChange);
+ if (fast === true) updatingFast = true;
+ debounceChange = setTimeout(update, fast === true ? 20 : 250);
+ }
+ function change(_cm, change) {
+ if (!dv.diffOutOfDate) {
+ dv.diffOutOfDate = true;
+ edit.from = edit.to = orig.from = orig.to = 0;
+ }
+ // Update faster when a line was added/removed
+ setDealign(change.text.length - 1 != change.to.line - change.from.line);
+ }
+ dv.edit.on("change", change);
+ dv.orig.on("change", change);
+ dv.edit.on("markerAdded", setDealign);
+ dv.edit.on("markerCleared", setDealign);
+ dv.orig.on("markerAdded", setDealign);
+ dv.orig.on("markerCleared", setDealign);
+ dv.edit.on("viewportChange", function() { set(false); });
+ dv.orig.on("viewportChange", function() { set(false); });
+ update();
+ return update;
+ }
+
+ function registerScroll(dv) {
+ dv.edit.on("scroll", function() {
+ syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
+ });
+ dv.orig.on("scroll", function() {
+ syncScroll(dv, DIFF_DELETE) && makeConnections(dv);
+ });
+ }
+
+ function syncScroll(dv, type) {
+ // Change handler will do a refresh after a timeout when diff is out of date
+ if (dv.diffOutOfDate) return false;
+ if (!dv.lockScroll) return true;
+ var editor, other, now = +new Date;
+ if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
+ else { editor = dv.orig; other = dv.edit; }
+ // Don't take action if the position of this editor was recently set
+ // (to prevent feedback loops)
+ if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
+
+ var sInfo = editor.getScrollInfo();
+ if (dv.mv.options.connect == "align") {
+ targetPos = sInfo.top;
+ } else {
+ var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
+ var mid = editor.lineAtHeight(midY, "local");
+ var around = chunkBoundariesAround(dv.chunks, mid, type == DIFF_INSERT);
+ var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
+ var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
+ var ratio = (midY - off.top) / (off.bot - off.top);
+ var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
+
+ var botDist, mix;
+ // Some careful tweaking to make sure no space is left out of view
+ // when scrolling to top or bottom.
+ if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
+ targetPos = targetPos * mix + sInfo.top * (1 - mix);
+ } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
+ var otherInfo = other.getScrollInfo();
+ var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
+ if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
+ targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
+ }
+ }
+
+ other.scrollTo(sInfo.left, targetPos);
+ other.state.scrollSetAt = now;
+ other.state.scrollSetBy = dv;
+ return true;
+ }
+
+ function getOffsets(editor, around) {
+ var bot = around.after;
+ if (bot == null) bot = editor.lastLine() + 1;
+ return {top: editor.heightAtLine(around.before || 0, "local"),
+ bot: editor.heightAtLine(bot, "local")};
+ }
+
+ function setScrollLock(dv, val, action) {
+ dv.lockScroll = val;
+ if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
+ dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db \u21da";
+ }
+
+ // Updating the marks for editor content
+
+ function clearMarks(editor, arr, classes) {
+ for (var i = 0; i < arr.length; ++i) {
+ var mark = arr[i];
+ if (mark instanceof CodeMirror.TextMarker) {
+ mark.clear();
+ } else if (mark.parent) {
+ editor.removeLineClass(mark, "background", classes.chunk);
+ editor.removeLineClass(mark, "background", classes.start);
+ editor.removeLineClass(mark, "background", classes.end);
+ }
+ }
+ arr.length = 0;
+ }
+
+ // FIXME maybe add a margin around viewport to prevent too many updates
+ function updateMarks(editor, diff, state, type, classes) {
+ var vp = editor.getViewport();
+ editor.operation(function() {
+ if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
+ clearMarks(editor, state.marked, classes);
+ markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
+ state.from = vp.from; state.to = vp.to;
+ } else {
+ if (vp.from < state.from) {
+ markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
+ state.from = vp.from;
+ }
+ if (vp.to > state.to) {
+ markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
+ state.to = vp.to;
+ }
+ }
+ });
+ }
+
+ function markChanges(editor, diff, type, marks, from, to, classes) {
+ var pos = Pos(0, 0);
+ var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
+ var cls = type == DIFF_DELETE ? classes.del : classes.insert;
+ function markChunk(start, end) {
+ var bfrom = Math.max(from, start), bto = Math.min(to, end);
+ for (var i = bfrom; i < bto; ++i) {
+ var line = editor.addLineClass(i, "background", classes.chunk);
+ if (i == start) editor.addLineClass(line, "background", classes.start);
+ if (i == end - 1) editor.addLineClass(line, "background", classes.end);
+ marks.push(line);
+ }
+ // When the chunk is empty, make sure a horizontal line shows up
+ if (start == end && bfrom == end && bto == end) {
+ if (bfrom)
+ marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
+ else
+ marks.push(editor.addLineClass(bfrom, "background", classes.start));
+ }
+ }
+
+ var chunkStart = 0;
+ for (var i = 0; i < diff.length; ++i) {
+ var part = diff[i], tp = part[0], str = part[1];
+ if (tp == DIFF_EQUAL) {
+ var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
+ moveOver(pos, str);
+ var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
+ if (cleanTo > cleanFrom) {
+ if (i) markChunk(chunkStart, cleanFrom);
+ chunkStart = cleanTo;
+ }
+ } else {
+ if (tp == type) {
+ var end = moveOver(pos, str, true);
+ var a = posMax(top, pos), b = posMin(bot, end);
+ if (!posEq(a, b))
+ marks.push(editor.markText(a, b, {className: cls}));
+ pos = end;
+ }
+ }
+ }
+ if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
+ }
+
+ // Updating the gap between editor and original
+
+ function makeConnections(dv) {
+ if (!dv.showDifferences) return;
+
+ if (dv.svg) {
+ clear(dv.svg);
+ var w = dv.gap.offsetWidth;
+ attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
+ }
+ if (dv.copyButtons) clear(dv.copyButtons);
+
+ var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
+ var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
+ for (var i = 0; i < dv.chunks.length; i++) {
+ var ch = dv.chunks[i];
+ if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
+ ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)
+ drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);
+ }
+ }
+
+ function getMatchingOrigLine(editLine, chunks) {
+ var editStart = 0, origStart = 0;
+ for (var i = 0; i < chunks.length; i++) {
+ var chunk = chunks[i];
+ if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;
+ if (chunk.editFrom > editLine) break;
+ editStart = chunk.editTo;
+ origStart = chunk.origTo;
+ }
+ return origStart + (editLine - editStart);
+ }
+
+ function findAlignedLines(dv, other) {
+ var linesToAlign = [];
+ for (var i = 0; i < dv.chunks.length; i++) {
+ var chunk = dv.chunks[i];
+ linesToAlign.push([chunk.origTo, chunk.editTo, other ? getMatchingOrigLine(chunk.editTo, other.chunks) : null]);
+ }
+ if (other) {
+ for (var i = 0; i < other.chunks.length; i++) {
+ var chunk = other.chunks[i];
+ for (var j = 0; j < linesToAlign.length; j++) {
+ var align = linesToAlign[j];
+ if (align[1] == chunk.editTo) {
+ j = -1;
+ break;
+ } else if (align[1] > chunk.editTo) {
+ break;
+ }
+ }
+ if (j > -1)
+ linesToAlign.splice(j - 1, 0, [getMatchingOrigLine(chunk.editTo, dv.chunks), chunk.editTo, chunk.origTo]);
+ }
+ }
+ return linesToAlign;
+ }
+
+ function alignChunks(dv, force) {
+ if (!dv.dealigned && !force) return;
+ if (!dv.orig.curOp) return dv.orig.operation(function() {
+ alignChunks(dv, force);
+ });
+
+ dv.dealigned = false;
+ var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;
+ if (other) {
+ ensureDiff(other);
+ other.dealigned = false;
+ }
+ var linesToAlign = findAlignedLines(dv, other);
+
+ // Clear old aligners
+ var aligners = dv.mv.aligners;
+ for (var i = 0; i < aligners.length; i++)
+ aligners[i].clear();
+ aligners.length = 0;
+
+ var cm = [dv.orig, dv.edit], scroll = [];
+ if (other) cm.push(other.orig);
+ for (var i = 0; i < cm.length; i++)
+ scroll.push(cm[i].getScrollInfo().top);
+
+ for (var ln = 0; ln < linesToAlign.length; ln++)
+ alignLines(cm, linesToAlign[ln], aligners);
+
+ for (var i = 0; i < cm.length; i++)
+ cm[i].scrollTo(null, scroll[i]);
+ }
+
+ function alignLines(cm, lines, aligners) {
+ var maxOffset = 0, offset = [];
+ for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
+ var off = cm[i].heightAtLine(lines[i], "local");
+ offset[i] = off;
+ maxOffset = Math.max(maxOffset, off);
+ }
+ for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
+ var diff = maxOffset - offset[i];
+ if (diff > 1)
+ aligners.push(padAbove(cm[i], lines[i], diff));
+ }
+ }
+
+ function padAbove(cm, line, size) {
+ var above = true;
+ if (line > cm.lastLine()) {
+ line--;
+ above = false;
+ }
+ var elt = document.createElement("div");
+ elt.className = "CodeMirror-merge-spacer";
+ elt.style.height = size + "px"; elt.style.minWidth = "1px";
+ return cm.addLineWidget(line, elt, {height: size, above: above});
+ }
+
+ function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
+ var flip = dv.type == "left";
+ var top = dv.orig.heightAtLine(chunk.origFrom, "local") - sTopOrig;
+ if (dv.svg) {
+ var topLpx = top;
+ var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
+ if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
+ var botLpx = dv.orig.heightAtLine(chunk.origTo, "local") - sTopOrig;
+ var botRpx = dv.edit.heightAtLine(chunk.editTo, "local") - sTopEdit;
+ if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
+ var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
+ var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
+ attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
+ "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
+ "class", dv.classes.connect);
+ }
+ if (dv.copyButtons) {
+ var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
+ "CodeMirror-merge-copy"));
+ var editOriginals = dv.mv.options.allowEditingOriginals;
+ copy.title = editOriginals ? "Push to left" : "Revert chunk";
+ copy.chunk = chunk;
+ copy.style.top = top + "px";
+
+ if (editOriginals) {
+ var topReverse = dv.orig.heightAtLine(chunk.editFrom, "local") - sTopEdit;
+ var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",
+ "CodeMirror-merge-copy-reverse"));
+ copyReverse.title = "Push to right";
+ copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,
+ origFrom: chunk.editFrom, origTo: chunk.editTo};
+ copyReverse.style.top = topReverse + "px";
+ dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";
+ }
+ }
+ }
+
+ function copyChunk(dv, to, from, chunk) {
+ if (dv.diffOutOfDate) return;
+ to.replaceRange(from.getRange(Pos(chunk.origFrom, 0), Pos(chunk.origTo, 0)),
+ Pos(chunk.editFrom, 0), Pos(chunk.editTo, 0));
+ }
+
+ // Merge view, containing 0, 1, or 2 diff views.
+
+ var MergeView = CodeMirror.MergeView = function(node, options) {
+ if (!(this instanceof MergeView)) return new MergeView(node, options);
+
+ this.options = options;
+ var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
+
+ var hasLeft = origLeft != null, hasRight = origRight != null;
+ var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
+ var wrap = [], left = this.left = null, right = this.right = null;
+ var self = this;
+
+ if (hasLeft) {
+ left = this.left = new DiffView(this, "left");
+ var leftPane = elt("div", null, "CodeMirror-merge-pane");
+ wrap.push(leftPane);
+ wrap.push(buildGap(left));
+ }
+
+ var editPane = elt("div", null, "CodeMirror-merge-pane");
+ wrap.push(editPane);
+
+ if (hasRight) {
+ right = this.right = new DiffView(this, "right");
+ wrap.push(buildGap(right));
+ var rightPane = elt("div", null, "CodeMirror-merge-pane");
+ wrap.push(rightPane);
+ }
+
+ (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
+
+ wrap.push(elt("div", null, null, "height: 0; clear: both;"));
+
+ var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
+ this.edit = CodeMirror(editPane, copyObj(options));
+
+ if (left) left.init(leftPane, origLeft, options);
+ if (right) right.init(rightPane, origRight, options);
+
+ if (options.collapseIdentical)
+ this.editor().operation(function() {
+ collapseIdenticalStretches(self, options.collapseIdentical);
+ });
+ if (options.connect == "align") {
+ this.aligners = [];
+ alignChunks(this.left || this.right, true);
+ }
+
+ var onResize = function() {
+ if (left) makeConnections(left);
+ if (right) makeConnections(right);
+ };
+ CodeMirror.on(window, "resize", onResize);
+ var resizeInterval = setInterval(function() {
+ for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
+ if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
+ }, 5000);
+ };
+
+ function buildGap(dv) {
+ var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
+ lock.title = "Toggle locked scrolling";
+ var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
+ CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
+ var gapElts = [lockWrap];
+ if (dv.mv.options.revertButtons !== false) {
+ dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
+ CodeMirror.on(dv.copyButtons, "click", function(e) {
+ var node = e.target || e.srcElement;
+ if (!node.chunk) return;
+ if (node.className == "CodeMirror-merge-copy-reverse") {
+ copyChunk(dv, dv.orig, dv.edit, node.chunk);
+ return;
+ }
+ copyChunk(dv, dv.edit, dv.orig, node.chunk);
+ });
+ gapElts.unshift(dv.copyButtons);
+ }
+ if (dv.mv.options.connect != "align") {
+ var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
+ if (svg && !svg.createSVGRect) svg = null;
+ dv.svg = svg;
+ if (svg) gapElts.push(svg);
+ }
+
+ return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
+ }
+
+ MergeView.prototype = {
+ constuctor: MergeView,
+ editor: function() { return this.edit; },
+ rightOriginal: function() { return this.right && this.right.orig; },
+ leftOriginal: function() { return this.left && this.left.orig; },
+ setShowDifferences: function(val) {
+ if (this.right) this.right.setShowDifferences(val);
+ if (this.left) this.left.setShowDifferences(val);
+ },
+ rightChunks: function() {
+ if (this.right) { ensureDiff(this.right); return this.right.chunks; }
+ },
+ leftChunks: function() {
+ if (this.left) { ensureDiff(this.left); return this.left.chunks; }
+ }
+ };
+
+ function asString(obj) {
+ if (typeof obj == "string") return obj;
+ else return obj.getValue();
+ }
+
+ // Operations on diffs
+
+ var dmp = new diff_match_patch();
+ function getDiff(a, b) {
+ var diff = dmp.diff_main(a, b);
+ dmp.diff_cleanupSemantic(diff);
+ // The library sometimes leaves in empty parts, which confuse the algorithm
+ for (var i = 0; i < diff.length; ++i) {
+ var part = diff[i];
+ if (!part[1]) {
+ diff.splice(i--, 1);
+ } else if (i && diff[i - 1][0] == part[0]) {
+ diff.splice(i--, 1);
+ diff[i][1] += part[1];
+ }
+ }
+ return diff;
+ }
+
+ function getChunks(diff) {
+ var chunks = [];
+ var startEdit = 0, startOrig = 0;
+ var edit = Pos(0, 0), orig = Pos(0, 0);
+ for (var i = 0; i < diff.length; ++i) {
+ var part = diff[i], tp = part[0];
+ if (tp == DIFF_EQUAL) {
+ var startOff = startOfLineClean(diff, i) ? 0 : 1;
+ var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
+ moveOver(edit, part[1], null, orig);
+ var endOff = endOfLineClean(diff, i) ? 1 : 0;
+ var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
+ if (cleanToEdit > cleanFromEdit) {
+ if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,
+ editFrom: startEdit, editTo: cleanFromEdit});
+ startEdit = cleanToEdit; startOrig = cleanToOrig;
+ }
+ } else {
+ moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
+ }
+ }
+ if (startEdit <= edit.line || startOrig <= orig.line)
+ chunks.push({origFrom: startOrig, origTo: orig.line + 1,
+ editFrom: startEdit, editTo: edit.line + 1});
+ return chunks;
+ }
+
+ function endOfLineClean(diff, i) {
+ if (i == diff.length - 1) return true;
+ var next = diff[i + 1][1];
+ if (next.length == 1 || next.charCodeAt(0) != 10) return false;
+ if (i == diff.length - 2) return true;
+ next = diff[i + 2][1];
+ return next.length > 1 && next.charCodeAt(0) == 10;
+ }
+
+ function startOfLineClean(diff, i) {
+ if (i == 0) return true;
+ var last = diff[i - 1][1];
+ if (last.charCodeAt(last.length - 1) != 10) return false;
+ if (i == 1) return true;
+ last = diff[i - 2][1];
+ return last.charCodeAt(last.length - 1) == 10;
+ }
+
+ function chunkBoundariesAround(chunks, n, nInEdit) {
+ var beforeE, afterE, beforeO, afterO;
+ for (var i = 0; i < chunks.length; i++) {
+ var chunk = chunks[i];
+ var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;
+ var toLocal = nInEdit ? chunk.editTo : chunk.origTo;
+ if (afterE == null) {
+ if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }
+ else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }
+ }
+ if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }
+ else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }
+ }
+ return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
+ }
+
+ function collapseSingle(cm, from, to) {
+ cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
+ var widget = document.createElement("span");
+ widget.className = "CodeMirror-merge-collapsed-widget";
+ widget.title = "Identical text collapsed. Click to expand.";
+ var mark = cm.markText(Pos(from, 0), Pos(to - 1), {
+ inclusiveLeft: true,
+ inclusiveRight: true,
+ replacedWith: widget,
+ clearOnEnter: true
+ });
+ function clear() {
+ mark.clear();
+ cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
+ }
+ CodeMirror.on(widget, "click", clear);
+ return {mark: mark, clear: clear};
+ }
+
+ function collapseStretch(size, editors) {
+ var marks = [];
+ function clear() {
+ for (var i = 0; i < marks.length; i++) marks[i].clear();
+ }
+ for (var i = 0; i < editors.length; i++) {
+ var editor = editors[i];
+ var mark = collapseSingle(editor.cm, editor.line, editor.line + size);
+ marks.push(mark);
+ mark.mark.on("clear", clear);
+ }
+ return marks[0].mark;
+ }
+
+ function unclearNearChunks(dv, margin, off, clear) {
+ for (var i = 0; i < dv.chunks.length; i++) {
+ var chunk = dv.chunks[i];
+ for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {
+ var pos = l + off;
+ if (pos >= 0 && pos < clear.length) clear[pos] = false;
+ }
+ }
+ }
+
+ function collapseIdenticalStretches(mv, margin) {
+ if (typeof margin != "number") margin = 2;
+ var clear = [], edit = mv.editor(), off = edit.firstLine();
+ for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);
+ if (mv.left) unclearNearChunks(mv.left, margin, off, clear);
+ if (mv.right) unclearNearChunks(mv.right, margin, off, clear);
+
+ for (var i = 0; i < clear.length; i++) {
+ if (clear[i]) {
+ var line = i + off;
+ for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}
+ if (size > margin) {
+ var editors = [{line: line, cm: edit}];
+ if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});
+ if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});
+ var mark = collapseStretch(size, editors);
+ if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);
+ }
+ }
+ }
+ }
+
+ // General 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;
+ }
+
+ function clear(node) {
+ for (var count = node.childNodes.length; count > 0; --count)
+ node.removeChild(node.firstChild);
+ }
+
+ function attrs(elt) {
+ for (var i = 1; i < arguments.length; i += 2)
+ elt.setAttribute(arguments[i], arguments[i+1]);
+ }
+
+ function copyObj(obj, target) {
+ if (!target) target = {};
+ for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
+ return target;
+ }
+
+ function moveOver(pos, str, copy, other) {
+ var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
+ for (;;) {
+ var nl = str.indexOf("\n", at);
+ if (nl == -1) break;
+ ++out.line;
+ if (other) ++other.line;
+ at = nl + 1;
+ }
+ out.ch = (at ? 0 : out.ch) + (str.length - at);
+ if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
+ return out;
+ }
+
+ function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
+ function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
+ function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
+
+ function findPrevDiff(chunks, start, isOrig) {
+ for (var i = chunks.length - 1; i >= 0; i--) {
+ var chunk = chunks[i];
+ var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;
+ if (to < start) return to;
+ }
+ }
+
+ function findNextDiff(chunks, start, isOrig) {
+ for (var i = 0; i < chunks.length; i++) {
+ var chunk = chunks[i];
+ var from = (isOrig ? chunk.origFrom : chunk.editFrom);
+ if (from > start) return from;
+ }
+ }
+
+ function goNearbyDiff(cm, dir) {
+ var found = null, views = cm.state.diffViews, line = cm.getCursor().line;
+ if (views) for (var i = 0; i < views.length; i++) {
+ var dv = views[i], isOrig = cm == dv.orig;
+ ensureDiff(dv);
+ var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);
+ if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))
+ found = pos;
+ }
+ if (found != null)
+ cm.setCursor(found, 0);
+ else
+ return CodeMirror.Pass;
+ }
+
+ CodeMirror.commands.goNextDiff = function(cm) {
+ return goNearbyDiff(cm, 1);
+ };
+ CodeMirror.commands.goPrevDiff = function(cm) {
+ return goNearbyDiff(cm, -1);
+ };
+});
diff --git a/codemirror/addon/mode/loadmode.js b/codemirror/addon/mode/loadmode.js
new file mode 100644
index 00000000..10117ec2
--- /dev/null
+++ b/codemirror/addon/mode/loadmode.js
@@ -0,0 +1,64 @@
+// 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"), "cjs");
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], function(CM) { mod(CM, "amd"); });
+ else // Plain browser env
+ mod(CodeMirror, "plain");
+})(function(CodeMirror, env) {
+ if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
+
+ var loading = {};
+ function splitCallback(cont, n) {
+ var countDown = n;
+ return function() { if (--countDown == 0) cont(); };
+ }
+ function ensureDeps(mode, cont) {
+ var deps = CodeMirror.modes[mode].dependencies;
+ if (!deps) return cont();
+ var missing = [];
+ for (var i = 0; i < deps.length; ++i) {
+ if (!CodeMirror.modes.hasOwnProperty(deps[i]))
+ missing.push(deps[i]);
+ }
+ if (!missing.length) return cont();
+ var split = splitCallback(cont, missing.length);
+ for (var i = 0; i < missing.length; ++i)
+ CodeMirror.requireMode(missing[i], split);
+ }
+
+ CodeMirror.requireMode = function(mode, cont) {
+ if (typeof mode != "string") mode = mode.name;
+ if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
+ if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
+
+ var file = CodeMirror.modeURL.replace(/%N/g, mode);
+ if (env == "plain") {
+ var script = document.createElement("script");
+ script.src = file;
+ var others = document.getElementsByTagName("script")[0];
+ var list = loading[mode] = [cont];
+ CodeMirror.on(script, "load", function() {
+ ensureDeps(mode, function() {
+ for (var i = 0; i < list.length; ++i) list[i]();
+ });
+ });
+ others.parentNode.insertBefore(script, others);
+ } else if (env == "cjs") {
+ require(file);
+ cont();
+ } else if (env == "amd") {
+ requirejs([file], cont);
+ }
+ };
+
+ CodeMirror.autoLoadMode = function(instance, mode) {
+ if (!CodeMirror.modes.hasOwnProperty(mode))
+ CodeMirror.requireMode(mode, function() {
+ instance.setOption("mode", instance.getOption("mode"));
+ });
+ };
+});
diff --git a/codemirror/addon/mode/multiplex.js b/codemirror/addon/mode/multiplex.js
new file mode 100644
index 00000000..3d8b34c4
--- /dev/null
+++ b/codemirror/addon/mode/multiplex.js
@@ -0,0 +1,123 @@
+// 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.multiplexingMode = function(outer /*, others */) {
+ // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
+ var others = Array.prototype.slice.call(arguments, 1);
+
+ function indexOf(string, pattern, from, returnEnd) {
+ if (typeof pattern == "string") {
+ var found = string.indexOf(pattern, from);
+ return returnEnd && found > -1 ? found + pattern.length : found;
+ }
+ var m = pattern.exec(from ? string.slice(from) : string);
+ return m ? m.index + from + (returnEnd ? m[0].length : 0) : -1;
+ }
+
+ return {
+ startState: function() {
+ return {
+ outer: CodeMirror.startState(outer),
+ innerActive: null,
+ inner: null
+ };
+ },
+
+ copyState: function(state) {
+ return {
+ outer: CodeMirror.copyState(outer, state.outer),
+ innerActive: state.innerActive,
+ inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
+ };
+ },
+
+ token: function(stream, state) {
+ if (!state.innerActive) {
+ var cutOff = Infinity, oldContent = stream.string;
+ for (var i = 0; i < others.length; ++i) {
+ var other = others[i];
+ var found = indexOf(oldContent, other.open, stream.pos);
+ if (found == stream.pos) {
+ if (!other.parseDelimiters) stream.match(other.open);
+ state.innerActive = other;
+ state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
+ return other.delimStyle && (other.delimStyle + " " + other.delimStyle + "-open");
+ } else if (found != -1 && found < cutOff) {
+ cutOff = found;
+ }
+ }
+ if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
+ var outerToken = outer.token(stream, state.outer);
+ if (cutOff != Infinity) stream.string = oldContent;
+ return outerToken;
+ } else {
+ var curInner = state.innerActive, oldContent = stream.string;
+ if (!curInner.close && stream.sol()) {
+ state.innerActive = state.inner = null;
+ return this.token(stream, state);
+ }
+ var found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos, curInner.parseDelimiters) : -1;
+ if (found == stream.pos && !curInner.parseDelimiters) {
+ stream.match(curInner.close);
+ state.innerActive = state.inner = null;
+ return curInner.delimStyle && (curInner.delimStyle + " " + curInner.delimStyle + "-close");
+ }
+ if (found > -1) stream.string = oldContent.slice(0, found);
+ var innerToken = curInner.mode.token(stream, state.inner);
+ if (found > -1) stream.string = oldContent;
+
+ if (found == stream.pos && curInner.parseDelimiters)
+ state.innerActive = state.inner = null;
+
+ if (curInner.innerStyle) {
+ if (innerToken) innerToken = innerToken + " " + curInner.innerStyle;
+ else innerToken = curInner.innerStyle;
+ }
+
+ return innerToken;
+ }
+ },
+
+ indent: function(state, textAfter) {
+ var mode = state.innerActive ? state.innerActive.mode : outer;
+ if (!mode.indent) return CodeMirror.Pass;
+ return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
+ },
+
+ blankLine: function(state) {
+ var mode = state.innerActive ? state.innerActive.mode : outer;
+ if (mode.blankLine) {
+ mode.blankLine(state.innerActive ? state.inner : state.outer);
+ }
+ if (!state.innerActive) {
+ for (var i = 0; i < others.length; ++i) {
+ var other = others[i];
+ if (other.open === "\n") {
+ state.innerActive = other;
+ state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
+ }
+ }
+ } else if (state.innerActive.close === "\n") {
+ state.innerActive = state.inner = null;
+ }
+ },
+
+ electricChars: outer.electricChars,
+
+ innerMode: function(state) {
+ return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
+ }
+ };
+};
+
+});
diff --git a/codemirror/addon/mode/multiplex_test.js b/codemirror/addon/mode/multiplex_test.js
new file mode 100644
index 00000000..24e5e670
--- /dev/null
+++ b/codemirror/addon/mode/multiplex_test.js
@@ -0,0 +1,33 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function() {
+ CodeMirror.defineMode("markdown_with_stex", function(){
+ var inner = CodeMirror.getMode({}, "stex");
+ var outer = CodeMirror.getMode({}, "markdown");
+
+ var innerOptions = {
+ open: '$',
+ close: '$',
+ mode: inner,
+ delimStyle: 'delim',
+ innerStyle: 'inner'
+ };
+
+ return CodeMirror.multiplexingMode(outer, innerOptions);
+ });
+
+ var mode = CodeMirror.getMode({}, "markdown_with_stex");
+
+ function MT(name) {
+ test.mode(
+ name,
+ mode,
+ Array.prototype.slice.call(arguments, 1),
+ 'multiplexing');
+ }
+
+ MT(
+ "stexInsideMarkdown",
+ "[strong **Equation:**] [delim&delim-open $][inner&tag \\pi][delim&delim-close $]");
+})();
diff --git a/codemirror/addon/mode/overlay.js b/codemirror/addon/mode/overlay.js
new file mode 100644
index 00000000..e1b9ed37
--- /dev/null
+++ b/codemirror/addon/mode/overlay.js
@@ -0,0 +1,85 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Utility function that allows modes to be combined. The mode given
+// as the base argument takes care of most of the normal mode
+// functionality, but a second (typically simple) mode is used, which
+// can override the style of text. Both modes get to parse all of the
+// text, but when both assign a non-null style to a piece of code, the
+// overlay wins, unless the combine argument was true and not overridden,
+// or state.overlay.combineTokens was true, in which case the styles are
+// combined.
+
+(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.overlayMode = function(base, overlay, combine) {
+ return {
+ startState: function() {
+ return {
+ base: CodeMirror.startState(base),
+ overlay: CodeMirror.startState(overlay),
+ basePos: 0, baseCur: null,
+ overlayPos: 0, overlayCur: null,
+ streamSeen: null
+ };
+ },
+ copyState: function(state) {
+ return {
+ base: CodeMirror.copyState(base, state.base),
+ overlay: CodeMirror.copyState(overlay, state.overlay),
+ basePos: state.basePos, baseCur: null,
+ overlayPos: state.overlayPos, overlayCur: null
+ };
+ },
+
+ token: function(stream, state) {
+ if (stream != state.streamSeen ||
+ Math.min(state.basePos, state.overlayPos) < stream.start) {
+ state.streamSeen = stream;
+ state.basePos = state.overlayPos = stream.start;
+ }
+
+ if (stream.start == state.basePos) {
+ state.baseCur = base.token(stream, state.base);
+ state.basePos = stream.pos;
+ }
+ if (stream.start == state.overlayPos) {
+ stream.pos = stream.start;
+ state.overlayCur = overlay.token(stream, state.overlay);
+ state.overlayPos = stream.pos;
+ }
+ stream.pos = Math.min(state.basePos, state.overlayPos);
+
+ // state.overlay.combineTokens always takes precedence over combine,
+ // unless set to null
+ if (state.overlayCur == null) return state.baseCur;
+ else if (state.baseCur != null &&
+ state.overlay.combineTokens ||
+ combine && state.overlay.combineTokens == null)
+ return state.baseCur + " " + state.overlayCur;
+ else return state.overlayCur;
+ },
+
+ indent: base.indent && function(state, textAfter) {
+ return base.indent(state.base, textAfter);
+ },
+ electricChars: base.electricChars,
+
+ innerMode: function(state) { return {state: state.base, mode: base}; },
+
+ blankLine: function(state) {
+ if (base.blankLine) base.blankLine(state.base);
+ if (overlay.blankLine) overlay.blankLine(state.overlay);
+ }
+ };
+};
+
+});
diff --git a/codemirror/addon/mode/simple.js b/codemirror/addon/mode/simple.js
new file mode 100644
index 00000000..df663365
--- /dev/null
+++ b/codemirror/addon/mode/simple.js
@@ -0,0 +1,213 @@
+// 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.defineSimpleMode = function(name, states) {
+ CodeMirror.defineMode(name, function(config) {
+ return CodeMirror.simpleMode(config, states);
+ });
+ };
+
+ CodeMirror.simpleMode = function(config, states) {
+ ensureState(states, "start");
+ var states_ = {}, meta = states.meta || {}, hasIndentation = false;
+ for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
+ var list = states_[state] = [], orig = states[state];
+ for (var i = 0; i < orig.length; i++) {
+ var data = orig[i];
+ list.push(new Rule(data, states));
+ if (data.indent || data.dedent) hasIndentation = true;
+ }
+ }
+ var mode = {
+ startState: function() {
+ return {state: "start", pending: null,
+ local: null, localState: null,
+ indent: hasIndentation ? [] : null};
+ },
+ copyState: function(state) {
+ var s = {state: state.state, pending: state.pending,
+ local: state.local, localState: null,
+ indent: state.indent && state.indent.slice(0)};
+ if (state.localState)
+ s.localState = CodeMirror.copyState(state.local.mode, state.localState);
+ if (state.stack)
+ s.stack = state.stack.slice(0);
+ for (var pers = state.persistentStates; pers; pers = pers.next)
+ s.persistentStates = {mode: pers.mode,
+ spec: pers.spec,
+ state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
+ next: s.persistentStates};
+ return s;
+ },
+ token: tokenFunction(states_, config),
+ innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
+ indent: indentFunction(states_, meta)
+ };
+ if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
+ mode[prop] = meta[prop];
+ return mode;
+ };
+
+ function ensureState(states, name) {
+ if (!states.hasOwnProperty(name))
+ throw new Error("Undefined state " + name + " in simple mode");
+ }
+
+ function toRegex(val, caret) {
+ if (!val) return /(?:)/;
+ var flags = "";
+ if (val instanceof RegExp) {
+ if (val.ignoreCase) flags = "i";
+ val = val.source;
+ } else {
+ val = String(val);
+ }
+ return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
+ }
+
+ function asToken(val) {
+ if (!val) return null;
+ if (typeof val == "string") return val.replace(/\./g, " ");
+ var result = [];
+ for (var i = 0; i < val.length; i++)
+ result.push(val[i] && val[i].replace(/\./g, " "));
+ return result;
+ }
+
+ function Rule(data, states) {
+ if (data.next || data.push) ensureState(states, data.next || data.push);
+ this.regex = toRegex(data.regex);
+ this.token = asToken(data.token);
+ this.data = data;
+ }
+
+ function tokenFunction(states, config) {
+ return function(stream, state) {
+ if (state.pending) {
+ var pend = state.pending.shift();
+ if (state.pending.length == 0) state.pending = null;
+ stream.pos += pend.text.length;
+ return pend.token;
+ }
+
+ if (state.local) {
+ if (state.local.end && stream.match(state.local.end)) {
+ var tok = state.local.endToken || null;
+ state.local = state.localState = null;
+ return tok;
+ } else {
+ var tok = state.local.mode.token(stream, state.localState), m;
+ if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
+ stream.pos = stream.start + m.index;
+ return tok;
+ }
+ }
+
+ var curState = states[state.state];
+ for (var i = 0; i < curState.length; i++) {
+ var rule = curState[i];
+ var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
+ if (matches) {
+ if (rule.data.next) {
+ state.state = rule.data.next;
+ } else if (rule.data.push) {
+ (state.stack || (state.stack = [])).push(state.state);
+ state.state = rule.data.push;
+ } else if (rule.data.pop && state.stack && state.stack.length) {
+ state.state = state.stack.pop();
+ }
+
+ if (rule.data.mode)
+ enterLocalMode(config, state, rule.data.mode, rule.token);
+ if (rule.data.indent)
+ state.indent.push(stream.indentation() + config.indentUnit);
+ if (rule.data.dedent)
+ state.indent.pop();
+ if (matches.length > 2) {
+ state.pending = [];
+ for (var j = 2; j < matches.length; j++)
+ if (matches[j])
+ state.pending.push({text: matches[j], token: rule.token[j - 1]});
+ stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
+ return rule.token[0];
+ } else if (rule.token && rule.token.join) {
+ return rule.token[0];
+ } else {
+ return rule.token;
+ }
+ }
+ }
+ stream.next();
+ return null;
+ };
+ }
+
+ function cmp(a, b) {
+ if (a === b) return true;
+ if (!a || typeof a != "object" || !b || typeof b != "object") return false;
+ var props = 0;
+ for (var prop in a) if (a.hasOwnProperty(prop)) {
+ if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
+ props++;
+ }
+ for (var prop in b) if (b.hasOwnProperty(prop)) props--;
+ return props == 0;
+ }
+
+ function enterLocalMode(config, state, spec, token) {
+ var pers;
+ if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
+ if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
+ var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
+ var lState = pers ? pers.state : CodeMirror.startState(mode);
+ if (spec.persistent && !pers)
+ state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};
+
+ state.localState = lState;
+ state.local = {mode: mode,
+ end: spec.end && toRegex(spec.end),
+ endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
+ endToken: token && token.join ? token[token.length - 1] : token};
+ }
+
+ function indexOf(val, arr) {
+ for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
+ }
+
+ function indentFunction(states, meta) {
+ return function(state, textAfter, line) {
+ if (state.local && state.local.mode.indent)
+ return state.local.mode.indent(state.localState, textAfter, line);
+ if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
+ return CodeMirror.Pass;
+
+ var pos = state.indent.length - 1, rules = states[state.state];
+ scan: for (;;) {
+ for (var i = 0; i < rules.length; i++) {
+ var rule = rules[i];
+ if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
+ var m = rule.regex.exec(textAfter);
+ if (m && m[0]) {
+ pos--;
+ if (rule.next || rule.push) rules = states[rule.next || rule.push];
+ textAfter = textAfter.slice(m[0].length);
+ continue scan;
+ }
+ }
+ }
+ break;
+ }
+ return pos < 0 ? 0 : state.indent[pos];
+ };
+ }
+});
diff --git a/codemirror/addon/runmode/colorize.js b/codemirror/addon/runmode/colorize.js
new file mode 100644
index 00000000..eb7060d0
--- /dev/null
+++ b/codemirror/addon/runmode/colorize.js
@@ -0,0 +1,40 @@
+// 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"), require("./runmode"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./runmode"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/;
+
+ function textContent(node, out) {
+ if (node.nodeType == 3) return out.push(node.nodeValue);
+ for (var ch = node.firstChild; ch; ch = ch.nextSibling) {
+ textContent(ch, out);
+ if (isBlock.test(node.nodeType)) out.push("\n");
+ }
+ }
+
+ CodeMirror.colorize = function(collection, defaultMode) {
+ if (!collection) collection = document.body.getElementsByTagName("pre");
+
+ for (var i = 0; i < collection.length; ++i) {
+ var node = collection[i];
+ var mode = node.getAttribute("data-lang") || defaultMode;
+ if (!mode) continue;
+
+ var text = [];
+ textContent(node, text);
+ node.innerHTML = "";
+ CodeMirror.runMode(text.join(""), mode, node);
+
+ node.className += " cm-s-default";
+ }
+ };
+});
diff --git a/codemirror/addon/runmode/runmode-standalone.js b/codemirror/addon/runmode/runmode-standalone.js
new file mode 100644
index 00000000..f4f352c8
--- /dev/null
+++ b/codemirror/addon/runmode/runmode-standalone.js
@@ -0,0 +1,157 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+window.CodeMirror = {};
+
+(function() {
+"use strict";
+
+function splitLines(string){ return string.split(/\r?\n|\r/); };
+
+function StringStream(string) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.lineStart = 0;
+}
+StringStream.prototype = {
+ eol: function() {return this.pos >= this.string.length;},
+ sol: function() {return this.pos == 0;},
+ peek: function() {return this.string.charAt(this.pos) || null;},
+ 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() {return this.start - this.lineStart;},
+ indentation: function() {return 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; }
+ }
+};
+CodeMirror.StringStream = StringStream;
+
+CodeMirror.startState = function (mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true;
+};
+
+var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+CodeMirror.defineMode = function (name, mode) {
+ if (arguments.length > 2)
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
+ modes[name] = mode;
+};
+CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
+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)) {
+ spec = mimeModes[spec.name];
+ }
+ if (typeof spec == "string") return {name: spec};
+ else return spec || {name: "null"};
+};
+CodeMirror.getMode = function (options, spec) {
+ spec = CodeMirror.resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) throw new Error("Unknown mode: " + spec);
+ return mfactory(options, spec);
+};
+CodeMirror.registerHelper = CodeMirror.registerGlobalHelper = Math.min;
+CodeMirror.defineMode("null", function() {
+ return {token: function(stream) {stream.skipToEnd();}};
+});
+CodeMirror.defineMIME("text/plain", "null");
+
+CodeMirror.runMode = function (string, modespec, callback, options) {
+ var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
+
+ if (callback.nodeType == 1) {
+ var tabSize = (options && options.tabSize) || 4;
+ var node = callback, col = 0;
+ node.innerHTML = "";
+ callback = function (text, style) {
+ if (text == "\n") {
+ node.appendChild(document.createElement("br"));
+ col = 0;
+ return;
+ }
+ var content = "";
+ // replace tabs
+ for (var pos = 0; ;) {
+ var idx = text.indexOf("\t", pos);
+ if (idx == -1) {
+ content += text.slice(pos);
+ col += text.length - pos;
+ break;
+ } else {
+ col += idx - pos;
+ content += text.slice(pos, idx);
+ var size = tabSize - col % tabSize;
+ col += size;
+ for (var i = 0; i < size; ++i) content += " ";
+ pos = idx + 1;
+ }
+ }
+
+ if (style) {
+ var sp = node.appendChild(document.createElement("span"));
+ sp.className = "cm-" + style.replace(/ +/g, " cm-");
+ sp.appendChild(document.createTextNode(content));
+ } else {
+ node.appendChild(document.createTextNode(content));
+ }
+ };
+ }
+
+ var lines = splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
+ for (var i = 0, e = lines.length; i < e; ++i) {
+ if (i) callback("\n");
+ var stream = new CodeMirror.StringStream(lines[i]);
+ if (!stream.string && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state);
+ callback(stream.current(), style, i, stream.start, state);
+ stream.start = stream.pos;
+ }
+ }
+};
+})();
diff --git a/codemirror/addon/runmode/runmode.js b/codemirror/addon/runmode/runmode.js
new file mode 100644
index 00000000..a51c6d0d
--- /dev/null
+++ b/codemirror/addon/runmode/runmode.js
@@ -0,0 +1,72 @@
+// 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.runMode = function(string, modespec, callback, options) {
+ var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
+ var ie = /MSIE \d/.test(navigator.userAgent);
+ var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
+
+ if (callback.appendChild) {
+ var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
+ var node = callback, col = 0;
+ node.innerHTML = "";
+ callback = function(text, style) {
+ if (text == "\n") {
+ // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
+ // Emitting a carriage return makes everything ok.
+ node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
+ col = 0;
+ return;
+ }
+ var content = "";
+ // replace tabs
+ for (var pos = 0;;) {
+ var idx = text.indexOf("\t", pos);
+ if (idx == -1) {
+ content += text.slice(pos);
+ col += text.length - pos;
+ break;
+ } else {
+ col += idx - pos;
+ content += text.slice(pos, idx);
+ var size = tabSize - col % tabSize;
+ col += size;
+ for (var i = 0; i < size; ++i) content += " ";
+ pos = idx + 1;
+ }
+ }
+
+ if (style) {
+ var sp = node.appendChild(document.createElement("span"));
+ sp.className = "cm-" + style.replace(/ +/g, " cm-");
+ sp.appendChild(document.createTextNode(content));
+ } else {
+ node.appendChild(document.createTextNode(content));
+ }
+ };
+ }
+
+ var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
+ for (var i = 0, e = lines.length; i < e; ++i) {
+ if (i) callback("\n");
+ var stream = new CodeMirror.StringStream(lines[i]);
+ if (!stream.string && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state);
+ callback(stream.current(), style, i, stream.start, state);
+ stream.start = stream.pos;
+ }
+ }
+};
+
+});
diff --git a/codemirror/addon/runmode/runmode.node.js b/codemirror/addon/runmode/runmode.node.js
new file mode 100644
index 00000000..b22a5187
--- /dev/null
+++ b/codemirror/addon/runmode/runmode.node.js
@@ -0,0 +1,179 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+/* Just enough of CodeMirror to run runMode under node.js */
+
+function splitLines(string){return string.split(/\r\n?|\n/);};
+
+// Counts the column offset in a string, taking tabs into account.
+// Used mostly to find indentation.
+var 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;
+ }
+};
+
+function StringStream(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; }
+ }
+};
+exports.StringStream = StringStream;
+
+exports.startState = function(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true;
+};
+
+var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
+exports.defineMode = function(name, mode) {
+ if (arguments.length > 2)
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
+ modes[name] = mode;
+};
+exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
+
+exports.defineMode("null", function() {
+ return {token: function(stream) {stream.skipToEnd();}};
+});
+exports.defineMIME("text/plain", "null");
+
+exports.resolveMode = function(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ spec = mimeModes[spec.name];
+ }
+ if (typeof spec == "string") return {name: spec};
+ else return spec || {name: "null"};
+};
+
+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;
+}
+
+// This can be used to attach properties to mode objects from
+// outside the actual mode definition.
+var modeExtensions = exports.modeExtensions = {};
+exports.extendMode = function(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+};
+
+exports.getMode = function(options, spec) {
+ var spec = exports.resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) return exports.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;
+};
+exports.registerHelper = exports.registerGlobalHelper = Math.min;
+
+exports.runMode = function(string, modespec, callback, options) {
+ var mode = exports.getMode({indentUnit: 2}, modespec);
+ var lines = splitLines(string), state = (options && options.state) || exports.startState(mode);
+ for (var i = 0, e = lines.length; i < e; ++i) {
+ if (i) callback("\n");
+ var stream = new exports.StringStream(lines[i]);
+ if (!stream.string && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state);
+ callback(stream.current(), style, i, stream.start, state);
+ stream.start = stream.pos;
+ }
+ }
+};
+
+require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")];
+require.cache[require.resolve("../../addon/runmode/runmode")] = require.cache[require.resolve("./runmode.node")];
diff --git a/codemirror/addon/scroll/annotatescrollbar.js b/codemirror/addon/scroll/annotatescrollbar.js
new file mode 100644
index 00000000..5e748e81
--- /dev/null
+++ b/codemirror/addon/scroll/annotatescrollbar.js
@@ -0,0 +1,118 @@
+// 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.defineExtension("annotateScrollbar", function(options) {
+ if (typeof options == "string") options = {className: options};
+ return new Annotation(this, options);
+ });
+
+ CodeMirror.defineOption("scrollButtonHeight", 0);
+
+ function Annotation(cm, options) {
+ this.cm = cm;
+ this.options = options;
+ this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight");
+ this.annotations = [];
+ this.doRedraw = this.doUpdate = null;
+ this.div = cm.getWrapperElement().appendChild(document.createElement("div"));
+ this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none";
+ this.computeScale();
+
+ function scheduleRedraw(delay) {
+ clearTimeout(self.doRedraw);
+ self.doRedraw = setTimeout(function() { self.redraw(); }, delay);
+ }
+
+ var self = this;
+ cm.on("refresh", this.resizeHandler = function() {
+ clearTimeout(self.doUpdate);
+ self.doUpdate = setTimeout(function() {
+ if (self.computeScale()) scheduleRedraw(20);
+ }, 100);
+ });
+ cm.on("markerAdded", this.resizeHandler);
+ cm.on("markerCleared", this.resizeHandler);
+ if (options.listenForChanges !== false)
+ cm.on("change", this.changeHandler = function() {
+ scheduleRedraw(250);
+ });
+ }
+
+ Annotation.prototype.computeScale = function() {
+ var cm = this.cm;
+ var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) /
+ cm.getScrollerElement().scrollHeight
+ if (hScale != this.hScale) {
+ this.hScale = hScale;
+ return true;
+ }
+ };
+
+ Annotation.prototype.update = function(annotations) {
+ this.annotations = annotations;
+ this.redraw();
+ };
+
+ Annotation.prototype.redraw = function(compute) {
+ if (compute !== false) this.computeScale();
+ var cm = this.cm, hScale = this.hScale;
+
+ var frag = document.createDocumentFragment(), anns = this.annotations;
+
+ var wrapping = cm.getOption("lineWrapping");
+ var singleLineH = wrapping && cm.defaultTextHeight() * 1.5;
+ var curLine = null, curLineObj = null;
+ function getY(pos, top) {
+ if (curLine != pos.line) {
+ curLine = pos.line;
+ curLineObj = cm.getLineHandle(curLine);
+ }
+ if (wrapping && curLineObj.height > singleLineH)
+ return cm.charCoords(pos, "local")[top ? "top" : "bottom"];
+ var topY = cm.heightAtLine(curLineObj, "local");
+ return topY + (top ? 0 : curLineObj.height);
+ }
+
+ if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) {
+ var ann = anns[i];
+ var top = nextTop || getY(ann.from, true) * hScale;
+ var bottom = getY(ann.to, false) * hScale;
+ while (i < anns.length - 1) {
+ nextTop = getY(anns[i + 1].from, true) * hScale;
+ if (nextTop > bottom + .9) break;
+ ann = anns[++i];
+ bottom = getY(ann.to, false) * hScale;
+ }
+ if (bottom == top) continue;
+ var height = Math.max(bottom - top, 3);
+
+ var elt = frag.appendChild(document.createElement("div"));
+ elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: "
+ + (top + this.buttonHeight) + "px; height: " + height + "px";
+ elt.className = this.options.className;
+ if (ann.id) {
+ elt.setAttribute("annotation-id", ann.id);
+ }
+ }
+ this.div.textContent = "";
+ this.div.appendChild(frag);
+ };
+
+ Annotation.prototype.clear = function() {
+ this.cm.off("refresh", this.resizeHandler);
+ this.cm.off("markerAdded", this.resizeHandler);
+ this.cm.off("markerCleared", this.resizeHandler);
+ if (this.changeHandler) this.cm.off("change", this.changeHandler);
+ this.div.parentNode.removeChild(this.div);
+ };
+});
diff --git a/codemirror/addon/scroll/scrollpastend.js b/codemirror/addon/scroll/scrollpastend.js
new file mode 100644
index 00000000..008ae4c7
--- /dev/null
+++ b/codemirror/addon/scroll/scrollpastend.js
@@ -0,0 +1,46 @@
+// 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.defineOption("scrollPastEnd", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.off("change", onChange);
+ cm.off("refresh", updateBottomMargin);
+ cm.display.lineSpace.parentNode.style.paddingBottom = "";
+ cm.state.scrollPastEndPadding = null;
+ }
+ if (val) {
+ cm.on("change", onChange);
+ cm.on("refresh", updateBottomMargin);
+ updateBottomMargin(cm);
+ }
+ });
+
+ function onChange(cm, change) {
+ if (CodeMirror.changeEnd(change).line == cm.lastLine())
+ updateBottomMargin(cm);
+ }
+
+ function updateBottomMargin(cm) {
+ var padding = "";
+ if (cm.lineCount() > 1) {
+ var totalH = cm.display.scroller.clientHeight - 30,
+ lastLineH = cm.getLineHandle(cm.lastLine()).height;
+ padding = (totalH - lastLineH) + "px";
+ }
+ if (cm.state.scrollPastEndPadding != padding) {
+ cm.state.scrollPastEndPadding = padding;
+ cm.display.lineSpace.parentNode.style.paddingBottom = padding;
+ cm.setSize();
+ }
+ }
+});
diff --git a/codemirror/addon/scroll/simplescrollbars.css b/codemirror/addon/scroll/simplescrollbars.css
new file mode 100644
index 00000000..5eea7aa1
--- /dev/null
+++ b/codemirror/addon/scroll/simplescrollbars.css
@@ -0,0 +1,66 @@
+.CodeMirror-simplescroll-horizontal div, .CodeMirror-simplescroll-vertical div {
+ position: absolute;
+ background: #ccc;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ border: 1px solid #bbb;
+ border-radius: 2px;
+}
+
+.CodeMirror-simplescroll-horizontal, .CodeMirror-simplescroll-vertical {
+ position: absolute;
+ z-index: 6;
+ background: #eee;
+}
+
+.CodeMirror-simplescroll-horizontal {
+ bottom: 0; left: 0;
+ height: 8px;
+}
+.CodeMirror-simplescroll-horizontal div {
+ bottom: 0;
+ height: 100%;
+}
+
+.CodeMirror-simplescroll-vertical {
+ right: 0; top: 0;
+ width: 8px;
+}
+.CodeMirror-simplescroll-vertical div {
+ right: 0;
+ width: 100%;
+}
+
+
+.CodeMirror-overlayscroll .CodeMirror-scrollbar-filler, .CodeMirror-overlayscroll .CodeMirror-gutter-filler {
+ display: none;
+}
+
+.CodeMirror-overlayscroll-horizontal div, .CodeMirror-overlayscroll-vertical div {
+ position: absolute;
+ background: #bcd;
+ border-radius: 3px;
+}
+
+.CodeMirror-overlayscroll-horizontal, .CodeMirror-overlayscroll-vertical {
+ position: absolute;
+ z-index: 6;
+}
+
+.CodeMirror-overlayscroll-horizontal {
+ bottom: 0; left: 0;
+ height: 6px;
+}
+.CodeMirror-overlayscroll-horizontal div {
+ bottom: 0;
+ height: 100%;
+}
+
+.CodeMirror-overlayscroll-vertical {
+ right: 0; top: 0;
+ width: 6px;
+}
+.CodeMirror-overlayscroll-vertical div {
+ right: 0;
+ width: 100%;
+}
diff --git a/codemirror/addon/scroll/simplescrollbars.js b/codemirror/addon/scroll/simplescrollbars.js
new file mode 100644
index 00000000..f78353a1
--- /dev/null
+++ b/codemirror/addon/scroll/simplescrollbars.js
@@ -0,0 +1,147 @@
+// 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";
+
+ function Bar(cls, orientation, scroll) {
+ this.orientation = orientation;
+ this.scroll = scroll;
+ this.screen = this.total = this.size = 1;
+ this.pos = 0;
+
+ this.node = document.createElement("div");
+ this.node.className = cls + "-" + orientation;
+ this.inner = this.node.appendChild(document.createElement("div"));
+
+ var self = this;
+ CodeMirror.on(this.inner, "mousedown", function(e) {
+ if (e.which != 1) return;
+ CodeMirror.e_preventDefault(e);
+ var axis = self.orientation == "horizontal" ? "pageX" : "pageY";
+ var start = e[axis], startpos = self.pos;
+ function done() {
+ CodeMirror.off(document, "mousemove", move);
+ CodeMirror.off(document, "mouseup", done);
+ }
+ function move(e) {
+ if (e.which != 1) return done();
+ self.moveTo(startpos + (e[axis] - start) * (self.total / self.size));
+ }
+ CodeMirror.on(document, "mousemove", move);
+ CodeMirror.on(document, "mouseup", done);
+ });
+
+ CodeMirror.on(this.node, "click", function(e) {
+ CodeMirror.e_preventDefault(e);
+ var innerBox = self.inner.getBoundingClientRect(), where;
+ if (self.orientation == "horizontal")
+ where = e.clientX < innerBox.left ? -1 : e.clientX > innerBox.right ? 1 : 0;
+ else
+ where = e.clientY < innerBox.top ? -1 : e.clientY > innerBox.bottom ? 1 : 0;
+ self.moveTo(self.pos + where * self.screen);
+ });
+
+ function onWheel(e) {
+ var moved = CodeMirror.wheelEventPixels(e)[self.orientation == "horizontal" ? "x" : "y"];
+ var oldPos = self.pos;
+ self.moveTo(self.pos + moved);
+ if (self.pos != oldPos) CodeMirror.e_preventDefault(e);
+ }
+ CodeMirror.on(this.node, "mousewheel", onWheel);
+ CodeMirror.on(this.node, "DOMMouseScroll", onWheel);
+ }
+
+ Bar.prototype.moveTo = function(pos, update) {
+ if (pos < 0) pos = 0;
+ if (pos > this.total - this.screen) pos = this.total - this.screen;
+ if (pos == this.pos) return;
+ this.pos = pos;
+ this.inner.style[this.orientation == "horizontal" ? "left" : "top"] =
+ (pos * (this.size / this.total)) + "px";
+ if (update !== false) this.scroll(pos, this.orientation);
+ };
+
+ var minButtonSize = 10;
+
+ Bar.prototype.update = function(scrollSize, clientSize, barSize) {
+ this.screen = clientSize;
+ this.total = scrollSize;
+ this.size = barSize;
+
+ var buttonSize = this.screen * (this.size / this.total);
+ if (buttonSize < minButtonSize) {
+ this.size -= minButtonSize - buttonSize;
+ buttonSize = minButtonSize;
+ }
+ this.inner.style[this.orientation == "horizontal" ? "width" : "height"] =
+ buttonSize + "px";
+ this.inner.style[this.orientation == "horizontal" ? "left" : "top"] =
+ this.pos * (this.size / this.total) + "px";
+ };
+
+ function SimpleScrollbars(cls, place, scroll) {
+ this.addClass = cls;
+ this.horiz = new Bar(cls, "horizontal", scroll);
+ place(this.horiz.node);
+ this.vert = new Bar(cls, "vertical", scroll);
+ place(this.vert.node);
+ this.width = null;
+ }
+
+ SimpleScrollbars.prototype.update = function(measure) {
+ if (this.width == null) {
+ var style = window.getComputedStyle ? window.getComputedStyle(this.horiz.node) : this.horiz.node.currentStyle;
+ if (style) this.width = parseInt(style.height);
+ }
+ var width = this.width || 0;
+
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
+ this.vert.node.style.display = needsV ? "block" : "none";
+ this.horiz.node.style.display = needsH ? "block" : "none";
+
+ if (needsV) {
+ this.vert.update(measure.scrollHeight, measure.clientHeight,
+ measure.viewHeight - (needsH ? width : 0));
+ this.vert.node.style.display = "block";
+ this.vert.node.style.bottom = needsH ? width + "px" : "0";
+ }
+ if (needsH) {
+ this.horiz.update(measure.scrollWidth, measure.clientWidth,
+ measure.viewWidth - (needsV ? width : 0) - measure.barLeft);
+ this.horiz.node.style.right = needsV ? width + "px" : "0";
+ this.horiz.node.style.left = measure.barLeft + "px";
+ }
+
+ return {right: needsV ? width : 0, bottom: needsH ? width : 0};
+ };
+
+ SimpleScrollbars.prototype.setScrollTop = function(pos) {
+ this.vert.moveTo(pos, false);
+ };
+
+ SimpleScrollbars.prototype.setScrollLeft = function(pos) {
+ this.horiz.moveTo(pos, false);
+ };
+
+ SimpleScrollbars.prototype.clear = function() {
+ var parent = this.horiz.node.parentNode;
+ parent.removeChild(this.horiz.node);
+ parent.removeChild(this.vert.node);
+ };
+
+ CodeMirror.scrollbarModel.simple = function(place, scroll) {
+ return new SimpleScrollbars("CodeMirror-simplescroll", place, scroll);
+ };
+ CodeMirror.scrollbarModel.overlay = function(place, scroll) {
+ return new SimpleScrollbars("CodeMirror-overlayscroll", place, scroll);
+ };
+});
diff --git a/codemirror/addon/search/jump-to-line.js b/codemirror/addon/search/jump-to-line.js
new file mode 100644
index 00000000..8b599cbc
--- /dev/null
+++ b/codemirror/addon/search/jump-to-line.js
@@ -0,0 +1,49 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Defines jumpToLine command. Uses dialog.js if present.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"), require("../dialog/dialog"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../dialog/dialog"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ function dialog(cm, text, shortText, deflt, f) {
+ if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
+ else f(prompt(shortText, deflt));
+ }
+
+ var jumpDialog =
+ 'Jump to line: (Use line:column or scroll% syntax)';
+
+ function interpretLine(cm, string) {
+ var num = Number(string)
+ if (/^[-+]/.test(string)) return cm.getCursor().line + num
+ else return num - 1
+ }
+
+ CodeMirror.commands.jumpToLine = function(cm) {
+ var cur = cm.getCursor();
+ dialog(cm, jumpDialog, "Jump to line:", (cur.line + 1) + ":" + cur.ch, function(posStr) {
+ if (!posStr) return;
+
+ var match;
+ if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
+ cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
+ } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
+ var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
+ if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
+ cm.setCursor(line - 1, cur.ch);
+ } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
+ cm.setCursor(interpretLine(cm, match[1]), cur.ch);
+ }
+ });
+ };
+
+ CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
+});
diff --git a/codemirror/addon/search/match-highlighter.js b/codemirror/addon/search/match-highlighter.js
new file mode 100644
index 00000000..e9a22721
--- /dev/null
+++ b/codemirror/addon/search/match-highlighter.js
@@ -0,0 +1,128 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Highlighting text that matches the selection
+//
+// Defines an option highlightSelectionMatches, which, when enabled,
+// will style strings that match the selection throughout the
+// document.
+//
+// The option can be set to true to simply enable it, or to a
+// {minChars, style, wordsOnly, showToken, delay} object to explicitly
+// configure it. minChars is the minimum amount of characters that should be
+// selected for the behavior to occur, and style is the token style to
+// apply to the matches. This will be prefixed by "cm-" to create an
+// actual CSS class name. If wordsOnly is enabled, the matches will be
+// highlighted only if the selected text is a word. showToken, when enabled,
+// will cause the current token to be highlighted when nothing is selected.
+// delay is used to specify how much time to wait, in milliseconds, before
+// highlighting the matches.
+
+(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";
+
+ var DEFAULT_MIN_CHARS = 2;
+ var DEFAULT_TOKEN_STYLE = "matchhighlight";
+ var DEFAULT_DELAY = 100;
+ var DEFAULT_WORDS_ONLY = false;
+
+ function State(options) {
+ if (typeof options == "object") {
+ this.minChars = options.minChars;
+ this.style = options.style;
+ this.showToken = options.showToken;
+ this.delay = options.delay;
+ this.wordsOnly = options.wordsOnly;
+ }
+ if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
+ if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
+ if (this.delay == null) this.delay = DEFAULT_DELAY;
+ if (this.wordsOnly == null) this.wordsOnly = DEFAULT_WORDS_ONLY;
+ this.overlay = this.timeout = null;
+ }
+
+ CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ var over = cm.state.matchHighlighter.overlay;
+ if (over) cm.removeOverlay(over);
+ clearTimeout(cm.state.matchHighlighter.timeout);
+ cm.state.matchHighlighter = null;
+ cm.off("cursorActivity", cursorActivity);
+ }
+ if (val) {
+ cm.state.matchHighlighter = new State(val);
+ highlightMatches(cm);
+ cm.on("cursorActivity", cursorActivity);
+ }
+ });
+
+ function cursorActivity(cm) {
+ var state = cm.state.matchHighlighter;
+ clearTimeout(state.timeout);
+ state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay);
+ }
+
+ function highlightMatches(cm) {
+ cm.operation(function() {
+ var state = cm.state.matchHighlighter;
+ if (state.overlay) {
+ cm.removeOverlay(state.overlay);
+ state.overlay = null;
+ }
+ if (!cm.somethingSelected() && state.showToken) {
+ var re = state.showToken === true ? /[\w$]/ : state.showToken;
+ var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
+ while (start && re.test(line.charAt(start - 1))) --start;
+ while (end < line.length && re.test(line.charAt(end))) ++end;
+ if (start < end)
+ cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
+ return;
+ }
+ var from = cm.getCursor("from"), to = cm.getCursor("to");
+ if (from.line != to.line) return;
+ if (state.wordsOnly && !isWord(cm, from, to)) return;
+ var selection = cm.getRange(from, to).replace(/^\s+|\s+$/g, "");
+ if (selection.length >= state.minChars)
+ cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
+ });
+ }
+
+ function isWord(cm, from, to) {
+ var str = cm.getRange(from, to);
+ if (str.match(/^\w+$/) !== null) {
+ if (from.ch > 0) {
+ var pos = {line: from.line, ch: from.ch - 1};
+ var chr = cm.getRange(pos, from);
+ if (chr.match(/\W/) === null) return false;
+ }
+ if (to.ch < cm.getLine(from.line).length) {
+ var pos = {line: to.line, ch: to.ch + 1};
+ var chr = cm.getRange(to, pos);
+ if (chr.match(/\W/) === null) return false;
+ }
+ return true;
+ } else return false;
+ }
+
+ function boundariesAround(stream, re) {
+ return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
+ (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
+ }
+
+ function makeOverlay(query, hasBoundary, style) {
+ return {token: function(stream) {
+ if (stream.match(query) &&
+ (!hasBoundary || boundariesAround(stream, hasBoundary)))
+ return style;
+ stream.next();
+ stream.skipTo(query.charAt(0)) || stream.skipToEnd();
+ }};
+ }
+});
diff --git a/codemirror/addon/search/matchesonscrollbar.css b/codemirror/addon/search/matchesonscrollbar.css
new file mode 100644
index 00000000..77932cc9
--- /dev/null
+++ b/codemirror/addon/search/matchesonscrollbar.css
@@ -0,0 +1,8 @@
+.CodeMirror-search-match {
+ background: gold;
+ border-top: 1px solid orange;
+ border-bottom: 1px solid orange;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ opacity: .5;
+}
diff --git a/codemirror/addon/search/matchesonscrollbar.js b/codemirror/addon/search/matchesonscrollbar.js
new file mode 100644
index 00000000..8d192289
--- /dev/null
+++ b/codemirror/addon/search/matchesonscrollbar.js
@@ -0,0 +1,97 @@
+// 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"), require("./searchcursor"), require("../scroll/annotatescrollbar"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./searchcursor", "../scroll/annotatescrollbar"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) {
+ if (typeof options == "string") options = {className: options};
+ if (!options) options = {};
+ return new SearchAnnotation(this, query, caseFold, options);
+ });
+
+ function SearchAnnotation(cm, query, caseFold, options) {
+ this.cm = cm;
+ this.options = options;
+ var annotateOptions = {listenForChanges: false};
+ for (var prop in options) annotateOptions[prop] = options[prop];
+ if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match";
+ this.annotation = cm.annotateScrollbar(annotateOptions);
+ this.query = query;
+ this.caseFold = caseFold;
+ this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1};
+ this.matches = [];
+ this.update = null;
+
+ this.findMatches();
+ this.annotation.update(this.matches);
+
+ var self = this;
+ cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); });
+ }
+
+ var MAX_MATCHES = 1000;
+
+ SearchAnnotation.prototype.findMatches = function() {
+ if (!this.gap) return;
+ for (var i = 0; i < this.matches.length; i++) {
+ var match = this.matches[i];
+ if (match.from.line >= this.gap.to) break;
+ if (match.to.line >= this.gap.from) this.matches.splice(i--, 1);
+ }
+ var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), this.caseFold);
+ var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES;
+ while (cursor.findNext()) {
+ var match = {from: cursor.from(), to: cursor.to()};
+ if (match.from.line >= this.gap.to) break;
+ this.matches.splice(i++, 0, match);
+ if (this.matches.length > maxMatches) break;
+ }
+ this.gap = null;
+ };
+
+ function offsetLine(line, changeStart, sizeChange) {
+ if (line <= changeStart) return line;
+ return Math.max(changeStart, line + sizeChange);
+ }
+
+ SearchAnnotation.prototype.onChange = function(change) {
+ var startLine = change.from.line;
+ var endLine = CodeMirror.changeEnd(change).line;
+ var sizeChange = endLine - change.to.line;
+ if (this.gap) {
+ this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line);
+ this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line);
+ } else {
+ this.gap = {from: change.from.line, to: endLine + 1};
+ }
+
+ if (sizeChange) for (var i = 0; i < this.matches.length; i++) {
+ var match = this.matches[i];
+ var newFrom = offsetLine(match.from.line, startLine, sizeChange);
+ if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch);
+ var newTo = offsetLine(match.to.line, startLine, sizeChange);
+ if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch);
+ }
+ clearTimeout(this.update);
+ var self = this;
+ this.update = setTimeout(function() { self.updateAfterChange(); }, 250);
+ };
+
+ SearchAnnotation.prototype.updateAfterChange = function() {
+ this.findMatches();
+ this.annotation.update(this.matches);
+ };
+
+ SearchAnnotation.prototype.clear = function() {
+ this.cm.off("change", this.changeHandler);
+ this.annotation.clear();
+ };
+});
diff --git a/codemirror/addon/search/search.js b/codemirror/addon/search/search.js
new file mode 100644
index 00000000..93e90b36
--- /dev/null
+++ b/codemirror/addon/search/search.js
@@ -0,0 +1,228 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Define search commands. Depends on dialog.js or another
+// implementation of the openDialog method.
+
+// Replace works a little oddly -- it will do the replace on the next
+// Ctrl-G (or whatever is bound to findNext) press. You prevent a
+// replace by making sure the match is no longer selected when hitting
+// Ctrl-G.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ function searchOverlay(query, caseInsensitive) {
+ if (typeof query == "string")
+ query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
+ else if (!query.global)
+ query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
+
+ return {token: function(stream) {
+ query.lastIndex = stream.pos;
+ var match = query.exec(stream.string);
+ if (match && match.index == stream.pos) {
+ stream.pos += match[0].length || 1;
+ return "searching";
+ } else if (match) {
+ stream.pos = match.index;
+ } else {
+ stream.skipToEnd();
+ }
+ }};
+ }
+
+ function SearchState() {
+ this.posFrom = this.posTo = this.lastQuery = this.query = null;
+ this.overlay = null;
+ }
+
+ function getSearchState(cm) {
+ return cm.state.search || (cm.state.search = new SearchState());
+ }
+
+ function queryCaseInsensitive(query) {
+ return typeof query == "string" && query == query.toLowerCase();
+ }
+
+ function getSearchCursor(cm, query, pos) {
+ // Heuristic: if the query string is all lowercase, do a case insensitive search.
+ return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
+ }
+
+ function persistentDialog(cm, text, deflt, f) {
+ cm.openDialog(text, f, {
+ value: deflt,
+ selectValueOnOpen: true,
+ closeOnEnter: false,
+ onClose: function() { clearSearch(cm); }
+ });
+ }
+
+ function dialog(cm, text, shortText, deflt, f) {
+ if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
+ else f(prompt(shortText, deflt));
+ }
+
+ function confirmDialog(cm, text, shortText, fs) {
+ if (cm.openConfirm) cm.openConfirm(text, fs);
+ else if (confirm(shortText)) fs[0]();
+ }
+
+ function parseString(string) {
+ return string.replace(/\\(.)/g, function(_, ch) {
+ if (ch == "n") return "\n"
+ if (ch == "r") return "\r"
+ return ch
+ })
+ }
+
+ function parseQuery(query) {
+ var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
+ if (isRE) {
+ try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
+ catch(e) {} // Not a regular expression after all, do a string search
+ } else {
+ query = parseString(query)
+ }
+ if (typeof query == "string" ? query == "" : query.test(""))
+ query = /x^/;
+ return query;
+ }
+
+ var queryDialog =
+ 'Search: (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/codemirror/addon/search/searchcursor.js b/codemirror/addon/search/searchcursor.js
new file mode 100644
index 00000000..b70242ee
--- /dev/null
+++ b/codemirror/addon/search/searchcursor.js
@@ -0,0 +1,189 @@
+// 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";
+ var Pos = CodeMirror.Pos;
+
+ function SearchCursor(doc, query, pos, caseFold) {
+ this.atOccurrence = false; this.doc = doc;
+ if (caseFold == null && typeof query == "string") caseFold = false;
+
+ pos = pos ? doc.clipPos(pos) : Pos(0, 0);
+ this.pos = {from: pos, to: pos};
+
+ // The matches method is filled in based on the type of query.
+ // It takes a position and a direction, and returns an object
+ // describing the next occurrence of the query, or null if no
+ // more matches were found.
+ if (typeof query != "string") { // Regexp match
+ if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
+ this.matches = function(reverse, pos) {
+ if (reverse) {
+ query.lastIndex = 0;
+ var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
+ for (;;) {
+ query.lastIndex = cutOff;
+ var newMatch = query.exec(line);
+ if (!newMatch) break;
+ match = newMatch;
+ start = match.index;
+ cutOff = match.index + (match[0].length || 1);
+ if (cutOff == line.length) break;
+ }
+ var matchLen = (match && match[0].length) || 0;
+ if (!matchLen) {
+ if (start == 0 && line.length == 0) {match = undefined;}
+ else if (start != doc.getLine(pos.line).length) {
+ matchLen++;
+ }
+ }
+ } else {
+ query.lastIndex = pos.ch;
+ var line = doc.getLine(pos.line), match = query.exec(line);
+ var matchLen = (match && match[0].length) || 0;
+ var start = match && match.index;
+ if (start + matchLen != line.length && !matchLen) matchLen = 1;
+ }
+ if (match && matchLen)
+ return {from: Pos(pos.line, start),
+ to: Pos(pos.line, start + matchLen),
+ match: match};
+ };
+ } else { // String query
+ var origQuery = query;
+ if (caseFold) query = query.toLowerCase();
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
+ var target = query.split("\n");
+ // Different methods for single-line and multi-line queries
+ if (target.length == 1) {
+ if (!query.length) {
+ // Empty string would match anything and never progress, so
+ // we define it to match nothing instead.
+ this.matches = function() {};
+ } else {
+ this.matches = function(reverse, pos) {
+ if (reverse) {
+ var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
+ var match = line.lastIndexOf(query);
+ if (match > -1) {
+ match = adjustPos(orig, line, match);
+ return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
+ }
+ } else {
+ var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
+ var match = line.indexOf(query);
+ if (match > -1) {
+ match = adjustPos(orig, line, match) + pos.ch;
+ return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
+ }
+ }
+ };
+ }
+ } else {
+ var origTarget = origQuery.split("\n");
+ this.matches = function(reverse, pos) {
+ var last = target.length - 1;
+ if (reverse) {
+ if (pos.line - (target.length - 1) < doc.firstLine()) return;
+ if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
+ var to = Pos(pos.line, origTarget[last].length);
+ for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
+ if (target[i] != fold(doc.getLine(ln))) return;
+ var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
+ if (fold(line.slice(cut)) != target[0]) return;
+ return {from: Pos(ln, cut), to: to};
+ } else {
+ if (pos.line + (target.length - 1) > doc.lastLine()) return;
+ var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
+ if (fold(line.slice(cut)) != target[0]) return;
+ var from = Pos(pos.line, cut);
+ for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
+ if (target[i] != fold(doc.getLine(ln))) return;
+ if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
+ return {from: from, to: Pos(ln, origTarget[last].length)};
+ }
+ };
+ }
+ }
+ }
+
+ SearchCursor.prototype = {
+ findNext: function() {return this.find(false);},
+ findPrevious: function() {return this.find(true);},
+
+ find: function(reverse) {
+ var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
+ function savePosAndFail(line) {
+ var pos = Pos(line, 0);
+ self.pos = {from: pos, to: pos};
+ self.atOccurrence = false;
+ return false;
+ }
+
+ for (;;) {
+ if (this.pos = this.matches(reverse, pos)) {
+ this.atOccurrence = true;
+ return this.pos.match || true;
+ }
+ if (reverse) {
+ if (!pos.line) return savePosAndFail(0);
+ pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
+ }
+ else {
+ var maxLine = this.doc.lineCount();
+ if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
+ pos = Pos(pos.line + 1, 0);
+ }
+ }
+ },
+
+ from: function() {if (this.atOccurrence) return this.pos.from;},
+ to: function() {if (this.atOccurrence) return this.pos.to;},
+
+ replace: function(newText, origin) {
+ if (!this.atOccurrence) return;
+ var lines = CodeMirror.splitLines(newText);
+ this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
+ this.pos.to = Pos(this.pos.from.line + lines.length - 1,
+ lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
+ }
+ };
+
+ // Maps a position in a case-folded line back to a position in the original line
+ // (compensating for codepoints increasing in number during folding)
+ function adjustPos(orig, folded, pos) {
+ if (orig.length == folded.length) return pos;
+ for (var pos1 = Math.min(pos, orig.length);;) {
+ var len1 = orig.slice(0, pos1).toLowerCase().length;
+ if (len1 < pos) ++pos1;
+ else if (len1 > pos) --pos1;
+ else return pos1;
+ }
+ }
+
+ CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
+ return new SearchCursor(this.doc, query, pos, caseFold);
+ });
+ CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
+ return new SearchCursor(this, query, pos, caseFold);
+ });
+
+ CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
+ var ranges = [];
+ var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
+ while (cur.findNext()) {
+ if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
+ ranges.push({anchor: cur.from(), head: cur.to()});
+ }
+ if (ranges.length)
+ this.setSelections(ranges, 0);
+ });
+});
diff --git a/codemirror/addon/selection/active-line.js b/codemirror/addon/selection/active-line.js
new file mode 100644
index 00000000..22da2e0a
--- /dev/null
+++ b/codemirror/addon/selection/active-line.js
@@ -0,0 +1,71 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Because sometimes you need to style the cursor's line.
+//
+// Adds an option 'styleActiveLine' which, when enabled, gives the
+// active line's wrapping
the CSS class "CodeMirror-activeline",
+// and gives its background
the class "CodeMirror-activeline-background".
+
+(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";
+ var WRAP_CLASS = "CodeMirror-activeline";
+ var BACK_CLASS = "CodeMirror-activeline-background";
+
+ CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.state.activeLines = [];
+ updateActiveLines(cm, cm.listSelections());
+ cm.on("beforeSelectionChange", selectionChange);
+ } else if (!val && prev) {
+ cm.off("beforeSelectionChange", selectionChange);
+ clearActiveLines(cm);
+ delete cm.state.activeLines;
+ }
+ });
+
+ function clearActiveLines(cm) {
+ for (var i = 0; i < cm.state.activeLines.length; i++) {
+ cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
+ cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
+ }
+ }
+
+ function sameArray(a, b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++)
+ if (a[i] != b[i]) return false;
+ return true;
+ }
+
+ function updateActiveLines(cm, ranges) {
+ var active = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (!range.empty()) continue;
+ var line = cm.getLineHandleVisualStart(range.head.line);
+ if (active[active.length - 1] != line) active.push(line);
+ }
+ if (sameArray(cm.state.activeLines, active)) return;
+ cm.operation(function() {
+ clearActiveLines(cm);
+ for (var i = 0; i < active.length; i++) {
+ cm.addLineClass(active[i], "wrap", WRAP_CLASS);
+ cm.addLineClass(active[i], "background", BACK_CLASS);
+ }
+ cm.state.activeLines = active;
+ });
+ }
+
+ function selectionChange(cm, sel) {
+ updateActiveLines(cm, sel.ranges);
+ }
+});
diff --git a/codemirror/addon/selection/mark-selection.js b/codemirror/addon/selection/mark-selection.js
new file mode 100644
index 00000000..5c42d21e
--- /dev/null
+++ b/codemirror/addon/selection/mark-selection.js
@@ -0,0 +1,118 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Because sometimes you need to mark the selected *text*.
+//
+// Adds an option 'styleSelectedText' which, when enabled, gives
+// selected text the CSS class given as option value, or
+// "CodeMirror-selectedtext" when the value is not a string.
+
+(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.defineOption("styleSelectedText", false, function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.state.markedSelection = [];
+ cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
+ reset(cm);
+ cm.on("cursorActivity", onCursorActivity);
+ cm.on("change", onChange);
+ } else if (!val && prev) {
+ cm.off("cursorActivity", onCursorActivity);
+ cm.off("change", onChange);
+ clear(cm);
+ cm.state.markedSelection = cm.state.markedSelectionStyle = null;
+ }
+ });
+
+ function onCursorActivity(cm) {
+ cm.operation(function() { update(cm); });
+ }
+
+ function onChange(cm) {
+ if (cm.state.markedSelection.length)
+ cm.operation(function() { clear(cm); });
+ }
+
+ var CHUNK_SIZE = 8;
+ var Pos = CodeMirror.Pos;
+ var cmp = CodeMirror.cmpPos;
+
+ function coverRange(cm, from, to, addAt) {
+ if (cmp(from, to) == 0) return;
+ var array = cm.state.markedSelection;
+ var cls = cm.state.markedSelectionStyle;
+ for (var line = from.line;;) {
+ var start = line == from.line ? from : Pos(line, 0);
+ var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
+ var end = atEnd ? to : Pos(endLine, 0);
+ var mark = cm.markText(start, end, {className: cls});
+ if (addAt == null) array.push(mark);
+ else array.splice(addAt++, 0, mark);
+ if (atEnd) break;
+ line = endLine;
+ }
+ }
+
+ function clear(cm) {
+ var array = cm.state.markedSelection;
+ for (var i = 0; i < array.length; ++i) array[i].clear();
+ array.length = 0;
+ }
+
+ function reset(cm) {
+ clear(cm);
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++)
+ coverRange(cm, ranges[i].from(), ranges[i].to());
+ }
+
+ function update(cm) {
+ if (!cm.somethingSelected()) return clear(cm);
+ if (cm.listSelections().length > 1) return reset(cm);
+
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
+
+ var array = cm.state.markedSelection;
+ if (!array.length) return coverRange(cm, from, to);
+
+ var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
+ if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
+ cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
+ return reset(cm);
+
+ while (cmp(from, coverStart.from) > 0) {
+ array.shift().clear();
+ coverStart = array[0].find();
+ }
+ if (cmp(from, coverStart.from) < 0) {
+ if (coverStart.to.line - from.line < CHUNK_SIZE) {
+ array.shift().clear();
+ coverRange(cm, from, coverStart.to, 0);
+ } else {
+ coverRange(cm, from, coverStart.from, 0);
+ }
+ }
+
+ while (cmp(to, coverEnd.to) < 0) {
+ array.pop().clear();
+ coverEnd = array[array.length - 1].find();
+ }
+ if (cmp(to, coverEnd.to) > 0) {
+ if (to.line - coverEnd.from.line < CHUNK_SIZE) {
+ array.pop().clear();
+ coverRange(cm, coverEnd.from, to);
+ } else {
+ coverRange(cm, coverEnd.to, to);
+ }
+ }
+ }
+});
diff --git a/codemirror/addon/selection/selection-pointer.js b/codemirror/addon/selection/selection-pointer.js
new file mode 100644
index 00000000..ef5e404a
--- /dev/null
+++ b/codemirror/addon/selection/selection-pointer.js
@@ -0,0 +1,98 @@
+// 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.defineOption("selectionPointer", false, function(cm, val) {
+ var data = cm.state.selectionPointer;
+ if (data) {
+ CodeMirror.off(cm.getWrapperElement(), "mousemove", data.mousemove);
+ CodeMirror.off(cm.getWrapperElement(), "mouseout", data.mouseout);
+ CodeMirror.off(window, "scroll", data.windowScroll);
+ cm.off("cursorActivity", reset);
+ cm.off("scroll", reset);
+ cm.state.selectionPointer = null;
+ cm.display.lineDiv.style.cursor = "";
+ }
+ if (val) {
+ data = cm.state.selectionPointer = {
+ value: typeof val == "string" ? val : "default",
+ mousemove: function(event) { mousemove(cm, event); },
+ mouseout: function(event) { mouseout(cm, event); },
+ windowScroll: function() { reset(cm); },
+ rects: null,
+ mouseX: null, mouseY: null,
+ willUpdate: false
+ };
+ CodeMirror.on(cm.getWrapperElement(), "mousemove", data.mousemove);
+ CodeMirror.on(cm.getWrapperElement(), "mouseout", data.mouseout);
+ CodeMirror.on(window, "scroll", data.windowScroll);
+ cm.on("cursorActivity", reset);
+ cm.on("scroll", reset);
+ }
+ });
+
+ function mousemove(cm, event) {
+ var data = cm.state.selectionPointer;
+ if (event.buttons == null ? event.which : event.buttons) {
+ data.mouseX = data.mouseY = null;
+ } else {
+ data.mouseX = event.clientX;
+ data.mouseY = event.clientY;
+ }
+ scheduleUpdate(cm);
+ }
+
+ function mouseout(cm, event) {
+ if (!cm.getWrapperElement().contains(event.relatedTarget)) {
+ var data = cm.state.selectionPointer;
+ data.mouseX = data.mouseY = null;
+ scheduleUpdate(cm);
+ }
+ }
+
+ function reset(cm) {
+ cm.state.selectionPointer.rects = null;
+ scheduleUpdate(cm);
+ }
+
+ function scheduleUpdate(cm) {
+ if (!cm.state.selectionPointer.willUpdate) {
+ cm.state.selectionPointer.willUpdate = true;
+ setTimeout(function() {
+ update(cm);
+ cm.state.selectionPointer.willUpdate = false;
+ }, 50);
+ }
+ }
+
+ function update(cm) {
+ var data = cm.state.selectionPointer;
+ if (!data) return;
+ if (data.rects == null && data.mouseX != null) {
+ data.rects = [];
+ if (cm.somethingSelected()) {
+ for (var sel = cm.display.selectionDiv.firstChild; sel; sel = sel.nextSibling)
+ data.rects.push(sel.getBoundingClientRect());
+ }
+ }
+ var inside = false;
+ if (data.mouseX != null) for (var i = 0; i < data.rects.length; i++) {
+ var rect = data.rects[i];
+ if (rect.left <= data.mouseX && rect.right >= data.mouseX &&
+ rect.top <= data.mouseY && rect.bottom >= data.mouseY)
+ inside = true;
+ }
+ var cursor = inside ? data.value : "";
+ if (cm.display.lineDiv.style.cursor != cursor)
+ cm.display.lineDiv.style.cursor = cursor;
+ }
+});
diff --git a/codemirror/addon/tern/tern.css b/codemirror/addon/tern/tern.css
new file mode 100644
index 00000000..c4b8a2f7
--- /dev/null
+++ b/codemirror/addon/tern/tern.css
@@ -0,0 +1,87 @@
+.CodeMirror-Tern-completion {
+ padding-left: 22px;
+ position: relative;
+ line-height: 1.5;
+}
+.CodeMirror-Tern-completion:before {
+ position: absolute;
+ left: 2px;
+ bottom: 2px;
+ border-radius: 50%;
+ font-size: 12px;
+ font-weight: bold;
+ height: 15px;
+ width: 15px;
+ line-height: 16px;
+ text-align: center;
+ color: white;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+.CodeMirror-Tern-completion-unknown:before {
+ content: "?";
+ background: #4bb;
+}
+.CodeMirror-Tern-completion-object:before {
+ content: "O";
+ background: #77c;
+}
+.CodeMirror-Tern-completion-fn:before {
+ content: "F";
+ background: #7c7;
+}
+.CodeMirror-Tern-completion-array:before {
+ content: "A";
+ background: #c66;
+}
+.CodeMirror-Tern-completion-number:before {
+ content: "1";
+ background: #999;
+}
+.CodeMirror-Tern-completion-string:before {
+ content: "S";
+ background: #999;
+}
+.CodeMirror-Tern-completion-bool:before {
+ content: "B";
+ background: #999;
+}
+
+.CodeMirror-Tern-completion-guess {
+ color: #999;
+}
+
+.CodeMirror-Tern-tooltip {
+ border: 1px solid silver;
+ border-radius: 3px;
+ color: #444;
+ padding: 2px 5px;
+ font-size: 90%;
+ font-family: monospace;
+ background-color: white;
+ white-space: pre-wrap;
+
+ max-width: 40em;
+ position: absolute;
+ z-index: 10;
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+
+ transition: opacity 1s;
+ -moz-transition: opacity 1s;
+ -webkit-transition: opacity 1s;
+ -o-transition: opacity 1s;
+ -ms-transition: opacity 1s;
+}
+
+.CodeMirror-Tern-hint-doc {
+ max-width: 25em;
+ margin-top: -3px;
+}
+
+.CodeMirror-Tern-fname { color: black; }
+.CodeMirror-Tern-farg { color: #70a; }
+.CodeMirror-Tern-farg-current { text-decoration: underline; }
+.CodeMirror-Tern-type { color: #07c; }
+.CodeMirror-Tern-fhint-guess { opacity: .7; }
diff --git a/codemirror/addon/tern/tern.js b/codemirror/addon/tern/tern.js
new file mode 100644
index 00000000..c345c497
--- /dev/null
+++ b/codemirror/addon/tern/tern.js
@@ -0,0 +1,701 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Glue code between CodeMirror and Tern.
+//
+// Create a CodeMirror.TernServer to wrap an actual Tern server,
+// register open documents (CodeMirror.Doc instances) with it, and
+// call its methods to activate the assisting functions that Tern
+// provides.
+//
+// Options supported (all optional):
+// * defs: An array of JSON definition data structures.
+// * plugins: An object mapping plugin names to configuration
+// options.
+// * getFile: A function(name, c) that can be used to access files in
+// the project that haven't been loaded yet. Simply do c(null) to
+// indicate that a file is not available.
+// * fileFilter: A function(value, docName, doc) that will be applied
+// to documents before passing them on to Tern.
+// * switchToDoc: A function(name, doc) that should, when providing a
+// multi-file view, switch the view or focus to the named file.
+// * showError: A function(editor, message) that can be used to
+// override the way errors are displayed.
+// * completionTip: Customize the content in tooltips for completions.
+// Is passed a single argument—the completion's data as returned by
+// Tern—and may return a string, DOM node, or null to indicate that
+// no tip should be shown. By default the docstring is shown.
+// * typeTip: Like completionTip, but for the tooltips shown for type
+// queries.
+// * responseFilter: A function(doc, query, request, error, data) that
+// will be applied to the Tern responses before treating them
+//
+//
+// It is possible to run the Tern server in a web worker by specifying
+// these additional options:
+// * useWorker: Set to true to enable web worker mode. You'll probably
+// want to feature detect the actual value you use here, for example
+// !!window.Worker.
+// * workerScript: The main script of the worker. Point this to
+// wherever you are hosting worker.js from this directory.
+// * workerDeps: An array of paths pointing (relative to workerScript)
+// to the Acorn and Tern libraries and any Tern plugins you want to
+// load. Or, if you minified those into a single script and included
+// them in the workerScript, simply leave this undefined.
+
+(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";
+ // declare global: tern
+
+ CodeMirror.TernServer = function(options) {
+ var self = this;
+ this.options = options || {};
+ var plugins = this.options.plugins || (this.options.plugins = {});
+ if (!plugins.doc_comment) plugins.doc_comment = true;
+ this.docs = Object.create(null);
+ if (this.options.useWorker) {
+ this.server = new WorkerServer(this);
+ } else {
+ this.server = new tern.Server({
+ getFile: function(name, c) { return getFile(self, name, c); },
+ async: true,
+ defs: this.options.defs || [],
+ plugins: plugins
+ });
+ }
+ this.trackChange = function(doc, change) { trackChange(self, doc, change); };
+
+ this.cachedArgHints = null;
+ this.activeArgHints = null;
+ this.jumpStack = [];
+
+ this.getHint = function(cm, c) { return hint(self, cm, c); };
+ this.getHint.async = true;
+ };
+
+ CodeMirror.TernServer.prototype = {
+ addDoc: function(name, doc) {
+ var data = {doc: doc, name: name, changed: null};
+ this.server.addFile(name, docValue(this, data));
+ CodeMirror.on(doc, "change", this.trackChange);
+ return this.docs[name] = data;
+ },
+
+ delDoc: function(id) {
+ var found = resolveDoc(this, id);
+ if (!found) return;
+ CodeMirror.off(found.doc, "change", this.trackChange);
+ delete this.docs[found.name];
+ this.server.delFile(found.name);
+ },
+
+ hideDoc: function(id) {
+ closeArgHints(this);
+ var found = resolveDoc(this, id);
+ if (found && found.changed) sendDoc(this, found);
+ },
+
+ complete: function(cm) {
+ cm.showHint({hint: this.getHint});
+ },
+
+ showType: function(cm, pos, c) { showContextInfo(this, cm, pos, "type", c); },
+
+ showDocs: function(cm, pos, c) { showContextInfo(this, cm, pos, "documentation", c); },
+
+ updateArgHints: function(cm) { updateArgHints(this, cm); },
+
+ jumpToDef: function(cm) { jumpToDef(this, cm); },
+
+ jumpBack: function(cm) { jumpBack(this, cm); },
+
+ rename: function(cm) { rename(this, cm); },
+
+ selectName: function(cm) { selectName(this, cm); },
+
+ request: function (cm, query, c, pos) {
+ var self = this;
+ var doc = findDoc(this, cm.getDoc());
+ var request = buildRequest(this, doc, query, pos);
+ var extraOptions = request.query && this.options.queryOptions && this.options.queryOptions[request.query.type]
+ if (extraOptions) for (var prop in extraOptions) request.query[prop] = extraOptions[prop];
+
+ this.server.request(request, function (error, data) {
+ if (!error && self.options.responseFilter)
+ data = self.options.responseFilter(doc, query, request, error, data);
+ c(error, data);
+ });
+ },
+
+ destroy: function () {
+ closeArgHints(this)
+ if (this.worker) {
+ this.worker.terminate();
+ this.worker = null;
+ }
+ }
+ };
+
+ var Pos = CodeMirror.Pos;
+ var cls = "CodeMirror-Tern-";
+ var bigDoc = 250;
+
+ function getFile(ts, name, c) {
+ var buf = ts.docs[name];
+ if (buf)
+ c(docValue(ts, buf));
+ else if (ts.options.getFile)
+ ts.options.getFile(name, c);
+ else
+ c(null);
+ }
+
+ function findDoc(ts, doc, name) {
+ for (var n in ts.docs) {
+ var cur = ts.docs[n];
+ if (cur.doc == doc) return cur;
+ }
+ if (!name) for (var i = 0;; ++i) {
+ n = "[doc" + (i || "") + "]";
+ if (!ts.docs[n]) { name = n; break; }
+ }
+ return ts.addDoc(name, doc);
+ }
+
+ function resolveDoc(ts, id) {
+ if (typeof id == "string") return ts.docs[id];
+ if (id instanceof CodeMirror) id = id.getDoc();
+ if (id instanceof CodeMirror.Doc) return findDoc(ts, id);
+ }
+
+ function trackChange(ts, doc, change) {
+ var data = findDoc(ts, doc);
+
+ var argHints = ts.cachedArgHints;
+ if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
+ ts.cachedArgHints = null;
+
+ var changed = data.changed;
+ if (changed == null)
+ data.changed = changed = {from: change.from.line, to: change.from.line};
+ var end = change.from.line + (change.text.length - 1);
+ if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
+ if (end >= changed.to) changed.to = end + 1;
+ if (changed.from > change.from.line) changed.from = change.from.line;
+
+ if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
+ if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
+ }, 200);
+ }
+
+ function sendDoc(ts, doc) {
+ ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
+ if (error) window.console.error(error);
+ else doc.changed = null;
+ });
+ }
+
+ // Completion
+
+ function hint(ts, cm, c) {
+ ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
+ if (error) return showError(ts, cm, error);
+ var completions = [], after = "";
+ var from = data.start, to = data.end;
+ if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
+ cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
+ after = "\"]";
+
+ for (var i = 0; i < data.completions.length; ++i) {
+ var completion = data.completions[i], className = typeToIcon(completion.type);
+ if (data.guess) className += " " + cls + "guess";
+ completions.push({text: completion.name + after,
+ displayText: completion.displayName || completion.name,
+ className: className,
+ data: completion});
+ }
+
+ var obj = {from: from, to: to, list: completions};
+ var tooltip = null;
+ CodeMirror.on(obj, "close", function() { remove(tooltip); });
+ CodeMirror.on(obj, "update", function() { remove(tooltip); });
+ CodeMirror.on(obj, "select", function(cur, node) {
+ remove(tooltip);
+ var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
+ if (content) {
+ tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
+ node.getBoundingClientRect().top + window.pageYOffset, content);
+ tooltip.className += " " + cls + "hint-doc";
+ }
+ });
+ c(obj);
+ });
+ }
+
+ function typeToIcon(type) {
+ var suffix;
+ if (type == "?") suffix = "unknown";
+ else if (type == "number" || type == "string" || type == "bool") suffix = type;
+ else if (/^fn\(/.test(type)) suffix = "fn";
+ else if (/^\[/.test(type)) suffix = "array";
+ else suffix = "object";
+ return cls + "completion " + cls + "completion-" + suffix;
+ }
+
+ // Type queries
+
+ function showContextInfo(ts, cm, pos, queryName, c) {
+ ts.request(cm, queryName, function(error, data) {
+ if (error) return showError(ts, cm, error);
+ if (ts.options.typeTip) {
+ var tip = ts.options.typeTip(data);
+ } else {
+ var tip = elt("span", null, elt("strong", null, data.type || "not found"));
+ if (data.doc)
+ tip.appendChild(document.createTextNode(" — " + data.doc));
+ if (data.url) {
+ tip.appendChild(document.createTextNode(" "));
+ var child = tip.appendChild(elt("a", null, "[docs]"));
+ child.href = data.url;
+ child.target = "_blank";
+ }
+ }
+ tempTooltip(cm, tip, ts);
+ if (c) c();
+ }, pos);
+ }
+
+ // Maintaining argument hints
+
+ function updateArgHints(ts, cm) {
+ closeArgHints(ts);
+
+ if (cm.somethingSelected()) return;
+ var state = cm.getTokenAt(cm.getCursor()).state;
+ var inner = CodeMirror.innerMode(cm.getMode(), state);
+ if (inner.mode.name != "javascript") return;
+ var lex = inner.state.lexical;
+ if (lex.info != "call") return;
+
+ var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize");
+ for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
+ var str = cm.getLine(line), extra = 0;
+ for (var pos = 0;;) {
+ var tab = str.indexOf("\t", pos);
+ if (tab == -1) break;
+ extra += tabSize - (tab + extra) % tabSize - 1;
+ pos = tab + 1;
+ }
+ ch = lex.column - extra;
+ if (str.charAt(ch) == "(") {found = true; break;}
+ }
+ if (!found) return;
+
+ var start = Pos(line, ch);
+ var cache = ts.cachedArgHints;
+ if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
+ return showArgHints(ts, cm, argPos);
+
+ ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
+ if (error || !data.type || !(/^fn\(/).test(data.type)) return;
+ ts.cachedArgHints = {
+ start: pos,
+ type: parseFnType(data.type),
+ name: data.exprName || data.name || "fn",
+ guess: data.guess,
+ doc: cm.getDoc()
+ };
+ showArgHints(ts, cm, argPos);
+ });
+ }
+
+ function showArgHints(ts, cm, pos) {
+ closeArgHints(ts);
+
+ var cache = ts.cachedArgHints, tp = cache.type;
+ var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
+ elt("span", cls + "fname", cache.name), "(");
+ for (var i = 0; i < tp.args.length; ++i) {
+ if (i) tip.appendChild(document.createTextNode(", "));
+ var arg = tp.args[i];
+ tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
+ if (arg.type != "?") {
+ tip.appendChild(document.createTextNode(":\u00a0"));
+ tip.appendChild(elt("span", cls + "type", arg.type));
+ }
+ }
+ tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
+ if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
+ var place = cm.cursorCoords(null, "page");
+ ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
+ }
+
+ function parseFnType(text) {
+ var args = [], pos = 3;
+
+ function skipMatching(upto) {
+ var depth = 0, start = pos;
+ for (;;) {
+ var next = text.charAt(pos);
+ if (upto.test(next) && !depth) return text.slice(start, pos);
+ if (/[{\[\(]/.test(next)) ++depth;
+ else if (/[}\]\)]/.test(next)) --depth;
+ ++pos;
+ }
+ }
+
+ // Parse arguments
+ if (text.charAt(pos) != ")") for (;;) {
+ var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
+ if (name) {
+ pos += name[0].length;
+ name = name[1];
+ }
+ args.push({name: name, type: skipMatching(/[\),]/)});
+ if (text.charAt(pos) == ")") break;
+ pos += 2;
+ }
+
+ var rettype = text.slice(pos).match(/^\) -> (.*)$/);
+
+ return {args: args, rettype: rettype && rettype[1]};
+ }
+
+ // Moving to the definition of something
+
+ function jumpToDef(ts, cm) {
+ function inner(varName) {
+ var req = {type: "definition", variable: varName || null};
+ var doc = findDoc(ts, cm.getDoc());
+ ts.server.request(buildRequest(ts, doc, req), function(error, data) {
+ if (error) return showError(ts, cm, error);
+ if (!data.file && data.url) { window.open(data.url); return; }
+
+ if (data.file) {
+ var localDoc = ts.docs[data.file], found;
+ if (localDoc && (found = findContext(localDoc.doc, data))) {
+ ts.jumpStack.push({file: doc.name,
+ start: cm.getCursor("from"),
+ end: cm.getCursor("to")});
+ moveTo(ts, doc, localDoc, found.start, found.end);
+ return;
+ }
+ }
+ showError(ts, cm, "Could not find a definition.");
+ });
+ }
+
+ if (!atInterestingExpression(cm))
+ dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
+ else
+ inner();
+ }
+
+ function jumpBack(ts, cm) {
+ var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
+ if (!doc) return;
+ moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
+ }
+
+ function moveTo(ts, curDoc, doc, start, end) {
+ doc.doc.setSelection(start, end);
+ if (curDoc != doc && ts.options.switchToDoc) {
+ closeArgHints(ts);
+ ts.options.switchToDoc(doc.name, doc.doc);
+ }
+ }
+
+ // The {line,ch} representation of positions makes this rather awkward.
+ function findContext(doc, data) {
+ var before = data.context.slice(0, data.contextOffset).split("\n");
+ var startLine = data.start.line - (before.length - 1);
+ var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
+
+ var text = doc.getLine(startLine).slice(start.ch);
+ for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
+ text += "\n" + doc.getLine(cur);
+ if (text.slice(0, data.context.length) == data.context) return data;
+
+ var cursor = doc.getSearchCursor(data.context, 0, false);
+ var nearest, nearestDist = Infinity;
+ while (cursor.findNext()) {
+ var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
+ if (!dist) dist = Math.abs(from.ch - start.ch);
+ if (dist < nearestDist) { nearest = from; nearestDist = dist; }
+ }
+ if (!nearest) return null;
+
+ if (before.length == 1)
+ nearest.ch += before[0].length;
+ else
+ nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
+ if (data.start.line == data.end.line)
+ var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
+ else
+ var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
+ return {start: nearest, end: end};
+ }
+
+ function atInterestingExpression(cm) {
+ var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
+ if (tok.start < pos.ch && tok.type == "comment") return false;
+ return /[\w)\]]/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
+ }
+
+ // Variable renaming
+
+ function rename(ts, cm) {
+ var token = cm.getTokenAt(cm.getCursor());
+ if (!/\w/.test(token.string)) return showError(ts, cm, "Not at a variable");
+ dialog(cm, "New name for " + token.string, function(newName) {
+ ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
+ if (error) return showError(ts, cm, error);
+ applyChanges(ts, data.changes);
+ });
+ });
+ }
+
+ function selectName(ts, cm) {
+ var name = findDoc(ts, cm.doc).name;
+ ts.request(cm, {type: "refs"}, function(error, data) {
+ if (error) return showError(ts, cm, error);
+ var ranges = [], cur = 0;
+ var curPos = cm.getCursor();
+ for (var i = 0; i < data.refs.length; i++) {
+ var ref = data.refs[i];
+ if (ref.file == name) {
+ ranges.push({anchor: ref.start, head: ref.end});
+ if (cmpPos(curPos, ref.start) >= 0 && cmpPos(curPos, ref.end) <= 0)
+ cur = ranges.length - 1;
+ }
+ }
+ cm.setSelections(ranges, cur);
+ });
+ }
+
+ var nextChangeOrig = 0;
+ function applyChanges(ts, changes) {
+ var perFile = Object.create(null);
+ for (var i = 0; i < changes.length; ++i) {
+ var ch = changes[i];
+ (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
+ }
+ for (var file in perFile) {
+ var known = ts.docs[file], chs = perFile[file];;
+ if (!known) continue;
+ chs.sort(function(a, b) { return cmpPos(b.start, a.start); });
+ var origin = "*rename" + (++nextChangeOrig);
+ for (var i = 0; i < chs.length; ++i) {
+ var ch = chs[i];
+ known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
+ }
+ }
+ }
+
+ // Generic request-building helper
+
+ function buildRequest(ts, doc, query, pos) {
+ var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
+ if (!allowFragments) delete query.fullDocs;
+ if (typeof query == "string") query = {type: query};
+ query.lineCharPositions = true;
+ if (query.end == null) {
+ query.end = pos || doc.doc.getCursor("end");
+ if (doc.doc.somethingSelected())
+ query.start = doc.doc.getCursor("start");
+ }
+ var startPos = query.start || query.end;
+
+ if (doc.changed) {
+ if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
+ doc.changed.to - doc.changed.from < 100 &&
+ doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
+ files.push(getFragmentAround(doc, startPos, query.end));
+ query.file = "#0";
+ var offsetLines = files[0].offsetLines;
+ if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
+ query.end = Pos(query.end.line - offsetLines, query.end.ch);
+ } else {
+ files.push({type: "full",
+ name: doc.name,
+ text: docValue(ts, doc)});
+ query.file = doc.name;
+ doc.changed = null;
+ }
+ } else {
+ query.file = doc.name;
+ }
+ for (var name in ts.docs) {
+ var cur = ts.docs[name];
+ if (cur.changed && cur != doc) {
+ files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
+ cur.changed = null;
+ }
+ }
+
+ return {query: query, files: files};
+ }
+
+ function getFragmentAround(data, start, end) {
+ var doc = data.doc;
+ var minIndent = null, minLine = null, endLine, tabSize = 4;
+ for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
+ var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
+ if (fn < 0) continue;
+ var indent = CodeMirror.countColumn(line, null, tabSize);
+ if (minIndent != null && minIndent <= indent) continue;
+ minIndent = indent;
+ minLine = p;
+ }
+ if (minLine == null) minLine = min;
+ var max = Math.min(doc.lastLine(), end.line + 20);
+ if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
+ endLine = max;
+ else for (endLine = end.line + 1; endLine < max; ++endLine) {
+ var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
+ if (indent <= minIndent) break;
+ }
+ var from = Pos(minLine, 0);
+
+ return {type: "part",
+ name: data.name,
+ offsetLines: from.line,
+ text: doc.getRange(from, Pos(endLine, 0))};
+ }
+
+ // Generic utilities
+
+ var cmpPos = CodeMirror.cmpPos;
+
+ function elt(tagname, cls /*, ... elts*/) {
+ var e = document.createElement(tagname);
+ if (cls) e.className = cls;
+ for (var i = 2; i < arguments.length; ++i) {
+ var elt = arguments[i];
+ if (typeof elt == "string") elt = document.createTextNode(elt);
+ e.appendChild(elt);
+ }
+ return e;
+ }
+
+ function dialog(cm, text, f) {
+ if (cm.openDialog)
+ cm.openDialog(text + ": ", f);
+ else
+ f(prompt(text, ""));
+ }
+
+ // Tooltips
+
+ function tempTooltip(cm, content, ts) {
+ if (cm.state.ternTooltip) remove(cm.state.ternTooltip);
+ var where = cm.cursorCoords();
+ var tip = cm.state.ternTooltip = makeTooltip(where.right + 1, where.bottom, content);
+ function maybeClear() {
+ old = true;
+ if (!mouseOnTip) clear();
+ }
+ function clear() {
+ cm.state.ternTooltip = null;
+ if (!tip.parentNode) return;
+ cm.off("cursorActivity", clear);
+ cm.off('blur', clear);
+ cm.off('scroll', clear);
+ fadeOut(tip);
+ }
+ var mouseOnTip = false, old = false;
+ CodeMirror.on(tip, "mousemove", function() { mouseOnTip = true; });
+ CodeMirror.on(tip, "mouseout", function(e) {
+ if (!CodeMirror.contains(tip, e.relatedTarget || e.toElement)) {
+ if (old) clear();
+ else mouseOnTip = false;
+ }
+ });
+ setTimeout(maybeClear, ts.options.hintDelay ? ts.options.hintDelay : 1700);
+ cm.on("cursorActivity", clear);
+ cm.on('blur', clear);
+ cm.on('scroll', clear);
+ }
+
+ function makeTooltip(x, y, content) {
+ var node = elt("div", cls + "tooltip", content);
+ node.style.left = x + "px";
+ node.style.top = y + "px";
+ document.body.appendChild(node);
+ return node;
+ }
+
+ function remove(node) {
+ var p = node && node.parentNode;
+ if (p) p.removeChild(node);
+ }
+
+ function fadeOut(tooltip) {
+ tooltip.style.opacity = "0";
+ setTimeout(function() { remove(tooltip); }, 1100);
+ }
+
+ function showError(ts, cm, msg) {
+ if (ts.options.showError)
+ ts.options.showError(cm, msg);
+ else
+ tempTooltip(cm, String(msg), ts);
+ }
+
+ function closeArgHints(ts) {
+ if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
+ }
+
+ function docValue(ts, doc) {
+ var val = doc.doc.getValue();
+ if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
+ return val;
+ }
+
+ // Worker wrapper
+
+ function WorkerServer(ts) {
+ var worker = ts.worker = new Worker(ts.options.workerScript);
+ worker.postMessage({type: "init",
+ defs: ts.options.defs,
+ plugins: ts.options.plugins,
+ scripts: ts.options.workerDeps});
+ var msgId = 0, pending = {};
+
+ function send(data, c) {
+ if (c) {
+ data.id = ++msgId;
+ pending[msgId] = c;
+ }
+ worker.postMessage(data);
+ }
+ worker.onmessage = function(e) {
+ var data = e.data;
+ if (data.type == "getFile") {
+ getFile(ts, data.name, function(err, text) {
+ send({type: "getFile", err: String(err), text: text, id: data.id});
+ });
+ } else if (data.type == "debug") {
+ window.console.log(data.message);
+ } else if (data.id && pending[data.id]) {
+ pending[data.id](data.err, data.body);
+ delete pending[data.id];
+ }
+ };
+ worker.onerror = function(e) {
+ for (var id in pending) pending[id](e);
+ pending = {};
+ };
+
+ this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
+ this.delFile = function(name) { send({type: "del", name: name}); };
+ this.request = function(body, c) { send({type: "req", body: body}, c); };
+ }
+});
diff --git a/codemirror/addon/tern/worker.js b/codemirror/addon/tern/worker.js
new file mode 100644
index 00000000..887f906a
--- /dev/null
+++ b/codemirror/addon/tern/worker.js
@@ -0,0 +1,44 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// declare global: tern, server
+
+var server;
+
+this.onmessage = function(e) {
+ var data = e.data;
+ switch (data.type) {
+ case "init": return startServer(data.defs, data.plugins, data.scripts);
+ case "add": return server.addFile(data.name, data.text);
+ case "del": return server.delFile(data.name);
+ case "req": return server.request(data.body, function(err, reqData) {
+ postMessage({id: data.id, body: reqData, err: err && String(err)});
+ });
+ case "getFile":
+ var c = pending[data.id];
+ delete pending[data.id];
+ return c(data.err, data.text);
+ default: throw new Error("Unknown message type: " + data.type);
+ }
+};
+
+var nextId = 0, pending = {};
+function getFile(file, c) {
+ postMessage({type: "getFile", name: file, id: ++nextId});
+ pending[nextId] = c;
+}
+
+function startServer(defs, plugins, scripts) {
+ if (scripts) importScripts.apply(null, scripts);
+
+ server = new tern.Server({
+ getFile: getFile,
+ async: true,
+ defs: defs,
+ plugins: plugins
+ });
+}
+
+this.console = {
+ log: function(v) { postMessage({type: "debug", message: v}); }
+};
diff --git a/codemirror/addon/wrap/hardwrap.js b/codemirror/addon/wrap/hardwrap.js
new file mode 100644
index 00000000..8806fbe2
--- /dev/null
+++ b/codemirror/addon/wrap/hardwrap.js
@@ -0,0 +1,142 @@
+// 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";
+
+ var Pos = CodeMirror.Pos;
+
+ function findParagraph(cm, pos, options) {
+ var startRE = options.paragraphStart || cm.getHelper(pos, "paragraphStart");
+ for (var start = pos.line, first = cm.firstLine(); start > first; --start) {
+ var line = cm.getLine(start);
+ if (startRE && startRE.test(line)) break;
+ if (!/\S/.test(line)) { ++start; break; }
+ }
+ var endRE = options.paragraphEnd || cm.getHelper(pos, "paragraphEnd");
+ for (var end = pos.line + 1, last = cm.lastLine(); end <= last; ++end) {
+ var line = cm.getLine(end);
+ if (endRE && endRE.test(line)) { ++end; break; }
+ if (!/\S/.test(line)) break;
+ }
+ return {from: start, to: end};
+ }
+
+ function findBreakPoint(text, column, wrapOn, killTrailingSpace) {
+ for (var at = column; at > 0; --at)
+ if (wrapOn.test(text.slice(at - 1, at + 1))) break;
+ for (var first = true;; first = false) {
+ var endOfText = at;
+ if (killTrailingSpace)
+ while (text.charAt(endOfText - 1) == " ") --endOfText;
+ if (endOfText == 0 && first) at = column;
+ else return {from: endOfText, to: at};
+ }
+ }
+
+ function wrapRange(cm, from, to, options) {
+ from = cm.clipPos(from); to = cm.clipPos(to);
+ var column = options.column || 80;
+ var wrapOn = options.wrapOn || /\s\S|-[^\.\d]/;
+ var killTrailing = options.killTrailingSpace !== false;
+ var changes = [], curLine = "", curNo = from.line;
+ var lines = cm.getRange(from, to, false);
+ if (!lines.length) return null;
+ var leadingSpace = lines[0].match(/^[ \t]*/)[0];
+
+ for (var i = 0; i < lines.length; ++i) {
+ var text = lines[i], oldLen = curLine.length, spaceInserted = 0;
+ if (curLine && text && !wrapOn.test(curLine.charAt(curLine.length - 1) + text.charAt(0))) {
+ curLine += " ";
+ spaceInserted = 1;
+ }
+ var spaceTrimmed = "";
+ if (i) {
+ spaceTrimmed = text.match(/^\s*/)[0];
+ text = text.slice(spaceTrimmed.length);
+ }
+ curLine += text;
+ if (i) {
+ var firstBreak = curLine.length > column && leadingSpace == spaceTrimmed &&
+ findBreakPoint(curLine, column, wrapOn, killTrailing);
+ // If this isn't broken, or is broken at a different point, remove old break
+ if (!firstBreak || firstBreak.from != oldLen || firstBreak.to != oldLen + spaceInserted) {
+ changes.push({text: [spaceInserted ? " " : ""],
+ from: Pos(curNo, oldLen),
+ to: Pos(curNo + 1, spaceTrimmed.length)});
+ } else {
+ curLine = leadingSpace + text;
+ ++curNo;
+ }
+ }
+ while (curLine.length > column) {
+ var bp = findBreakPoint(curLine, column, wrapOn, killTrailing);
+ changes.push({text: ["", leadingSpace],
+ from: Pos(curNo, bp.from),
+ to: Pos(curNo, bp.to)});
+ curLine = leadingSpace + curLine.slice(bp.to);
+ ++curNo;
+ }
+ }
+ if (changes.length) cm.operation(function() {
+ for (var i = 0; i < changes.length; ++i) {
+ var change = changes[i];
+ if (change.text || CodeMirror.cmpPos(change.from, change.to))
+ cm.replaceRange(change.text, change.from, change.to);
+ }
+ });
+ return changes.length ? {from: changes[0].from, to: CodeMirror.changeEnd(changes[changes.length - 1])} : null;
+ }
+
+ CodeMirror.defineExtension("wrapParagraph", function(pos, options) {
+ options = options || {};
+ if (!pos) pos = this.getCursor();
+ var para = findParagraph(this, pos, options);
+ return wrapRange(this, Pos(para.from, 0), Pos(para.to - 1), options);
+ });
+
+ CodeMirror.commands.wrapLines = function(cm) {
+ cm.operation(function() {
+ var ranges = cm.listSelections(), at = cm.lastLine() + 1;
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var range = ranges[i], span;
+ if (range.empty()) {
+ var para = findParagraph(cm, range.head, {});
+ span = {from: Pos(para.from, 0), to: Pos(para.to - 1)};
+ } else {
+ span = {from: range.from(), to: range.to()};
+ }
+ if (span.to.line >= at) continue;
+ at = span.from.line;
+ wrapRange(cm, span.from, span.to, {});
+ }
+ });
+ };
+
+ CodeMirror.defineExtension("wrapRange", function(from, to, options) {
+ return wrapRange(this, from, to, options || {});
+ });
+
+ CodeMirror.defineExtension("wrapParagraphsInRange", function(from, to, options) {
+ options = options || {};
+ var cm = this, paras = [];
+ for (var line = from.line; line <= to.line;) {
+ var para = findParagraph(cm, Pos(line, 0), options);
+ paras.push(para);
+ line = para.to;
+ }
+ var madeChange = false;
+ if (paras.length) cm.operation(function() {
+ for (var i = paras.length - 1; i >= 0; --i)
+ madeChange = madeChange || wrapRange(cm, Pos(paras[i].from, 0), Pos(paras[i].to - 1), options);
+ });
+ return madeChange;
+ });
+});
diff --git a/codemirror/lib/codemirror.css b/codemirror/lib/codemirror.css
new file mode 100644
index 00000000..1067b3ee
--- /dev/null
+++ b/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 actual 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/codemirror/lib/codemirror.js b/codemirror/lib/codemirror.js
new file mode 100644
index 00000000..942ad1f3
--- /dev/null
+++ b/codemirror/lib/codemirror.js
@@ -0,0 +1,8887 @@
+// 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 || window).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.checkedZeroWidth = 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.checkedZeroWidth && measure.clientHeight > 0) {
+ if (sWidth == 0) this.zeroWidthHack();
+ this.checkedZeroWidth = true;
+ }
+
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
+ },
+ setScrollLeft: function(pos) {
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
+ if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
+ },
+ setScrollTop: function(pos) {
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
+ if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
+ },
+ zeroWidthHack: function() {
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
+ this.horiz.style.height = this.vert.style.width = w;
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
+ this.disableHoriz = new Delayed;
+ this.disableVert = new Delayed;
+ },
+ enableZeroWidthBar: function(bar, delay) {
+ bar.style.pointerEvents = "auto";
+ function maybeDisable() {
+ // To find out whether the scrollbar is still visible, we
+ // check whether the element under the pixel in the bottom
+ // left corner of the scrollbar box is the scrollbar box
+ // itself (when the bar is still visible) or its filler child
+ // (when the bar is hidden). If it is still visible, we keep
+ // it enabled, if it's hidden, we disable pointer events.
+ var box = bar.getBoundingClientRect();
+ var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
+ if (elt != bar) bar.style.pointerEvents = "none";
+ else delay.set(1000, maybeDisable);
+ }
+ delay.set(1000, maybeDisable);
+ },
+ 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.parentNode.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); }
+ }
+
+ // 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 (!cm.isReadOnly() && !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 (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
+
+ 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) || signalDOMEvent(cm, 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) ||
+ cm.isReadOnly() || 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) {
+ if (!signalDOMEvent(cm, 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 (cm.isReadOnly() || !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) {
+ if (!gecko && this.cm.state.focused) {
+ sel.collapse(start.node, start.offset);
+ if (!rng.collapsed) sel.addRange(rng);
+ } else {
+ 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 (this.cm.isReadOnly())
+ 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 (!this.cm.isReadOnly())
+ 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, options) {
+ 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));
+ },
+ origin: options && options.origin
+ };
+ 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, options);
+
+ 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 old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
+ var newHead = skipAtomic(doc, range.head, old && old.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;
+ }
+
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+ var line = getLine(doc, pos.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 <= pos.ch : sp.from < pos.ch)) &&
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) break;
+ else {--i; continue;}
+ }
+ }
+ if (!m.atomic) continue;
+
+ if (oldPos) {
+ var near = m.find(dir < 0 ? 1 : -1), diff;
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) near = movePos(doc, near, -dir, line);
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
+ return skipAtomicInner(doc, near, pos, dir, mayClear);
+ }
+
+ var far = m.find(dir < 0 ? -1 : 1);
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) far = movePos(doc, far, dir, line);
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
+ }
+ }
+ return pos;
+ }
+
+ // Ensure a given position is not inside an atomic range.
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
+ var dir = bias || 1;
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
+ if (!found) {
+ doc.cantEdit = true;
+ return Pos(doc.first, 0);
+ }
+ return found;
+ }
+
+ function movePos(doc, pos, dir, line) {
+ if (dir < 0 && pos.ch == 0) {
+ if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
+ else return null;
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
+ if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
+ else return null;
+ } else {
+ return new Pos(pos.line, pos.ch + dir);
+ }
+ }
+
+ // 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() && (!document.hasFocus || document.hasFocus()))
+ 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 && !cm.isReadOnly() &&
+ 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) {
+ 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];
+ signal(cm, type, cm, line, gutter, e);
+ return e_defaultPrevented(e);
+ }
+ }
+ }
+
+ function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true);
+ }
+
+ // 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 || cm.isReadOnly()) 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 (cm.isReadOnly()) 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);
+ }
+
+ // 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), pos, 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(); },
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
+
+ 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.parentNode.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 = [], endStyles
+ 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 = (css ? css + ";" : "") + m.css;
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
+ if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
+ 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 (endStyles) for (var j = 0; j < endStyles.length; j += 2)
+ if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
+
+ 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;
+ this.extend = false;
+
+ 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) {
+ var heads = map(this.sel.ranges, f);
+ extendSelections(this, clipPosArray(this, heads), 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.10.0";
+
+ return CodeMirror;
+});
diff --git a/codemirror/mode/javascript/javascript.js b/codemirror/mode/javascript/javascript.js
new file mode 100644
index 00000000..d4ae6687
--- /dev/null
+++ b/codemirror/mode/javascript/javascript.js
@@ -0,0 +1,731 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// TODO actually recognize syntax of TypeScript constructs
+
+(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("javascript", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var statementIndent = parserConfig.statementIndent;
+ var jsonldMode = parserConfig.jsonld;
+ var jsonMode = parserConfig.json || jsonldMode;
+ var isTS = parserConfig.typescript;
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
+
+ // Tokenizer
+
+ var keywords = function(){
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+
+ var jsKeywords = {
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+ "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C,
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
+ "function": kw("function"), "catch": kw("catch"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "typeof": operator, "instanceof": operator,
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C
+ };
+
+ // Extend the 'normal' keywords with the TypeScript language extensions
+ if (isTS) {
+ var type = {type: "variable", style: "variable-3"};
+ var tsKeywords = {
+ // object-like things
+ "interface": kw("class"),
+ "implements": C,
+ "namespace": C,
+ "module": kw("module"),
+ "enum": kw("module"),
+
+ // scope modifiers
+ "public": kw("modifier"),
+ "private": kw("modifier"),
+ "protected": kw("modifier"),
+ "abstract": kw("modifier"),
+
+ // operators
+ "as": operator,
+
+ // types
+ "string": type, "number": type, "boolean": type, "any": type
+ };
+
+ for (var attr in tsKeywords) {
+ jsKeywords[attr] = tsKeywords[attr];
+ }
+ }
+
+ return jsKeywords;
+ }();
+
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+
+ function readRegexp(stream) {
+ var escaped = false, next, inSet = false;
+ while ((next = stream.next()) != null) {
+ if (!escaped) {
+ if (next == "/" && !inSet) return;
+ if (next == "[") inSet = true;
+ else if (inSet && next == "]") inSet = false;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ }
+
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
+ return ret("number", "number");
+ } else if (ch == "." && stream.match("..")) {
+ return ret("spread", "meta");
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "=" && stream.eat(">")) {
+ return ret("=>", "operator");
+ } else if (ch == "0" && stream.eat(/x/i)) {
+ stream.eatWhile(/[\da-f]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/o/i)) {
+ stream.eatWhile(/[0-7]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/b/i)) {
+ stream.eatWhile(/[01]/i);
+ return ret("number", "number");
+ } else if (/\d/.test(ch)) {
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+ return ret("number", "number");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else if (/^(?:operator|sof|keyword c|case|new|[\[{}\(,;:])$/.test(state.lastType) ||
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - 1)))) {
+ readRegexp(stream);
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
+ return ret("regexp", "string-2");
+ } else {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current());
+ }
+ } else if (ch == "`") {
+ state.tokenize = tokenQuasi;
+ return tokenQuasi(stream, state);
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return ret("error", "error");
+ } else if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current());
+ } else if (wordRE.test(ch)) {
+ stream.eatWhile(wordRE);
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
+ ret("variable", "variable", word);
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next;
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
+ state.tokenize = tokenBase;
+ return ret("jsonld-keyword", "meta");
+ }
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) break;
+ escaped = !escaped && next == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenQuasi(stream, state) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ return ret("quasi", "string-2", stream.current());
+ }
+
+ var brackets = "([{}])";
+ // This is a crude lookahead trick to try and notice that we're
+ // parsing the argument patterns for a fat-arrow function before we
+ // actually hit the arrow token. It only works if the arrow is on
+ // the same line as the arguments and there's no strange noise
+ // (comments) in between. Fallback is to only notice when we hit the
+ // arrow, and not declare the arguments as locals for the arrow
+ // body.
+ function findFatArrow(stream, state) {
+ if (state.fatArrowAt) state.fatArrowAt = null;
+ var arrow = stream.string.indexOf("=>", stream.start);
+ if (arrow < 0) return;
+
+ var depth = 0, sawSomething = false;
+ for (var pos = arrow - 1; pos >= 0; --pos) {
+ var ch = stream.string.charAt(pos);
+ var bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (!depth) { ++pos; break; }
+ if (--depth == 0) break;
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.test(ch)) {
+ sawSomething = true;
+ } else if (/["'\/]/.test(ch)) {
+ return;
+ } else if (sawSomething && !depth) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && !depth) state.fatArrowAt = pos;
+ }
+
+ // Parser
+
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
+
+ function JSLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
+
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ for (var cx = state.context; cx; cx = cx.prev) {
+ for (var v = cx.vars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+ }
+
+ function parseJS(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
+
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
+
+ while(true) {
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ return style;
+ }
+ }
+ }
+
+ // Combinator utils
+
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+ function register(varname) {
+ function inList(list) {
+ for (var v = list; v; v = v.next)
+ if (v.name == varname) return true;
+ return false;
+ }
+ var state = cx.state;
+ cx.marked = "def";
+ if (state.context) {
+ if (inList(state.localVars)) return;
+ state.localVars = {name: varname, next: state.localVars};
+ } else {
+ if (inList(state.globalVars)) return;
+ if (parserConfig.globalVars)
+ state.globalVars = {name: varname, next: state.globalVars};
+ }
+ }
+
+ // Combinators
+
+ var defaultVars = {name: "this", next: {name: "arguments"}};
+ function pushcontext() {
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+ cx.state.localVars = defaultVars;
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars;
+ cx.state.context = cx.state.context.prev;
+ }
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state, indent = state.indented;
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ }
+ poplex.lex = true;
+
+ function expect(wanted) {
+ function exp(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";") return pass();
+ else return cont(exp);
+ };
+ return exp;
+ }
+
+ function statement(type, value) {
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "{") return cont(pushlex("}"), block, poplex);
+ if (type == ";") return cont();
+ if (type == "if") {
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
+ cx.state.cc.pop()();
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
+ }
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+ block, poplex, poplex);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+ statement, poplex, popcontext);
+ if (type == "class") return cont(pushlex("form"), className, poplex);
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
+ if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function expression(type) {
+ return expressionInner(type, false);
+ }
+ function expressionNoComma(type) {
+ return expressionInner(type, true);
+ }
+ function expressionInner(type, noComma) {
+ if (cx.state.fatArrowAt == cx.stream.start) {
+ var body = noComma ? arrowBodyNoComma : arrowBody;
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
+ }
+
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+ if (type == "function") return cont(functiondef, maybeop);
+ if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
+ if (type == "quasi") return pass(quasi, maybeop);
+ if (type == "new") return cont(maybeTarget(noComma));
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+ function maybeexpressionNoComma(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expressionNoComma);
+ }
+
+ function maybeoperatorComma(type, value) {
+ if (type == ",") return cont(expression);
+ return maybeoperatorNoComma(type, value, false);
+ }
+ function maybeoperatorNoComma(type, value, noComma) {
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+ var expr = noComma == false ? expression : expressionNoComma;
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
+ if (type == "operator") {
+ if (/\+\+|--/.test(value)) return cont(me);
+ if (value == "?") return cont(expression, expect(":"), expr);
+ return cont(expr);
+ }
+ if (type == "quasi") { return pass(quasi, me); }
+ if (type == ";") return;
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
+ if (type == ".") return cont(property, me);
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+ }
+ function quasi(type, value) {
+ if (type != "quasi") return pass();
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
+ return cont(expression, continueQuasi);
+ }
+ function continueQuasi(type) {
+ if (type == "}") {
+ cx.marked = "string-2";
+ cx.state.tokenize = tokenQuasi;
+ return cont(quasi);
+ }
+ }
+ function arrowBody(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expression);
+ }
+ function arrowBodyNoComma(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expressionNoComma);
+ }
+ function maybeTarget(noComma) {
+ return function(type) {
+ if (type == ".") return cont(noComma ? targetNoComma : target);
+ else return pass(noComma ? expressionNoComma : expression);
+ };
+ }
+ function target(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
+ }
+ function targetNoComma(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
+ }
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperatorComma, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(getterSetter);
+ return cont(afterprop);
+ } else if (type == "number" || type == "string") {
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
+ return cont(afterprop);
+ } else if (type == "jsonld-keyword") {
+ return cont(afterprop);
+ } else if (type == "modifier") {
+ return cont(objprop)
+ } else if (type == "[") {
+ return cont(expression, expect("]"), afterprop);
+ } else if (type == "spread") {
+ return cont(expression);
+ }
+ }
+ function getterSetter(type) {
+ if (type != "variable") return pass(afterprop);
+ cx.marked = "property";
+ return cont(functiondef);
+ }
+ function afterprop(type) {
+ if (type == ":") return cont(expressionNoComma);
+ if (type == "(") return pass(functiondef);
+ }
+ function commasep(what, end) {
+ function proceed(type) {
+ if (type == ",") {
+ var lex = cx.state.lexical;
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+ return cont(what, proceed);
+ }
+ if (type == end) return cont();
+ return cont(expect(end));
+ }
+ return function(type) {
+ if (type == end) return cont();
+ return pass(what, proceed);
+ };
+ }
+ function contCommasep(what, end, info) {
+ for (var i = 3; i < arguments.length; i++)
+ cx.cc.push(arguments[i]);
+ return cont(pushlex(end, info), commasep(what, end), poplex);
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function maybetype(type) {
+ if (isTS && type == ":") return cont(typedef);
+ }
+ function maybedefault(_, value) {
+ if (value == "=") return cont(expressionNoComma);
+ }
+ function typedef(type) {
+ if (type == "variable") {cx.marked = "variable-3"; return cont();}
+ }
+ function vardef() {
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
+ }
+ function pattern(type, value) {
+ if (type == "modifier") return cont(pattern)
+ if (type == "variable") { register(value); return cont(); }
+ if (type == "spread") return cont(pattern);
+ if (type == "[") return contCommasep(pattern, "]");
+ if (type == "{") return contCommasep(proppattern, "}");
+ }
+ function proppattern(type, value) {
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
+ register(value);
+ return cont(maybeAssign);
+ }
+ if (type == "variable") cx.marked = "property";
+ if (type == "spread") return cont(pattern);
+ return cont(expect(":"), pattern, maybeAssign);
+ }
+ function maybeAssign(_type, value) {
+ if (value == "=") return cont(expressionNoComma);
+ }
+ function vardefCont(type) {
+ if (type == ",") return cont(vardef);
+ }
+ function maybeelse(type, value) {
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
+ }
+ function forspec(type) {
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
+ }
+ function forspec1(type) {
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
+ if (type == ";") return cont(forspec2);
+ if (type == "variable") return cont(formaybeinof);
+ return pass(expression, expect(";"), forspec2);
+ }
+ function formaybeinof(_type, value) {
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return cont(maybeoperatorComma, forspec2);
+ }
+ function forspec2(type, value) {
+ if (type == ";") return cont(forspec3);
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return pass(expression, expect(";"), forspec3);
+ }
+ function forspec3(type) {
+ if (type != ")") cont(expression);
+ }
+ function functiondef(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
+ if (type == "variable") {register(value); return cont(functiondef);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
+ }
+ function funarg(type) {
+ if (type == "spread") return cont(funarg);
+ return pass(pattern, maybetype, maybedefault);
+ }
+ function className(type, value) {
+ if (type == "variable") {register(value); return cont(classNameAfter);}
+ }
+ function classNameAfter(type, value) {
+ if (value == "extends") return cont(expression, classNameAfter);
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
+ }
+ function classBody(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ if (value == "static") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
+ return cont(functiondef, classBody);
+ }
+ if (value == "*") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == ";") return cont(classBody);
+ if (type == "}") return cont();
+ }
+ function classGetterSetter(type) {
+ if (type != "variable") return pass();
+ cx.marked = "property";
+ return cont();
+ }
+ function afterExport(_type, value) {
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
+ return pass(statement);
+ }
+ function afterImport(type) {
+ if (type == "string") return cont();
+ return pass(importSpec, maybeFrom);
+ }
+ function importSpec(type, value) {
+ if (type == "{") return contCommasep(importSpec, "}");
+ if (type == "variable") register(value);
+ if (value == "*") cx.marked = "keyword";
+ return cont(maybeAs);
+ }
+ function maybeAs(_type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
+ }
+ function maybeFrom(_type, value) {
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
+ }
+ function arrayLiteral(type) {
+ if (type == "]") return cont();
+ return pass(expressionNoComma, maybeArrayComprehension);
+ }
+ function maybeArrayComprehension(type) {
+ if (type == "for") return pass(comprehension, expect("]"));
+ if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
+ return pass(commasep(expressionNoComma, "]"));
+ }
+ function comprehension(type) {
+ if (type == "for") return cont(forspec, comprehension);
+ if (type == "if") return cont(expression, comprehension);
+ }
+
+ function isContinuedStatement(state, textAfter) {
+ return state.lastType == "operator" || state.lastType == "," ||
+ isOperatorChar.test(textAfter.charAt(0)) ||
+ /[,.]/.test(textAfter.charAt(0));
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ var state = {
+ tokenize: tokenBase,
+ lastType: "sof",
+ cc: [],
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
+ indented: 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ findFatArrow(stream, state);
+ }
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+ return parseJS(state, style, type, content, stream);
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
+ if (state.tokenize != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
+ var c = state.cc[i];
+ if (c == poplex) lexical = lexical.prev;
+ else if (c != maybeelse) break;
+ }
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+ lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "form") return lexical.indented + indentUnit;
+ else if (type == "stat")
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
+ blockCommentStart: jsonMode ? null : "/*",
+ blockCommentEnd: jsonMode ? null : "*/",
+ lineComment: jsonMode ? null : "//",
+ fold: "brace",
+ closeBrackets: "()[]{}''\"\"``",
+
+ helperType: jsonMode ? "json" : "javascript",
+ jsonldMode: jsonldMode,
+ jsonMode: jsonMode
+ };
+});
+
+CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/javascript", "javascript");
+CodeMirror.defineMIME("application/x-javascript", "javascript");
+CodeMirror.defineMIME("application/ecmascript", "javascript");
+CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
+CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
+
+});
diff --git a/dex.js b/dex.js
new file mode 100644
index 00000000..1f9feb8f
--- /dev/null
+++ b/dex.js
@@ -0,0 +1,344 @@
+/**
+ * Created by Fry on 1/17/16.
+ */
+
+function dex(){} //just a namespace
+
+dex.train_task_names = [] //don't put this in the init as we want it to persist accross tasks, whe user clicks New task
+dex.train_dex_pos_x = 0
+dex.train_dex_pos_y = 0
+dex.train_dex_pos_z = 0
+dex.train_gripper_opening = 0
+
+dex.init_train = function(){
+ // these are per training window use and get reinited when new training window is opened
+ dex.train_task_name = ""
+ dex.train_action_names = []
+ dex.train_action_name_to_pure_code = {} //keys of action names, values of the code without function prefix or trailing comments.
+ //dex.train_number_of_insertions = 0
+ dex.train_halt_the_pause_by_example = false
+ dex.train_pause_start_ms = 0
+ dex.train_task_for_loops_made = 0
+}
+
+dex.post_creation_window_init = function(){
+ var vals = {} //we don't have any as we're just initing
+ var new_win_default_name = "task_" + (dex.train_task_names.length + 1)
+ dex.set_in_window(undefined, "task_name", "value", new_win_default_name)
+ dex.fill_in_task_names(vals)
+}
+
+dex.get_dexter_position = function(){
+ return [dex.train_dex_pos_x, dex.train_dex_pos_y, dex.train_dex_pos_z]
+}
+
+dex.set_dexter_position = function(array3){
+ dex.train_dex_pos_x = array3[0]
+ dex.train_dex_pos_y = array3[1]
+ dex.train_dex_pos_z = array3[2]
+}
+
+dex.handle_train_task_fn_start = function(vals){
+ //returns empty string unless the "function ..." code needed, in which case it returns it
+ var fn_start = ""
+ if(dex.train_action_names.length == 0){
+ dex.train_task_name = vals.task_name
+ fn_start = "function " + clean_action_or_task_name(vals.task_name) + "(){ //task \n"
+ }
+ return fn_start
+}
+
+dex.simulate_user_moving_dexter = function(){
+ dex.train_dex_pos_x = Math.floor(Math.random() * 600)
+ dex.train_dex_pos_y = Math.floor(Math.random() * 600)
+ dex.train_dex_pos_z = Math.floor(Math.random() * 600)
+}
+
+dex.fill_in_empty_position_values_from_dexter = function(vals){
+ var val_names_from_dexter = []
+ if ((vals.x == "") || (vals.x == null)) {vals.x = dex.train_dex_pos_x; val_names_from_dexter.push("x")}
+ if ((vals.y == "") || (vals.y == null)) {vals.y = dex.train_dex_pos_y; val_names_from_dexter.push("y")}
+ if ((vals.z == "") || (vals.z == null)) {vals.z = dex.train_dex_pos_z; val_names_from_dexter.push("z")}
+ return val_names_from_dexter
+}
+
+dex.insert_etc = function(pure_code, code, vals){
+ Editor.insert(code)
+ //dex.train_number_of_insertions += 1 //the next index
+ dex.train_action_name_to_pure_code[clean_action_or_task_name(vals.action_name)] = pure_code //for Do action button
+ dex.train_action_names.push(clean_action_or_task_name(vals.action_name))
+ var action_options = ""
+ for(var act of dex.train_action_names){
+ action_options += "
" + act + "
"
+ }
+ dex.set_in_window(vals.window_index, "do_action_action_names", "innerHTML", action_options)
+ dex.set_in_window(vals.window_index, "repeat_from_action_names", "innerHTML", action_options)
+ dex.set_in_window(vals.window_index, "repeat_through_action_names", "innerHTML", action_options)
+
+ var new_action_name_default = "action_" + (dex.train_action_names.length + 1) //make this 1 baed so that the instruction "click to add the 1st action ..." will make most sense.
+ dex.set_in_window(vals.window_index, "action_name", "value", new_action_name_default)
+ dex.replace_top_instruction_line(vals)
+}
+
+dex.replace_top_instruction_line = function(vals, text){
+ if (text == null){
+ var index = dex.train_action_names.length + 1
+ var index_string = integer_to_ordinal(index)
+ text = "Click on a button below to add the " + index_string + " action to this task."
+ }
+ text = "" + text + "">
+ dex.set_in_window(vals.window_index, "top_instruction_line", "innerHTML", text)
+}
+
+//might be general utility so don't put it in dex package
+function integer_to_ordinal(int){
+//Given an integer, return the appropriate string.
+//use "th" except if last digit is 1, 2, 3, except if we're between 11 and 13 inclusive.
+ var int_str = "" + int
+ var last_char = int_str[int_str.length - 1]
+ var last_int = parseInt(last_char)
+ var suffix
+ if (int == 11) suffix = "th"
+ else if (int == 12) suffix = "th"
+ else if (int == 13) suffix = "th"
+ else if (last_int == 1) suffix = "st"
+ else if (last_int == 2) suffix = "nd"
+ else if (last_int == 3) suffix = "rd"
+ else suffix = "th"
+ return int + suffix
+}
+
+
+dex.fill_in_task_names = function(vals){ //just called by New task
+ /* var task_options = ""
+ for (var task of dex.train_task_names){ //train_task_names whne this is called in new Task,
+ //has just been extended with vals.task_name but
+ //don't worry about recursion because we are now
+ //getting OUT of the cur task and into a new one.
+ task_options += "
"
+ }
+ dex.set_in_window(vals.window_index, "task_names_datalist", "innerHTML", task_options)
+ */
+ dex.set_in_window(vals.window_index, "task_names", "combo_box_options", dex.train_task_names)
+}
+
+
+dex.set_in_window = function(window_index, elt_name, elt_attr_name, new_value){
+ var jqxw_jq = get_window_of_index(window_index)
+ var elt_jq = jqxw_jq.find("[name='" + elt_name + "']")
+ if (elt_attr_name == "innerHTML") {elt_jq[0].innerHTML = new_value}
+ else if (elt_attr_name == "value") {elt_jq[0].value = new_value}
+ else if (elt_attr_name.startsWith("style.")){
+ var style_prop = elt_attr_name.split(".")[1]
+ elt_jq.css(style_prop, new_value)
+ }
+ else if (elt_attr_name == "combo_box_options"){
+ elt_jq.jqxComboBox({source: new_value, selectedIndex: 0})
+ }
+ else {elt_jq.attr(elt_attr_name, new_value)}
+}
+
+function clean_action_or_task_name(name){
+ name = name.trim()
+ name = name.replace(/ /g, " ") //replace 3 spaces with 1
+ name = name.replace(/ /g, " ") //replace 2 spaces with 1
+ name = name.replace(/ /g, "_") //replace 1 space with underscore
+ return name
+}
+
+//in sandbox
+function dex_handle_train(vals){ //not dex.handle_train because then I can't use the name in the show_window 2nd arg.
+ //don't insert fn_start UNTIL the user does the first real action insert, so as making canceling easier
+ if (vals.clicked_button_value == "Move"){
+ dex.simulate_user_moving_dexter()
+ var val_names_from_dexter = dex.fill_in_empty_position_values_from_dexter(vals)
+ var val_names_string = val_names_from_dexter.join(",")
+ if (val_names_string != ""){
+ val_names_string = val_names_string + " came from Dexter."
+ }
+ var pure_code = " dex.move_to(" + vals.x + ", " + vals.y + ", " + vals.z + ")"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code + " //" +
+ clean_action_or_task_name(vals.action_name) + " " + val_names_string + "\n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ else if (vals.clicked_button_value == "Relative move"){
+ var pure_code = " dex.relative_move_to(" + vals.rel_x + ", " + vals.rel_y + ", " + vals.rel_z + ")"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code + " //" + clean_action_or_task_name(vals.action_name) + " \n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ else if (vals.clicked_button_value == "Pause"){
+ var secs = vals.pause_seconds
+ if ((secs == null) || ((typeof(secs) == "string") && (secs.trim() == ""))) {
+ dex.train_halt_the_pause_by_example = false
+ dex.train_pause_start_ms = new Date().valueOf()
+ var fn = function(){
+ var ending_ms = new Date().valueOf()
+ var secs = (ending_ms - dex.train_pause_start_ms) / 1000.0
+ var the_window_index = vals.window_index
+ dex.set_in_window(the_window_index, "pause_seconds", "value", secs)
+ if (dex.train_halt_the_pause_by_example){
+ var pure_code = " dex.pause_for(" + secs + ")"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code + " //" + clean_action_or_task_name(vals.action_name) + " \n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ else {
+ setTimeout(arguments.callee, 100)
+ }
+ }
+ setTimeout(fn, 100)
+ }
+ else {
+ var pure_code = " dex.pause_for(" + secs + ")"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code + " //" + clean_action_or_task_name(vals.action_name) + " \n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ }
+ else if (vals.clicked_button_value == "Stop"){
+ dex.train_halt_the_pause_by_example = true
+ }
+ else if (vals.clicked_button_value == "Do action"){
+ //can't have any fn prefix because this can't be the first action, because no actions to copy
+ var orig_action_name = vals.do_action_action_names
+ var pure_code = dex.train_action_name_to_pure_code[orig_action_name] //should get the chosed value
+ var code = pure_code + " //" + clean_action_or_task_name(vals.action_name) + //should be the NEW action name, not the one we're copying
+ " originally from: " + orig_action_name + " \n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ else if (vals.clicked_button_value == "Do task"){
+ var do_task_name = vals.task_names
+ if (do_task_name == clean_action_or_task_name(vals.task_name)){
+ out("Error: Do not specify to 'Do task' of " +
+ "the current task you're creating because " +
+ "that would cause infinite recursion. ", "red")
+ }
+ else if (do_task_name == ""){
+ out("Error: You did not specify a task name to do. ", "red")
+ }
+ else{
+ var pure_code = " " + do_task_name + "()"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code +
+ " //" + clean_action_or_task_name(vals.action_name) + " \n"
+ dex.insert_etc(pure_code, code, vals)
+ }
+ }
+ else if (vals.clicked_button_value == "Set gripper opening"){
+ var pure_code = " dex.set_gripper_opening(" + vals.gripper_opening + ")"
+ var code = dex.handle_train_task_fn_start(vals) + pure_code + " //" + clean_action_or_task_name(vals.action_name) + " \n" //should be the NEW action name, not the one we're copying
+ dex.insert_etc(pure_code, code, vals)
+ }
+
+ else if (vals.clicked_button_value == "Repeat"){
+ Editor.train_for_loop_insert(clean_action_or_task_name(vals.task_name),
+ vals.repeat_from_action_names,
+ vals.repeat_through_action_names,
+ vals.repeat_times,
+ dex.train_task_for_loops_made) //so that on 2nd for loop, its var will be named j, not i
+ dex.train_task_for_loops_made += 1
+ }
+ else if (vals.clicked_button_value == "Run Task"){
+ Editor.run_unfinished_task(vals.task_name)
+ }
+ else if (vals.clicked_button_value == "New Task"){
+ if (dex.train_action_names.length > 0){ //otherwise vals.task_name isn't a real task name
+ Editor.insert("}\n\n" + clean_action_or_task_name(vals.task_name) + "() //eval to perform this task\n\n")
+ dex.train_task_names.push(clean_action_or_task_name(vals.task_name))
+ dex.fill_in_task_names(vals)
+ dex.replace_top_instruction_line(vals, "Click a button below to start this new task.")
+ }
+ dex.init_train()
+ var new_default_task_name = "task_" + (dex.train_task_names.length + 1)//1 based names, just line action names need to be
+ dex.set_in_window(vals.window_index, "task_name", "value", new_default_task_name)
+ dex.set_in_window(vals.window_index, "action_name", "value", "action_1")
+ }
+ else if (vals.clicked_button_value == "Done"){
+ if (dex.train_action_names.length > 0){ //otherwise we havent' made a real task.
+ Editor.insert("}\n\n" + clean_action_or_task_name(vals.task_name) + "() //eval to perform this task\n\n")
+ dex.train_task_names.push(clean_action_or_task_name(vals.task_name))
+ }
+ }
+}
+//var next_index_for_task_default_name = 0 //must be here for ui env, can't use length of tasks becaue that's in snadvox
+
+dex.train = function(){ //happens in ui env, called from Insert menu item when user chooses "train" item
+ dex.init_train()
+ var task_name = "task_" //+ (dex.train_task_names.length + 1)
+ //next_index_for_task_default_name += 1
+ show_window({content:
+`
Click on a button below to add the first action to this task.
+Task Name:
+
+Action Name:
+
+
+ to
+ x:
+ y:
+ z:
+
+ to
+ x:
+ y:
+ z:
+
+
+ for seconds.
+
+
+
+ again.
+
+
+
+ from
+ through
+ ,
+ times.
+
+ to
+ mm.
+
+
+
+
+
+
+
+`,
+ title: '' +
+ 'Train Dexter (simulation only)',
+ width:480, height:410, callback: dex_handle_train
+})
+ setTimeout(function(){dex.post_creation_window_init()}, 100) //needed to init the combo box for actions
+
+}
+
+dex.move_to = function(x, y ,z){
+ dex.set_dexter_position([x, y, z])
+ out("Dexter moved to: " + x +", " + y + ", " + z, "#338833")
+}
+
+dex.relative_move_to = function(x, y ,z){
+ var dex_pos = dex.get_dexter_position()
+ var new_x = dex_pos[0] + x
+ var new_y = dex_pos[1] + y
+ var new_z = dex_pos[2] + z
+ dex.set_dexter_position([new_x, new_y, new_z])
+ out("Dexter moved to: " + new_x +", " + new_y + ", " + new_z, "#338833")
+}
+
+dex.pause_for = function(seconds){
+ out("Dexter pausing for: " + seconds + " seconds.", "#338833")
+}
+
+dex.set_gripper_opening = function(width){
+ dex.train_gripper_opening = width
+ out("Dexter gripper opening is: " + width, "#338833")
+}
+
diff --git a/dexter_128.png b/dexter_128.png
new file mode 100644
index 00000000..4d5eb191
Binary files /dev/null and b/dexter_128.png differ
diff --git a/dexter_16.png b/dexter_16.png
new file mode 100644
index 00000000..3f6a34d1
Binary files /dev/null and b/dexter_16.png differ
diff --git a/dextersim.js b/dextersim.js
new file mode 100644
index 00000000..c962f563
--- /dev/null
+++ b/dextersim.js
@@ -0,0 +1,226 @@
+/* Created by Fry on 3/30/16.*/
+//whole file loaded in ui env only as is tcp
+DexterSim = class DexterSim{
+ constructor({robot_name = "required"}){
+ this.robot_name = robot_name
+ this.rs = Dexter.make_default_status_array()
+ this.instruction_queue = []
+ this.completed_instructions = []
+ this.status = "before_first_send"
+ this.sent_instructions_count = 0
+ this.now_processing_instruction = null //a Dexter can only be doing at most 1 instruction at a time. This is it.
+ DexterSim.robot_name_to_dextersim_instance_map[robot_name] = this
+ Socket.new_socket_callback(robot_name)
+ }
+
+ static create(robot_name){
+ new DexterSim({robot_name: robot_name})
+ }
+
+ static send(robot_name, instruction_array){
+ //out("Sim.send passed instruction_array: " + instruction_array + " robot_name: " + robot_name)
+ let the_inst = DexterSim.robot_name_to_dextersim_instance_map[robot_name]
+ the_inst.sent_instructions_count += 1
+ if (the_inst.status == "closing"){
+ shouldnt("In a_DexterSim.send with robot_name: " + robot_name +
+ " passed instruction_array: " + instruction_array +
+ " but it shouldn't be called at all because a_DexterSim.status == 'closing'.")
+ }
+ let prev_status = the_inst.status
+ the_inst.status = "after_first_send"
+
+ let oplet = instruction_array[Dexter.INSTRUCTION_TYPE]
+ switch(oplet){
+ case "E": //empty_instruction_queue_immediately
+ out("In simulating Dexter at robot_name: " + the_inst.robot_name +
+ ", an E instruction (empty_instruction_queue_immediately), is " +
+ "deleting " + the_inst.instruction_queue.length + " instructions: " +
+ the_inst.instruction_queue.join(" ") +
+ " from the queue that will never be run.")
+ the_inst.instruction_queue = []
+ the_inst.ack_reply(instruction_array)
+ break;
+ case "F": //empty_instruction_queue, //waits to be "executed" when instruction is processed
+ the_inst.instruction_queue.push(instruction_array)
+ break;
+ case "g": //get naturally. This is like "F" in that it lets the buffer empty out.
+ //so like F, don't ack_reply. This is automatically sent as the last instruction in a job.
+ //it always returns a full robot_status in order.
+ the_inst.instruction_queue.push(instruction_array) //stick it on the front of the queue so it will be done next
+ break;
+ case "G": //get immediate. The very first instruction sent to send should be "G",
+ //so let it be the first call to process_next_instruction & start out the setTimeout chain
+ the_inst.instruction_queue.unshift(instruction_array) //stick it on the front of the queue so it will be done next
+ break;
+ case "h": //doesn't go on instruction queue, just immediate ack
+ the_inst.ack_reply(instruction_array)
+ break;
+ default:
+ the_inst.instruction_queue.push(instruction_array)
+ the_inst.ack_reply(instruction_array)
+ break;
+ }
+ if (prev_status == "before_first_send") { the_inst.process_next_instruction() }
+ //else there should already be a setTimeout chain for process_next_instruction going on
+ }
+
+ ack_reply(instruction_array){
+ let ack_array = new Array(Dexter.robot_ack_labels.length)
+ ack_array[Dexter.JOB_ID] = instruction_array[Instruction.JOB_ID]
+ ack_array[Dexter.INSTRUCTION_ID] = instruction_array[Instruction.INSTRUCTION_ID]
+ ack_array[Dexter.START_TIME] = Date.now()
+ ack_array[Dexter.STOP_TIME] = Date.now()
+ ack_array[Dexter.INSTRUCTION_TYPE] = instruction_array[Instruction.INSTRUCTION_TYPE] //leave this as a 1 char string for now. helpful for debugging
+ ack_array[Dexter.ERROR_CODE] = 0
+ setTimeout(function(){
+ Dexter.robot_done_with_instruction(ack_array)
+ }, 1)
+ }
+
+ process_next_instruction(){
+ let dur = 10
+ if ((this.now_processing_instruction == null) && //we're not busy and
+ (this.instruction_queue.length > 0)) { //there's stuff to do
+ this.now_processing_instruction = this.instruction_queue.shift() //pop off next inst from front of the list
+ let instruction_array = this.now_processing_instruction
+ var robot_status = this.rs
+ dur = 1000 //default dur in ms
+ var oplet = instruction_array[Dexter.INSTRUCTION_TYPE]
+ robot_status[Dexter.JOB_ID] = instruction_array[Instruction.JOB_ID]
+ robot_status[Dexter.INSTRUCTION_ID] = instruction_array[Instruction.INSTRUCTION_ID]
+ robot_status[Dexter.START_TIME] = Date.now()
+ robot_status[Dexter.INSTRUCTION_TYPE] = instruction_array[Instruction.INSTRUCTION_TYPE] //leave this as a 1 char string for now. helpful for debugging
+ robot_status[Dexter.ERROR_CODE] = 0
+ let ins_args = Instruction.args(instruction_array)
+ let angle
+ switch (oplet){
+ case "a": //moveall joints
+ angle = ins_args[0]
+ if (!isNaN(angle)){ robot_status[Dexter.J1_ANGLE] = angle}
+ angle = ins_args[1]
+ if (!isNaN(angle)){ robot_status[Dexter.J2_ANGLE] = angle}
+ angle = ins_args[2]
+ if (!isNaN(angle)){ robot_status[Dexter.J3_ANGLE] = angle}
+ angle = ins_args[3]
+ if (!isNaN(angle)){ robot_status[Dexter.J4_ANGLE] = angle}
+ angle = ins_args[4]
+ if (!isNaN(angle)){ robot_status[Dexter.J5_ANGLE] = angle}
+ //DexterSim.fill_in_robot_status_xyzs(robot_status)
+ break;
+ case "b": //move_to xyz
+ /*if (!isNaN(instruction_array[2])) robot_status[Dexter.ds_j5_x_index] = instruction_array[2]
+ if (!isNaN(instruction_array[3])) robot_status[Dexter.ds_j5_y_index] = instruction_array[3]
+ if (!isNaN(instruction_array[4])) robot_status[Dexter.ds_j5_z_index] = instruction_array[4]
+ if (!isNaN(instruction_array[5])) robot_status[Dexter.ds_j4_angle_index] = instruction_array[5]
+ DexterSim.fill_in_robot_status_joint_angles(robot_status)
+ */
+ break;
+ case "B": //move_to_relative xyz
+ /*if (!isNaN(instruction_array[2])) robot_status[Dexter.ds_j5_x_index] = robot_status[Dexter.ds_j5_x_index] + instruction_array[2]
+ if (!isNaN(instruction_array[3])) robot_status[Dexter.ds_j5_y_index] = robot_status[Dexter.ds_j5_y_index] + instruction_array[3]
+ if (!isNaN(instruction_array[4])) robot_status[Dexter.ds_j5_z_index] = robot_status[Dexter.ds_j5_z_index] + instruction_array[4]
+ if (!isNaN(instruction_array[5])) robot_status[Dexter.ds_j4_angle_index] = instruction_array[5] //not relative
+ DexterSim.fill_in_robot_status_joint_angles(robot_status)*/
+ break;
+ case "e": //cause an error. Used for testing only
+ robot_status[Dexter.ERROR_CODE] = instruction_array[2]
+ break;
+ case "F":
+ dur = 0
+ break;
+ case "g": //get_robot_status
+ dur = 0;
+ break;
+ case "G": //get_robot_status
+ dur = 0;
+ break;
+ //handled by send. h never gets to this fn
+ case "h": //heartbeat get robot status
+ //dur = 0;
+ shouldnt("In dextersim.process_next_instruction, got an 'h' oplet but this fn shouldn't get 'h' instructions.")
+ break;
+ case "R": //relative_moveall joints
+ angle = ins_args[0]
+ if (!isNaN(angle)){ robot_status[Dexter.J1_ANGLE] += angle}
+ angle = ins_args[1]
+ if (!isNaN(angle)){ robot_status[Dexter.J2_ANGLE] += angle}
+ angle = ins_args[2]
+ if (!isNaN(angle)){ robot_status[Dexter.J3_ANGLE] += angle}
+ angle = ins_args[3]
+ if (!isNaN(angle)){ robot_status[Dexter.J4_ANGLE] += angle}
+ angle = ins_args[4]
+ if (!isNaN(angle)){ robot_status[Dexter.J5_ANGLE] += angle}
+ //DexterSim.fill_in_robot_status_xyzs(robot_status)
+ break;
+ case "S": //set_parameter
+ dur = 0
+ break
+ case "z": //sleep
+ dur = Math.round(ins_args[0]) //instruction array z sleep time is in milliseconds. JS timeout dur is in milliseconds
+ break;
+ default:
+ if (Dexter.instruction_type_to_function_name_map[oplet]){
+ out("Warning: Dextersim.send doesn't know what to do with the legal oplet: " + oplet, "red")
+ }
+ else {
+ out("Error: DexterSim.send received an instruction array with an illegal oplet: " + instruction_array, "red")
+ }
+ }
+ //if (oplet != "h"){ //never put -1 in instruction_id of robot status except before first instruction is run.
+ //For heartbeats, we want to leave in robot_status whatever the last "real" instruction was in there.
+ // ds_copy[0] = instruction_array[0] //instruction id
+ //}
+ if (!$("#real_time_sim_checkbox").val()){
+ dur = 0
+ }
+ let ds_copy = robot_status.slice(0) //make a copy to return as some subseqent call to this meth will modify the one "model of dexter" that we're saving in the instance
+ let the_inst = this
+ setTimeout(function(){
+ ds_copy[Dexter.STOP_TIME] = Date.now()
+ the_inst.completed_instructions.push(instruction_array)
+ const job_id = robot_status[Dexter.JOB_ID]
+ const job_instance = Job.job_id_to_job_instance(job_id)
+ SimUtils.render_once(robot_status, "Job: " + job_instance.name) //renders after dur, ie when the dexter move is completed.
+ if (["F", "G", "g"].includes(oplet)) { Dexter.robot_done_with_instruction(ds_copy) } //or I could just always do this when in sim mode.
+ the_inst.now_processing_instruction = null //Done with cur ins,
+ if((the_inst.instruction_queue.length == 0) && //nothing in the queue,
+ (the_inst.status == "closing")) { //and no more coming from DDE.
+ //the_inst.status = "closed" //Its over.
+ DexterSim.close(the_inst.robot_name) //cleaner to set "closed" in one place.
+ }
+ },
+ dur)
+ }
+
+ if(this.status == "closed") {} //don't call process_next_instruction any more
+ else {
+ let the_inst = this
+ setTimeout(function(){
+ the_inst.process_next_instruction()
+ }, dur + 10) //no point in calling process_next_instruction until after dur so that we finish
+ //the prev instruction first. IF there are no instrucdtions in the queue
+ //when process_next_instruction is called, then dur will be some small number
+ }
+ }
+ static close(robot_name){
+ //when this is called, no more instructions will be coming from the job, but there might be
+ //be stragglers left in the instruction_queue
+ let the_inst = DexterSim.robot_name_to_dextersim_instance_map[robot_name]
+ if(the_inst){
+ if ((the_inst.instruction_queue.length == 0) &&
+ (the_inst.now_processing_instruction == null)){
+ the_inst.status = "closed" //also set near bottom of process_next_instruction
+ }
+ else { //note: now that I automatically put a "g" instruction as the automatic last instruction
+ //of a job's do_list, we shouldn't be getting this "closing" state because
+ //the "g" naturally empties the instruction_queue.
+ the_inst.status = "closing"
+ //setTimeout(function(){DexterSim.close(socket_id)}, 1000) //shouldn't be necessary.
+ //as process_next_instruction will handle final close in this case.
+ }
+ }
+ }
+
+}
+
+DexterSim.robot_name_to_dextersim_instance_map = {}
\ No newline at end of file
diff --git a/doc/Dexter Development Environment_files/filelist.xml b/doc/Dexter Development Environment_files/filelist.xml
new file mode 100644
index 00000000..7de5df1e
--- /dev/null
+++ b/doc/Dexter Development Environment_files/filelist.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/doc/Dexter Development Environment_files/header.htm b/doc/Dexter Development Environment_files/header.htm
new file mode 100644
index 00000000..f356da21
--- /dev/null
+++ b/doc/Dexter Development Environment_files/header.htm
@@ -0,0 +1,123 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
[Type
+ text][Type text][Type text]
+
+
+
+
+
+
Dexter Development Environment: Fry, 9/21/16Page 1 of 1
+
+
+
+
+
+
diff --git a/doc/Dexter Development Environment_files/image001.png b/doc/Dexter Development Environment_files/image001.png
new file mode 100644
index 00000000..4b231f8a
Binary files /dev/null and b/doc/Dexter Development Environment_files/image001.png differ
diff --git a/doc/Dexter Development Environment_files/image002.png b/doc/Dexter Development Environment_files/image002.png
new file mode 100644
index 00000000..def8cc50
Binary files /dev/null and b/doc/Dexter Development Environment_files/image002.png differ
diff --git a/doc/Dexter Development Environment_files/image003.png b/doc/Dexter Development Environment_files/image003.png
new file mode 100644
index 00000000..addbb8b9
Binary files /dev/null and b/doc/Dexter Development Environment_files/image003.png differ
diff --git a/doc/Dexter Development Environment_files/image004.png b/doc/Dexter Development Environment_files/image004.png
new file mode 100644
index 00000000..96e33cb6
Binary files /dev/null and b/doc/Dexter Development Environment_files/image004.png differ
diff --git a/doc/Dexter Development Environment_files/image005.png b/doc/Dexter Development Environment_files/image005.png
new file mode 100644
index 00000000..e6885b9e
Binary files /dev/null and b/doc/Dexter Development Environment_files/image005.png differ
diff --git a/doc/Dexter Development Environment_files/image006.png b/doc/Dexter Development Environment_files/image006.png
new file mode 100644
index 00000000..34aeaabb
Binary files /dev/null and b/doc/Dexter Development Environment_files/image006.png differ
diff --git a/doc/Dexter Development Environment_files/item0001.xml b/doc/Dexter Development Environment_files/item0001.xml
new file mode 100644
index 00000000..72e886cb
--- /dev/null
+++ b/doc/Dexter Development Environment_files/item0001.xml
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/doc/Dexter Development Environment_files/props0002.xml b/doc/Dexter Development Environment_files/props0002.xml
new file mode 100644
index 00000000..45e37766
--- /dev/null
+++ b/doc/Dexter Development Environment_files/props0002.xml
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/doc/Dexter Development Environment_files/themedata.xml b/doc/Dexter Development Environment_files/themedata.xml
new file mode 100644
index 00000000..bb4c689b
Binary files /dev/null and b/doc/Dexter Development Environment_files/themedata.xml differ
diff --git a/doc/Dexter_Development_Environment.html b/doc/Dexter_Development_Environment.html
new file mode 100644
index 00000000..9fe43629
--- /dev/null
+++ b/doc/Dexter_Development_Environment.html
@@ -0,0 +1,1004 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
As consumers demand "mass
+customization", the hardware of our robots is meeting the challenge by becoming
+more capable. They have more degrees of freedom, higher accuracy, greater
+speed, and additional sensors.In
+order to take advantage of this hardware, we need more sophisticated
+software.This is as it should be.
+It is easier to change a line of code than to change a transmission line of
+electricity or light.
+
+
+
+
Software
+
+
Unfortunately the cost of
+software development can be quite high, especially if that cost is not
+amortized over the manufacture of many copies of the same thing. The operators
+of these robots may be factory workers, mechanical engineers or even home users
+for personal manufacturing. With the luxury of professional programmers not
+available, we must make "end user programming environments" that facilitate
+part customization, fixing build-environment specific bugs and ultimately,
+design of whole new parts.
+
+
+
+
3D printers are perhaps the
+most common "manufacturing robot" in homes, but they typically use just
+one-material and one-process for manufacturing. Complex products will need
+multiple materials and multiple processes (CNC, laser cutting, sintering, pick
+and place, assembly, etc.).
+
+
+
+
As the complexity of the
+build processes grows, so too must the job description. A conventional "app"
+with a few buttons, can't accommodate the breadth of customization necessary. A
+user will need to interact at multiple levels that will permit an
+ever-increasing control over complex procedures. Ultimately we need the full
+power of a general purpose programming language. Our build process" description
+looks less like a list of numbers and more like a full-fledged program.
+
+
+
+
Robots
+
+
The Dexter Development
+Environment was designed to program the rather adept "Dexter" robot. It is a
+5-axis arm designed for table or ceiling mounting. Dexter contains a
+general-purpose processer that runs Linux as well as an FPGA supercomputer for
+high-speed parallel operations.
+
+
+
+
As flexible as Dexter is,
+complex multi-robot builds may involve not just multiple robots, but robots of
+different kinds. DDE"s architecture
+accommodates multiple kinds of robots that can perform in concert. The simplest
+robot kind that DDE supports is called "Brain". It can't perform physical
+operations on its own, but it can direct other robots to do so, just as an
+orchestra conductor doesn"t play an instrument, but directs others that do.
+
+
+
+
The "Serial" robot is a
+non-specific robot controller that drives processes through a serial port, such
+as the USB port in a laptop.It has
+been used to control an Arduino. We might think of a Serial robot as a sort of
+general purpose percussionist, who can play a variety of instruments dependent
+upon the piece to be played (or rather built.)
+
+
+
+
The "Human" robot is perhaps
+the most controversial yet conceptually interesting. Complex jobs may not be
+able to be fully automated. The Human robot has an instruction set that includes
+operations only a person can perform. These are either a textual description of
+a task, or some choice that the human operator needs to make. The important
+idea is that an instruction for a human can be stuck on a do-list and treated
+just like any other kind of instruction. We can thus synchronize human tasks
+and automated tasks in one coherent environment.
+
+
+
+
The Human robot is the singer
+in our orchestra. It does not need an instrument to perform its part. We can
+even use DDE jobs to coordinate multiple humans, a chorus if you will!
+
+
+
+
Unlike a typical musical
+performance, we don't require the person to memorize their part. Text, menus, other
+graphical widgets and even speech can be used to make life easy for the singer
+of the band. Our conductor tells the singer when to start singing, though the
+singer must tell the conductor when she is done. This allows the person to take
+as much time as the task requires, giving her maximum flexibility to perform
+her best.
+
+
+
+
+
+
An
+example of "lyrics" that DDE presents to the "singer".
+
+
+
+
Self Teaching
+
+
If this complex software
+environment is to be effectively used, it must be understood by its users. DDE utilizes a variety of media for
+explaining itself to users. Thus
+DDE performs the role of "music teacher", though not so much for training
+performers as training composers, who write the score (do-list) for each
+instrument (robot). Because a do-list is a carefully ordered sequence of
+instructions that must be synchronized with other instruments, our instructions
+bear more than a passing resemblance to notes in an actual score.
+
+
+
+
Above we see the 4 panes of
+DDE. The upper left pane is the code editor. It can contain any JavaScript. The
+content in this screen shot was inserted from an example on the Jobs menu
+(shown expanded). A job feeds the instructions on its do-list to a robot. This insertion
+comes not just with the code, but with comments explaining the code's
+functionality (in brown text).This
+particular example contains two jobs that coordinate by "synchronizing" at each
+of their "sync_point" instructions.
+
+
+
+
+
Every character in the editor
+has help available by clicking on it. Here we clicked on "sync_point".Concise help appears in the Output pane
+in the lower left. The blue text in this help is a link to extended
+documentation from the reference manual, shown in the Documentation pane in the
+upper right. The lower right is the Simulation pane, which shows a graphical
+simulation of the robot under control, or mimics a real robot.
+
+
+
+
Orchestras usually have
+scores with every note written out ahead of the performance. However, our real-world
+builds need to be more flexible than that. Robot sensors can detect anomalies
+that may need to be addressed during the build, just as professional musicians
+can cover up for each other's mistakes. Since the do-list can contain arbitrary
+JavaScript, it can actually generate new instructions on the fly, much as a
+jazz improviser composes on the spot. One of DDE's instruction types is
+literally a JavaScript "generator". It can produce a stream of instructions
+who's length needn't even be set before the generator starts producing
+instructions, perhaps like some stage-hogging lead guitarist.
+
+
+
+
A Natural Language Application
+
+
We can take advantage of
+DDE's window system programming, speech generation & recognition, natural
+language parsing capability and AI reasoning to make easy-to-program, as well
+as easy-to-use interfaces to sophisticated applications. In this example, we
+use Google's speech I/O and the MIT InfoLab Group's English parser (named
+START) to build an application that lets a user create a knowledge base and ask
+questions about it, with a speech interface. Note that this application is not
+part of DDE, but it does represent the kind of application that can be built with DDE.
+The high level interface is:
+
+
+
+
+
+
+
+
If a user
+presses Click to talk before saying
+each of the above example sentences, they will create a knowledge base and get
+speech feedback after each sentence, ending with "Robot is useful because robot
+have hand."
+
+
+
+
Levels of Programming
+
+
Our base
+level of programming for this application is JavaScript. We layer on DDE
+utilities, makingaccess to I/O and
+parsing easier in the next level up. Finally we use a knowledge base and
+reasoning for our natural language interface. If a user needs functionality not
+available at a high level, they can drop down a level, remaining in the same development environment, to gain increased
+breadth at the expense of using a lower level language.
+
+
+
+
It is
+important to understand that the above English sentences are, literally, code.They create a program with a definitive
+behavior that we can access via asking questions.
+
+
+
+
Debugging
+
+
The majority
+of a programmer's time is not spent typing in code, it is in debugging that
+code. Analogously, the majority of our natural language coder's time will not
+be spent speaking the code, it will be in debugging.
+
+
+
+
A winning
+strategy for developing working code quickly is to get feedback from our
+development environment incrementally as we build our application.As we construct our "Robot Knowledge
+Base Application",the development
+environment gives us feedback after each sentence. For the two sentences that
+add knowledge to the knowledge base, "A robot has a hand." and "If a
+robot has a hand, a robot is useful.",
+our development environment responds with "OK" and "Got it."
+(Identical acknowledgement in English is boring an unnatural!) This informs our
+natural language coder that their utterances are syntactically correct.
+
+
+
+
If we
+consider that the goal of our app is to answer the final question, the
+intermediate questions are probing the semantic validity of the knowledge base
+being built.They take the place of
+"print statements" in traditional programming. However, as you can see, they
+are much higher level than print statements. They don't need to be embedded
+inside some complex algorithm, and they produce output in a very understandable
+way. For instance "Does a robot have a hand?" is responded to with "Yes, a robot
+has a hand".
+
+
+
+
Knowledge Base Debugging
+
+
Applications
+that rely on knowledge bases have a special kind of bug: bugs in the knowledge
+base itself. We therefore need to be especially careful to inform the natural
+language coder what's in that (potentially huge) knowledge base, but only with what's
+relevant at the moment.
+
+
+
+
Here's a
+dialog our app supports:
+
+
+
+
Human: A robot has a hand.
+
+
DevEnv: OK.
+
+
Human: A robot has a hand.
+
+
DevEnv: I already know that.
+
+
+
+
Our
+application responds to the first sentence with "OK" but the 2nd
+sentence with "I already know that." This informs our natural language coder about
+redundancy, much as a fellow human would in a conversation. Furthermore, our
+app does not stick into the knowledge base the same knowledge twice.
DevEnv: Sorry, robot is useful, is
+only true under certain conditions.
+
+
+
+
Human: A robot has a hand.
+
+
DevEnv: Got it.
+
+
+
+
Human: Why is a robot useful?
+
+
DevEnv: Robot is useful because
+robot have hand.
+
+
+
+
+
+
Notice that
+there are three different responses to the Human's question of "Why is a robot
+useful?". Each informs the user about what is in the knowledge base at time
+time of the ask, giving clues about one of the most common bugs: missing
+knowledge.
+
+
+
+
Conclusion
+
+
Dexter Development
+Environment lets uses "print" a part from a design contained in Jobs that have
+do-lists. But this rather passive interaction is analogous to an audience member
+at a concert. Via end-user programming techniques, we enable the user to
+orchestrate the process, ultimately giving them control of even the low-level
+instructions in the process. With the "Human" robot, we can synchronize what
+machines do best with what people can do best by providing appropriately timed
+instructions, similar to real-time lyric presentation in a Karaoke bar.
+The complexity of composing build-scripts can be mitigated by DDE's
+self-teaching techniques and the AI of natural language processing plus
+knowledge base management that we've only just begun (apologies to
+the Carpenters).
+
+
+
+
+
+
diff --git a/doc/guide.html b/doc/guide.html
new file mode 100644
index 00000000..45ad54d3
--- /dev/null
+++ b/doc/guide.html
@@ -0,0 +1,450 @@
+About
+ Dexter Development Environment
+ v is
+ beta test software.
+ DDE helps you create, debug, and send software to a Dexter robot.
+ You can use any Javascript augmented with DDE-specific functions to help find out about,
+ and manipulate, a robot.
+ Videos on Dexter
+ DDE Overview Paper
+
+Why Use DDE?
+ Dexter has a limitless variety of capabilities.
+ We couldn't think of them all let alone program them.
+ And if we could, finding the right button for each program would be
+ extremely difficult, besides overfilling screen real estate.
+
+ By providing a general purpose language that is broad enough to cover all the bases,
+ yet detailed enough to specify the action details, users can specify the
+ precise behavior they desire.
+ We've extended JavaScript, most common web page programming language,
+ with dexter-specific functions like
+ "move" and ways to gets values from its sensors (like camera").
+ This allows you to specify things like:
+ If part X is in the workspace, then move it 10 millimeters to its left.
+
+ You need a general purpose language to customize that "10"
+ with any computable number in a myriad of ways. We may want to
+ create actions that depend on conditions that differ with the environment, time,
+ or materials. Instead of move, we might want to rotate, or grasp, or drill, etc.
+ Won't a Text Editor Do?
+ You could use any old text editor to write code. But you'd need to know:
+
+
What capabilities are available?
+
What do they actually do? (semantic details)
+
How do I use them? (syntactic details)
+
How do I run the code?
+
How do I localize bugs?
+
How do I understand and fix them?
+
How do I store and re-run programs I've created?
+
How do I change and extend existing code?
+
+ DDE helps you with all of the above.
+
+
+Prerequisites
+ You'll need a Dexter robot and a basic knowledge of JavaScript to make full use of DDE.
+ DDE provides a lot of help for learning JavaScript directly and the
+ Learning JavaScript section of this documentation gives you a number of
+ very good on-line sources to smooth your path.
+ Without a robot, you can still use DDE to simulate one.
+
+Installation
+ First Install
+ needs work
+
+ Updating to the latest DDE
+ needs work
+
+ Launch DDE
+ needs work
+
+
+Robot Configuration
+
+
The Dexter robot supports a wi-fi connection to your computer.
+
Please use the latest Chrome browser for DDE.
+
Enter the URL of the Dexter computer into the "ROS url" type-in at the top of
+ the JavaScript pane. It will normally have a port suffix of ":9090".
+
Verify the connection by choosing the Output pane menu/ROS Info/ping menu item.
+
+
+User Interface
+ Video tutorial of DDE
+ JavaScript Pane
+ The JavaScript pane is a text editor. You can view and edit any text documents in it,
+ but primarily you will be editing JavaScript that defines a job to make something
+ with Dexter. DDE expects you to save such "apps" in your Documents/dde_apps/
+ folder.
+
+ Output Pane
+ DDE prints information in the Output pane that will be useful in your current context.
+ You can explicitly print in the output pane with a call to the JavaScript function out.
+ Example:
+ out("hi world", "blue")
+ out accepts any valid HTML as its first argument. It will be rendered in the Output pane.
+
+ Documentation Pane
+ The Documentation pane attempts to describe the core knowledge you'll need to command Dexter to make things.
+ Admittedly we'll always fall short of this goal, but let us know if some crucial information
+ is missing and we'll do our best to fill the void.
+ You can find out what version of DDE is running and the latest changes under the
+ Release Notes section of the documentation.
+ Details about programming Dexter are in the Reference Manual section.
+
+ Simulate Pane
+
+ The simulate pane shows a graphical simulation of Dexter with
+ joint angles of the last heartbeat robot status returned.
+ (By default, heartbeats happen every 100ms.)
+
+ Use the mouse in the Simulate pane to:
+
+
Rotate table: mouse-down then drag.
+
Zoom: shift-down then mouse-down then drag.
+
Pan: alt or option down, then mouse-down, then drag.
+
+
+ shows Dexter randomly flailing around, not
+ correlated to a connected Dexter.
+
+ The menu in the Simulate pane header let's you browse several videos showing
+ off Dexter's capabilities.
+
+ Stepping Instructions
+ To understand a Job's behavior, its useful to step through each instruction.
+ Checking the pause checkbox will cause running jobs to pause
+ when they have completed their current instruction. Jobs started when
+ the pause button is checked will pause right before the first user instruction
+ on the do_list is run.
+ When a job is paused, clicking the button will cause
+ it to execute the next instruction, print out useful information in the Output
+ pane, and pause. If a job is paused, and you uncheck the pause checkbox,
+ then click the button, the job will begin running normally.
+
+ "debugger"
+ The instruction of "debugger" in a do_list will cause
+ the pause checkbox to be checked and the job to pause.
+ A function that returns the string "debugger" or
+ even an array that has an element of "debugger"
+ will cause a pause.
+
+ Note that using the string "debugger"
+ is intentionally similar to using the JavaScript constant debugger.
+ If you have the constant debugger
+ in the body of a function that is a do_list item, or is called by
+ a do_list item, it will cause a JavaScript breakpoint and you
+ can step through that code using the Chrome dev tools.
+ See Documentation top level section Debugging.
+
+
+
+
+JavaScript
+ DDE let's you control a Dexter robot with Javascript. You can execute all of JS.
+ DDE extends JavaScript with a library of functions that control Dexter, allow access to Unix commands
+ on Dexter's computer, Window system extensions, as well as ROS specific function calls allowing you to find out about
+ and control Dexter.
+ In DDE, console.log sends its output
+ to the (usually hidden) Chrome console.
+ Use out (on the menu) to see output in the Output pane.
+
+Learning JavaScript
+ The quickest way to learn most of the JavaScript you'll need is from the
+ JavaScript Pane's menu.
+ Read menu item tooltips, choose an item to insert code, then click
+ to eval all the code in the Editor. If there's a selection when you click Eval,
+ just the selected code will be evaluated.
+ Choose menu items under in depth-first order for a consistent overview, and later you can choose
+ exactly those items you need to insert a code snippet.
+
+ A nice interactive tutorial is available at:
+
+ https://www.codecademy.com/learn/javascript Beware that console.log prints to the
+ normally hidden chrome console. DDE's out is easier to use.
+
+ If you want more prose, there are lots of JavaScript tutorials on the web. You will not need to know
+ HTML, CSS or JQuery that are commonly taught in conjunction with JavaScript.
+
+ A very gentle intro to JavaScript. Ignore the
+ parts that use the Underscore library.
+ A more formal (and long) tutorial.
+ JS for Programmers
+ If you're already a competent programmer but don't know JS specifics,
+ here's a few tips:
+ JavaScript is an untyped language. That means you don't declare types
+ of variables, function parameters, or return values. So for instance,
+ C's int foo = 32;
+ in Js is var foo = 32;
+ The type system is,
+ um, weak. The object system is also in somewhat of disarray. Because of that
+ there are many packages adding a more rational Object system, but they all
+ differ, confusingly.
+
+ There's no compiler in JavaScript. There are no "includes" or
+ "pre processors" or "macros". The code is run in an iterpreter inside
+ a browser (every browser, actually). The major browsers also offer a
+ debugging environment, though typically no Editor. DDE gives you an editor
+ and a lot of other convenieces for developing code.
+
+ Whitespace characters are those characers that "take up space" but you can't
+ otherwise see. This includes space, tab, newline and a few others. In Javascript,
+ mostly its the case that 1 whitespace character is equivalent to any number of
+ contiguous whitespace characters. Except that function calls need to be ended
+ with either a semicolon or a newline, not just a space.
+ For example:
+ Math.min(3, 4); Math.min(5, 6)
+ is legal, as is:
+ Math.min(3, 4)
+ Math.min(5, 6)
+ but not:
+ Math.min(3, 4) Math.min(5, 6)
+
+ There is no Window System per se in JavaScript but it ties into
+ HTML, CSS and the browser's Document Object Model. This is confusing since
+ it requires several different syntaxes and ways-of-thinking. DDE
+ simplifies this by providing
+ the key window system facilites you'll need for commanding Dexter
+ via the function show_window, the Human.enter_* instructions
+ and a few other utilities. See the menu.
+
+ Javascript's functionality greatly expanded in 2016 with a new version who's name
+ itself is confusing. You'll see EcmaScript 6, JavaScript 2015 and a few variants.
+ Browsers vary as to how much of this they implement, but Chrome, the browser
+ DDE uses, has nearly 100% of this new standard implemented as of June, 2016.
+ DDE depends on these new features.
+
+ See in, this documentation, Installation/Keep Chrome up to date.
+ JS 6 can run code from earlier versions of JS, but there's an awful lot
+ of new functionality that isn't in most existing JS documentation.
+
+ Like all popular programming languages, JavaScript has its problems.
+ But its unique in its "deployability". JS and DDE runs on Windows, Macs,
+ Linux, and Chromebooks. Its new features are quite powerful, and DDE strives
+ to make learning and using JS as simple as possible. Your new skills will
+ serve you well in Web programming for billions of users.
+
+ Recommended JS Tutorials for the experienced programmer (both of which ignore
+ the new JS 6 extensions):
+
+ JS re-introduction
+ more comprehensive
+
+ Eventually you will need to know the concepts of ROS (the Robot Operating System), though
+ not the syntax of BASH, C++ and Python normally required to work with ROS.
+
+Workflow
+ DDE let's you execute arbitrary JavaScript that is entered into the JavaScript pane.
+
The JavaScript pane's menus allow you to insert useful code snippets into
+ the JavaScript pane.
+
You can edit and extend the inserted code. Use any valid JavaScript.
+
Click the button. The result of the last expression evaluated
+ will appear in the Output pane.
+
If there is a selection when the button is clicked, only the selected
+ code will be executed.
+
Triple click on a line to select it.
+
Alt-click on a JS function call to select it.
+
+ Try this: type into the editor
+ 2 + 3
+ Click and see 5 in the Output pane.
+
+ Persistent Data
+ When you have defined a named function, set a global variable or a property
+ reachable by a global variable, that data will remain in the JS environment until
+ you relaunch DDE. This is even true if you bring a new file into the editor.
+
+ Overall this facilitates programming, but it does have some behavior that may be unexpected.
+ Imagine you define
+ function foo(){return bar()} and
+ function bar(){return 'stuff'}
+ You call foo() and it returns 'stuff'.
+ Now you rename bar to baz and test baz(). It returns
+ 'stuff' as expected, as does calling foo(). Now
+
Save this code in a file
+
Relaunch DDE
+
Open the file in the editor
+
Eval it
+
Call foo()
+
+ The call to foo will error because bar is no longer defined.
+ When redefining function and global variables, its a good idea to save your
+ code in file(s), relaunch DDE, and reload your code periodically, to check against such issues.
+
+ Working with Dexter
+
In the output pane, enter any Unix BASH shell command in the shell type in
+ and hit enter. It is run on Dexter's computer. Returned text will be printed below.
+ The command you typed in will also be added to the Output pane's menu under
+ "User Commands" should you want to execute it again.
+
+
The Output pane's menu allows easy access to finding out about the ROS environment.
+
If you click on underlined text in the Output pane, it will pop up a help
+ window about the clicked on item. Often the help window will have buttons allowing
+ you to insert relevant JS function calls into the JavaScript pane.
+
+
+
+Series
+ A useful way to organize knowledge is to construct lists of similar-typed concepts.
+ DDE calls such lists series. There are over 30 series in DDE, including
+ numbers, dates, colors, functions for math, strings, arrays, etc.
+ The most useful functions and data structures in DDE are in a series.
+
+ The menu allows you to insert into the
+ editor, an example item from each series. When you click on a series item in the editor,
+ help is given on that item in the Output pane. Using the Right and Left arrow
+ keys, you can replace a selected series item with the next or previous item
+ in its series. The Up and Down arrow buttons replace a selected series item
+ with an item from another series. Effectively this uses the series of series.
+
+ An example of a series is boolean. Choose it from the
+ menu. It inserts true. Now hit the right arrow key to see additional items
+ in the series (false, null, etc.) The left arrow goes backwards through the series.
+
+ With any series item selected, hit the down arrow. If you're on a member of the boolean series,
+ this will replace the selection with an item from the integer series.
+ Press the up and down arrows to go to a new series.
+
+ Each time you go to a new item from series or click on one already in the editor,
+ help on it will be displayed in the Output pane.
+
+Jobs
+ A job feeds the instructions in its do_list to a robot for making things.
+ Most users of DDE will spend most of their time creating and running jobs.
+
+ The menu gives help on Jobs and Robots.
+
+ The menu contains numerous examples of defining Jobs and
+ how to run them. Choose Insert example 1 and read the comments to understand Job syntax.
+ See the Reference Manual on Job for the details of specifying a job.
+
+Robots
+ A robot is a machine capable of performing the instructions in its instruction set.
+ The class hierarchy of DDE Robots is:
+
Robot
+
Brain
+
Dexter
+
Human
+
Serial
+
+
+
+ To get a robot to perform instructions, you create an instance of its class, giving it
+ at least a name (and in the case of Dexter, an ip_address and a port number) then
+ create an instance of Job and give it a robot property of the robot you created.
+ The job should also have a do_list, which is the sequence of instructions to run
+ on the robot. When the start method is called on a Job, it sends the items
+ on its do_list to the associated robot, sequentially, one at a time.
+
+ From a software standpoint, a robot is its instruction set.
+ The key difference between different kinds of Robots is the difference
+ between their instruction sets. If a robot is sent
+ an instruction not in its instruction set, it will error, because it doesn't know
+ how to perform that kind of instruction.
+
+ Robot is the superclass of all robot classes. It contains instructions that
+ can run on all robots. These are control instructions because they help
+ manage the flow of instructions in a job. Examples include: Robot.stop
+ to end a job immediately without processing the insructions after the stop instruction,
+ and Robot.wait_until which pauses execution of the job's instructions until
+ the calling of the given JS function returns true.
+
+ See submenu "robot" for details about robots as
+ well as the Reference Manual section on Robots.
+
+TestSuite
+ DDE has the capability to compose, run and report on Test Suites.
+ DDE comes with several Test Suites and you can define more.
+
+ Each Test Suite has a name and an array of tests.
+ A test is composed of an array of 1, 2, or 3 literal strings.
+
A literal string of JavaScript code to evaluate that returns a value to be tested.
+
The expected value of the above JavaScript code, also represented by
+ a literal string of JavaScript.
+
A literal string of a comment to aid in understanding the purpose or behavior of this test.
+ If the comment starts with "known", then if the test does not pass, it
+ will be reported on as an "known" failure. Other failures will be
+ reported as "unknown". Often it is convenient to mark a test as "known" when
+ you'd like to defer fixing it and just want to see the "unknown" failures.
+
+ Choose Insert Example to see a demonstation
+ Test Suite.
+ You run a Test Suite by selecting it and hitting the right arrow key or
+ choosing the JavaScript pane's Test/naviation/Run & sel next item menu item.
+ Use the down arrow key to select the next level down item such as a test or
+ even a part of a test. In each case, the right arrow executes the item and
+ selects the next item at that level.
+
+ To create a Test Suite, type in the JavaScript source of the suite's first test,
+ select it, and choose Selection to test.
+ This will wrap a Test Suite around the item and fill in the test's expected value
+ with the result of evaluating the code you have selected. If you do that again
+ for a second JavaScript selection, it will also create a test, but this time,
+ because the test is already in a Test Suite, it will not create a new
+ Test Suite.
+
+ Other operations on the menu are documented with tooltips.
+
+Debugging
+ Most programmers spend most of their time debugging.
+ We recommend entering just a bit of code at a time; a line or less before testing it.
+ That way, when a bug shows up, you'll know it was in the last bit that you added.
+ If you fail to do this, and have a large amount of code that has a bug, comment out
+ lines incrementally and test to isolate the bug.
+ DDE uses an automatic syntax checker named ESLint. It
+ indicates syntax errors in the JavaScript pane as soon as you enter them.
+ There are many different styles of JS coding and different versions
+ of JS so its hard to get such errors correct. Even if you have syntax
+ errors indicated, your code may run fine. As a first pass though, try
+ to fix such errors before evaling. If you can't, go ahead and evaluate
+ your code. Perhaps runtime errors will help you fix the bug,
+ or perhaps it will run OK and you'll know to just ignore the JS Pane syntax
+ bug indication.
+
+ Evaling just selected portions is another way to isolate bugs. If there is a selection
+ of JavaScript code, only that code will be evaled when you click
+
+ Another technique is to comment out code until your bug goes away.
+ // comments out to the end of the line.
+ /* comment */ Wrap JavaScript in
+ slash-star ... star-slash to comment
+ out code in the middle of a line or multiple lines.
+ See the JavaScript pane's debugging menu items.
+
+ Entering debugger; into the body of a JS function definition will set a breakpoint there.
+ When debugger; is evaluated (after you call the function) and the Chrome Developer Tools
+ window is open, execution will pause and highlight the debugger;" statement in a copy
+ of your source code.
+ (To open the Chrome Developer Tools window, click right on any DDE pane and choose
+ Inspect. If you don't see "Inspect" on the menu, read the documentation
+ under "Installation" on "Configure Chrome".)
+ Use the arrow buttons
+ in the Developer Tools window upper right to step execution.
+
+ Wrapping console.log(...) around a complex data structure will print it
+ out in the Chrome Developer Tools console with arrows to allow you to expand
+ data pieces of your choice to inspect. To see the console,
+ click right anywhere in DDE and choose "Inspect".
+ You can print strings into the Output pane with a call to out.
+ Because out returns
+ its 1st argument, you can embed it in code to see an intermediate value.
+ (out(2 + 3)) * 4 will print out 5, but return 20.
+ Print to output has items that print in a few different colors
+ so that you can distinquish some outputs from others in a complex debugging session.
+
+ speak behaves similarly to out in that it returns its 1st arg.
+ It can be useful in contexts where you want to know a value but don't
+ want to look at the screen to find it.
+ speak is on the Insert menu, under Learn Javascript/debugging.
+
+
+Contact
+ Please help us by emailing a bug report or suggestion to
+ cfry@media.mit.edu Take a look at the
+ latest Release Notes and the underlying Known Issues to avoid duplication.
+
+
+
+
+
diff --git a/doc/known_issues.html b/doc/known_issues.html
new file mode 100644
index 00000000..8afa477a
--- /dev/null
+++ b/doc/known_issues.html
@@ -0,0 +1,10 @@
+Known Issues
+
+
Dexter.draw_dxf needs extension to describe the drawing plane.
+
Dexter.run_gcode needs many extensions.
+
Some instructions lacking sections in the Reference Manual.
+
Train Dexter doesn't output a Job definition.
+
Documentation on ROS functionality
+
Support for ROS action clients needed.
+
+
\ No newline at end of file
diff --git a/doc/ref_man.html b/doc/ref_man.html
new file mode 100644
index 00000000..379c8ac1
--- /dev/null
+++ b/doc/ref_man.html
@@ -0,0 +1,2120 @@
+
+I/O
+out
+out prints its first argument into the Output pane.
+The optional 2nd argument controls the color printed (default "black").
+Example:out("hi", "blue")
+If you have a lot of out calls, it can be helpful to give them
+different colors so you can easily find a particular one.
+
+
+get_page
+get_page retrieves the contents of a web page.
+You pass in a url and get_page returns the contents as a string.
+The argument can either be a string of a url, or a literal JS object.
+Example: get_page("http://ibm.com")
+If there is an error, the returned string will start with "Error:"
+and be followed by some clues as to why the error happened.
+
+It will not eval scripts on the page
+so you may see an error when retriving a page containing JavaScript.
+
+Instead of a url as the argument, you can pass a literal JS object
+with lots of options, described at:
+ options
+
+
+get_page_async
+A call to get_page_async is asynchronus. It returns immediately,
+but when the actual page content is finally retrieved from the web,
+a callback is called and passed an error object, a response object, and the body string
+of the page.
+
+It will not eval scripts on the page
+so you may see an error when retriving a page containing JavaScript.
+
+Example:
+
+Instead of a url as the argument, you can pass a literal JS object
+with lots of options, described at:
+options
+
+
+make_url
+ url is a poorly designed language for transfering data on the web.
+ Documentation.
+ It's normal behavior is as an asyncrhonous function call, where the
+ call is typically on a web device known as a 'client', and it is sent to
+ a different device on the web known as a 'server'.
+
+ Usually its used to
+ get the content of a web page into a browser. Usually the content of a web page
+ is written in a polyglot of languages (HTML, CSS, JavaScript, etc.) but
+ we can use urls to retrieve data in other syntaxes such as JSON or just plain strings.
+
+ make_url does two things:
+
Prepends "http://" to the url being constructed, if it looks like
+ there is no protocol in the url already. If there is no "://" in the
+ first 16 chars of the url, it prepends "http://". If you want a
+ different protocol, such as https, or you are using "://" in the value
+ of an argument, you should include the protocol in the passed in url.
+
Makes creating arguments easier and appends them to the end of the url.
+
+ Parameters:
+ url: A string containing the base url. If the protocol is to be "http",
+ you can omit it in most cases.
+ Example: www.ibm.com means the same thing as
+ http://www.ibm.com
+ arguments: A string of arguments, formally called a query string.
+ Example: "x=123&y=45&color=blue"OR
+ A literal object with name-value pairs representing the arguments.
+ Example:
{x: 123,
+ y: 45,
+ color: "blue"}
+ This later form makes it easy to compute and set indivudal args.
+ Example:
+
+
+Sound
+
+recognize_speech
+ Speech recognition has a long history in AI. After many decades of research, it can
+ be useful, but don't expect it to be as reliable as a human. DDE uses Google's speech
+ recognition, which sends audio over the web to be recognized on Google's servers.
+ If you don't have:
+
a good microphone in your computer,
+
a quiet room,
+
a reliable net connection or
+
a fast net connection
+
+ don't attempt to use recognize_speech.
+ Be sure to crank up the volume of your mic.
+
+ The recognized text is quite good compared to recognizers of the past but, like people,
+ it still makes mistakes. Recognized text comes with a confidence number indicating
+ how good the recognizer thinks the text is at matching what you've said.
+ In theory its nice to have this confidence number but in practice, it might
+ not matter much. The number varies from 1 (very confident) to 0 (very unconfident)
+ though we've seen a bunch of 0 confidence numbers for perfectly fine text.
+ Also in the middle of a session, you may well see network bugs even though
+ it seems like your network is fine to you.
+
+ If you are using speech to dictate
+ a critical process, we recommend displaying or saying (via the speak function)
+ the recognized text and asking the user for a simple yes or no confirmation.
+
+ When recognize_speech is called, it pops up a dialog telling you to speak.
+ The arguments to recognize_speech configure this dialog and the callbacks that receive the
+ recognized text and confidence numbers. All of these are keyword arguments with defaults. See
+ menu, sound/recognize_speech for an example call.
+
title Default: "Recognize Speech". Shows in the title bar of the dialog.
+
+
prompt Default: "". Displays instructions for the user at the top of the dialog.
+ Can be any HTML.
+
+
only_once Default true. When true, the dialog is automatically closed at the end of the first phrase.
+ When false, the dialog re-initializes after you pause and permits another phrase to be recognized.
+ Say finish to close the dialog.
+
+
click_to_talk Default true. When true, the user
+ must click to start the recognition.
+ When false, recognition starts as soon as the dialog is shown,
+ or as soon as it has recognized the previous phrase (when only_once=false).
+
+
width Default: 400. The distance from the left edge of the dialog to the right edge in pixels.
+
+
height Default: 180. The distance from the top edge of the dialog to the bottom in pixels.
+ If you have multiple lines for the prompt, this should be increased.
+
+
x Default: 400. The distance from the left edge of the DDE window to the left edge of the dialog in pixels.
+
+
y Default: 200. The distance from the top edge of the DDE window to the top of the dialog in pixels.
+
+
background_color Default: "rgb(238, 238, 238)" i.e. light gray. Can be one of the names (strings) in the color series.
+
+
phrase_callback Default recognize_speech_default_phrase_callback.
+ This function is called when the user pauses after speaking.
+ It is passed the recognized text, and the confidence number (0 to 1).
+ If only_once=true, only this callback is called.
+ The default prints these two arguments into the Output pane.
+
+
finish_callback Default null meaning no action.
+ This function is called when the user says the finish_phrase.
+ It is passed an array of arrays. Each inner array has elements of the text
+ and the confidence number of each phrase spoken in this use of recognize_speech.
+ This argument is moot if only_once=true.
+
+
finish_phrase Default: "finish". The phrase that the user should speak to
+ end the dialog. Moot when only_once=true.
+
+
+
+
+speak
+speak uses text to speech technology.
+Example:
+speak("hey there")
+By passing a literal object, you can control many aspects of speak.
+The speak_data input can be more than just text. You can feed speak any JavaScript data
+(such as a boolean, a number, a date, an array, etc.) and it will do its best to say it out loud.
+Example:
speak({speak_data: [true, "It is", new Date()],//default="hello"
+ volume: 1.0, //default=1.0 0 to 1.0,
+ rate: 1.0, //default=1.0 0.1 to 10,
+ pitch: 1.0, //default=1.0 0 to 2,
+ lang: "en-US", //default="en-US"
+ voice: 0, //default=0 0, 1, 2, or 3
+ callback: function(event) {out('Dur in nsecs: ' + event.elapsedTime)} //default=null called when speech is done.
+ })
+
+
+
+
+
+
+File Access
+Web clients reading an writing files to their local file system has been impossible in the past.
+DDE gives you programmatic read/write access to all files under the dde_apps folder
+under your Documents folder, typically under the user's home folder.
+
+The code for your Job definitions should live under that folder (at any depth beneath
+that folder).
+If you do not have a dde_apps folder under your Documents folder, please create one.
+
+dde_apps_dir
+The folder beneath which DDE has programmatic access.
+You cannot set this constant. It will have a value something like:
+"/Users/Fry/Documents/dde_apps" on the Mac.
+
+
+file_content
+file_content takes an argument of a filepath, similar to load_files,
+and returns a string of the content of the file.
+Parameters
+path A string of a path to the file. Usually this will not start with a slash,
+ but rather tha first character of a file name inside of your dde_apps folder.
+ if the path starts with a path, it should be a complete path from the root
+ of your file system, on through to dde_apps and the file below it.
+
+encoding A string indicating the encoding of the file. Default: "utf8".
+ The default works fine for most plain text files, including .js files.
+
+Example:file_content("myfold/foo.txt"
+
+Editor.edit_file
+Editor.edit_file takes an argument of a filepath, similar to load_files,
+and puts that file in DDE's editor.
+
+Its 2nd argument is a callback that takes no arguments. It is called when the file's content
+is in DDE's editor.
+Example:Editor.edit_file("/myfold/foo.txt")
+
+
+file_exists
+Returns true if the file path in the first argument exists.
+Example>
+file_exists("class_play.js")
+
+
+folder_separator
+A function of no arguments that returns the character used to separate folders in a filepath.
+For Windows OS's this is "\\" (backslash).
+For others its "/" (forward slash).
+
+
+load_files
+load_files gets the content of files from disk and evaluate
+it in the DDE environment programmatically. You can pass any number of file paths to
+load files. It will load the files sequentially, such that later files
+can depend on the contents of earlier files loaded.
+A file path that starts with a slash is expected to have a full path to the file.
+A file path that doesn't start with a slash will have prepended to it
+the preceeding file path folder (up to but exluding the file name)
+that did start with a path.
+If the first file doesn't start with a slash (as is normal),
+its "prefix" will be dde_apps_dir
+This scheme makes it easy to load multiple files in a folder since you only
+have to include that folder name once.
+
+load_files returns the result of evaluating the last expression in the last file loaded.
+
+
+write_file
+ Arguments:
+ filepath The location to save to. This string must be the filepath for one of the 500 most recent files
+ that you manually brought into the editor. It will overwrite the current content.
+ Defaults to the file currently in the
+ editor.
+ content A string of the content you wish to be in the written file.
+ Defaults to the text currently in the editor.
+ Examples:
+ write_file() Saves the content now in the editor to the file being edited.
+ write_file("no_exist.js") This will error because write_file can't be used to create new files.
+ write_file("exists_but_not_edited.js") This will error because write_file won't work
+ unless the file is among the last 500 that you have edited.
+ write_file("foo.js") Providing that foo.js has been edited by you,
+ it will now contain the contents of the editor.
+ This is the save_as functionality.
+ write_file("/a_folder/foo.js", "new content") Replaces the existing content
+ of the given file with "new content".
+
+
+folder_listing
+ folder_listing retrieves an array of filenames and/or folder names that are somewhere
+ beneath the dde_apps folder. This function only works if you have
+ Web Server for Chrome installed. (See the doc for load_files.)
+ Arguments:
+ folder Default: "/". The name of the folder to retreive the listing of.
+ A folder of "/" finds the files and/or folders immediately below the dde_apps folder.
+ Folder should begin and end with a slash, but if it doesn't, it will be added.
+ include_folders Default: true. Retrieved folder names end in slash.
+ include_files Default: true.
+ callback Default: out A function of one argument. It is passed the
+ array of file and/or folder names determined by the other arguments.
+ Examples:
+ folder_listing() Retrieves the files and folders immediately under dde_apps.
+ folder_listing("/test_folder/", true, false) Retrieves only the folder names immediately under test_folder.
+ folder_listing("/whatever/", false, false) Retrieves nothing. An empty array will be passed to the callback.
+
+
+operating_system
+A global variable that has a value of the name of the current operating system.
+Windows OS's have the value "win". Macintosh OS's have the value "mac".
+If you find the value of other operating systems, please tell us!
+
+
+
+
+
+
+Persistent Database
+DDE has a very simple database, whose values remain in tact accross DDE sessions.
+The DB stores a JSON object. The top level is a literal object
+with string keys and values that can be any JSON objects, including null, booleans,
+numbers, strings, arrays and other literal objects nested as deep as you like.
+It is not meant to store a large amount of data, mostly preferences and
+small objects.
+
+The DB is stored in the file dde_apps/persistent.json as plain text.
+You can view the entire by opening it in DDE's editor if you like.
+However, we do not recommend editing it from DDE. That's because
+any changes will be overwritten the next time something is written
+to the DB by DDE. If you'd like to edit it as a file,
+close DDE and edit it with another editor. Be careful to
+get the JSON syntax correct.
+
+persistent_set
+Binds a literal to a string key that can be retreived in a later DDE session.
+Null, booleans, numbers, strings, arrays, and literal objects can all be stored.
+Example: persistent_set("test4", 44)
+
+
+persistent_get
+Retreives a literal that was set with persistent_set
+The first argument is the key to retreive. Its default value is "get_all"
+which gets a JavaScript literal object that has key-value pairs for all the
+calls to persistent_set. If a key is not in the database,
+undefined will be retreived.
+
+The 2nd arg is a callback that is passed the retreived value.
+Its default value is the DDE function out.
+Example: persistent_get("test4", function(val){ out("Got: " + val)})
+
+
+persistent_remove
+Removes the binding between the first argument (key) and a stored value in the persistent db.
+Example: persistent_remove("test4")
+After such a call, attempting to retreive the value of that key will get undefined.
+
+
+persistent_clear
+Removes all the values in the persistent db.
+Example: persistent_clear()
+After such a call, attempting to retreive the value of any key will get undefined.
+Warning: DDE uses the persistent db to store the keys of edited files.
+Clearing the db will mean that you must have the Web Server for Chrome installed until
+you manually edit those files again. See the documentation for Files.
+
+
+
+
+
+Job
+A job contains a do_list of instructions that it feeds to a robot to make things.
+The syntax of defining a job is:
+
+Defined jobs remain inert until they are started like so:
+Job.j1.start()
+start initializes the job and feeds the instructions in its do_list to
+the job's robot, which executes the instructions. Jobs either run to completion,
+error, or are stopped by the user via menu Stop all jobs.
+Stopped jobs may be restarted by calling Job.j1.start() again.
+This reinitializes the job with the original arguments passed to new Job
+and runs the do_list instructions again.
+
+new Job parameters
+The parameters used to define a new Job are:
+
name You can use Job.a_job_name to get the instance programmatically.
+
robot An instance of one of the subclasses of Robot, such as
+ Dexter, designating where
+ this Job's instructions are sent.
+
do_list An array of instructions to be sent to the job's robot when the
+ Job is run. There are a number of different kinds of instructions, including
+ user-defined JavaScript functions that can call arbitrary JS code.
+ Instructions may add additional instructions to the do_list by returning
+ them as a single instruction or an array of instructions.
+ Such instructions are inserted into the do_list just below the instruction that
+ made them.
+ Instructions are documented with the kind of robot that they run on.
+
+
keep_history true or false, default true. If true, the robot_status arrays
+ returned from running instructions on the robot
+ are stored in Job.the_job_name.rs_history.
+ This is useful for debugging, but uses memory, which can be
+ saved by setting keep_history to false.
+
log_instructions true or false, default false. Prints messages
+ to the Chrome console indicating the progress of a running job.
+
inter_do_item_dur A number indicating the number of milliseconds between
+ when an instruction is completed by its robot, and when the next instruction is
+ computed and sent to the robot of the job. This "taking a breath" gives other
+ jobs a chance to run. Default 100.
+
user_data A literal object of name-value pairs where arbitrary data created
+ at the beginning of a job or during the execution of an instruction can be stored
+ and retrieved. Default {} (an empty object).
+ It can be initialized in the call to new job like so:
+ new Job ({name:"j22" user_data:{color: "blue", weight: 123} })
+ Within an instruction, you can get a user_data value via
+ this.user_data.color
+ or set it via
+ this.user_data.color = "green"
+ You can set existing user_data names or create new ones by setting them.
+
+ user_data is persistent only while a job is executing. If you restart the
+ job, its user_data is lost. For data that you want to persist across restarts,
+ or for user_data that doesn't really belong with any one job but is used
+ by mulitple ones, use the class property Job.global_user_data.
+ This can be written to like so: Job.global_user_data.my_count = 123.
+
+ The value for user_data is passed in when creating a job is shallow_copied when
+ the job starts. So if this value was stored in some external-to-the-job way
+ and a job is run twice with that very same user_data, the 2nd time the job
+ is started, it will see the same top level keys as the first time,
+ and all the top level values that are immutable (booleans, strings, numbers).
+ However, if there is a mutable value (say an element of an array or a literal object,
+ the first job might have modified that and that modification will be see
+ when the job is run a 2nd time. Mostly all this doesn't matter because
+ most jobs don't use user_data at all. Others look at it but don't
+ write to it, and most of the others would only write top level, immutable
+ values to it. But nested mutable data in user_data can "leak" over to
+ another running of a job, or even other jobs. This might or might not
+ be what you want.
+
+ Job.global_user_data is initialized to {} when DDE launches.
+ You can store data here that you wish to persist across running jobs, but realize
+ that if a job modifies Job.global_user_data, the 2nd time that
+ job is run, it will see a different Job.global_user_data than the first.
+ If you want data to persist across launches, see
+ Reference Manual/IO/Persistent Database.
+
+
+
+
+start
+ start is an instance method on Job that
+ causes the job instance to feed its do_list to the Job's robot instance.
+ After a job instance is done running, you can call start
+ again to run it again.
+ ExampleJob.my_job.start()
+ Parameter
+ sent_from_job can be any do_list item, which will be prepended to the do_list
+ of the job before it is started. This new do_list item is not remembered
+ in subsequent calls to start for this same job instance.
+ It is thus a way to customize a job for each start call.
+
+ Its name comes from its (interal) usage when the instruction send_to_job
+ sends an instruction to a job that has been defined but not yet started.
+ This parameter is not commonly used. Most users can ignore it.
+
+
+
+
+
+Robots
+ A robot is a machine that can execute the instructions in its instruction set. In general,
+ each kind of robot will have its own instruction set. The primary
+ difference between robots is the difference in their instruction sets.
+
+Robot Instructions
+These instructions can be used for any robot, as can the instructions for
+the Human robot.
+
+error
+ Causes the job to error, immediately stopping it.
+ The one argument is a string of a reason for the error which
+ will aid in debugging. Example:
+ Robot.error("fubar")
+
+
+get_page
+ Similar to the function get_page, only made into an instruction.
+ This instruction gets the content of a url and places it in a given user_data variable
+ on the job instance before allowing the next instruction in the do_list to run.
+ Example:
+ Parameters:
+ url_or_options: The url whose contents this instruction gets.
+ Instead of a url as the argument, you can pass a literal JS object with lots of options, described at:
+ options
+
+ response_variable_name: Default: "http_response". The name
+ of the property in the job instance's user_data object to set to the
+ content of the url.
+
+Using make_url can help make constructing calls to get_page a bit easier.
+Example:
+make_url is documented in the reference manual under "I/O".
+
+
+grab_robot_status
+ robot_status is an array that holds data from the robot, along with aspects of the instruction
+ that was sent to the robot to capture that data. This array is the value of the robot
+ instance field robot_status.
+ grab_robot_status provides an easy way to get values out of that array.
+ Parameters
+ user_data_variable A string (required) of the name of the job's
+ user_data variable to shove the grabbed
+ robot_status data into.
+ start_index A non-negative integer signifying the
+ first data item to extract from the robot_status array.
+ Its default value is the value of Serial.DATA0
+ Special values:"all" The entire 60 element robot_status
+ array is used. The value of end_index is ignored.
+ "data_array" The part of the robot_status array after
+ the header information is used. For Serial robots, this will be just
+ the data returned by the serial port. For Dexter robots, this
+ will be the data about Dexter's joint angles, etc.
+ The value of end_index is ignored.
+ end_index A non-negative integer signifying the last element of the
+ robot_status array to extract. The default value is null.
+ If this value is null or not passed, only the data at the start_index
+ is used. The value will NOT be an array, just that one element.
+ Special value"end" The portion of the robot_status
+ from start_index through the end of the robot_status array is extracted.
+
+ If both the start_index and end_index are not passed,
+ then the value will be: For a Serial robot, the first "item"
+ returned from the serial port in response to a send.
+ For Dexter, it will be DMA_READ_DATA.
+
+ You can use some constants for the values of start_index and end_index.
+ For a Dexter robot these are:
+Dexter.JOB_ID
+Dexter.INSTRUCTION_ID
+Dexter.START_TIME //ms since jan 1, 1970 from Dexter's clock
+Dexter.STOP_TIME"
+Dexter.INSTRUCTION_TYPE //a letter signifying the instruction type.
+
+Dexter.ERROR_CODE" //0 means no error.
+Dexter.DMA_READ_DATA"
+Dexter.READ_BLOCK_COUNT"
+Dexter.RECORD_BLOCK_SIZE"
+Dexter.END_EFFECTOR_IN"
+
+Dexter.J1_ANGLE" // BASE_POSITION_AT
+Dexter.J1_DELTA" // BASE_POSITION_DELTA
+Dexter.J1_PID_DELTA" // BASE_POSITION_PID_DELTA
+Dexter.J1_FORCE_CALC_ANGLE" // BASE_POSITION_FORCE_DELTA
+Dexter.J1_A2D_SIN", // BASE_SIN
+Dexter.J1_A2D_COS", // BASE_COS
+Dexter.J1_PLAYBACK", // PLAYBACK_BASE_POSITION
+Dexter.J1_SENT", // SENT_BASE_POSITION
+Dexter.J1_SLOPE", // SLOPE_BASE_POSITION
+
+and a similar set of names beginning with J2, J3, J4 and J5.
+
+For a Serial robot these are:
+Serial.JOB_ID
+Serial.INSTRUCTION_ID
+Serial.START_TIME // ms since jan 1, 1970 from Dexter's clock
+Serial.STOP_TIME // ms since jan 1, 1970 from Dexter's clock
+Serial.INSTRUCTION_TYPE // A letter indicating the instruction type
+
+Serial.ERROR_CODE // means no error.
+Serial.DATA0 // data coming back from the board
+Serial.DATA1
+Serial.DATA2
+Serial.DATA3
+Serial.DATA4
+Serial.DATA5
+Serial.DATA6
+Serial.DATA7
+Serial.DATA8
+Serial.DATA9
+
+
+In order to insure that the Dexter robot_status array is up to date,
+you should place Dexter.get_robot_status() in your do_list before
+the grab_robot_status instruction.
+Example:
+
+Dexter.get_robot_status(),
+Robot.grab_robot_status("no_result", Serial.DATA0),
+See Job Example 9 for an extended example.
+
+
+out
+ Very similar to the function out but made for use as a robot instruction.
+ Prints a message to the Output pane in the color of your choice.
+ Example:
+ Robot.out("hey " + 345, "green")
+ Parameters:
+ val Any JavaScript data. Most commonly this is a string, but
+ can be a number, an array etc.
+ color A string representing a color. Default "black". Can
+ be any string in the color series, or have the format:
+ "rgb(255, 100, 0)".
+
+ This is the most basic debugging tool, often used to let you know that
+ the job its in has reached this instruction. Unlike an instruction such as:
+ function(){out("The status is: " + this.status_code)}
+ Robot.out cannot access its job instance, but it does print out
+ its job name and instruction ID right before printing val.
+
+
+if_any_error
+ if_any_error checks to see if any of the supplied jobs have errored.
+ If so, it inserts the supplied instruction into the do_list on the job
+ that this instruction is on. In either case, if_any_error continues
+ the job that its on.
+ Parameters
+ job_names An array of strings of job names. If a named job doesn't exist, error.
+ instruction_if_error An instruction that will be inserted into the do_list
+ immediately after this instruction IF one of the named jobs has errored.
+ The default for instruction_if_error is a function that
+ inserts an instance of Robot.error into the do_list of this job, causing it to error.
+ The "reason" for that error instruction is explicit about the cause of the error.
+
+ Generally a job should be stopped quickly if there is an error.
+ This instruction makes it easy to stop jobs that are concurrently cooperating
+ with the current job. The instruction_if_error can be a function (called with the
+ current job for "this") so that some arbitrary compensation can be made for the error.
+
+
+
+stop
+ Causes the job to stop. This is an expected stop, as constrasted with
+ Robot.error.
+ The one argument is a string of a reason for stopping which
+ will aid in debugging. Example:
+ Robot.stop("all done")
+
+
+suspend
+ Causes the job to pause. It will not execute any more of its instructions
+ until it is unsuspended. It takes no arguments.
+ Example:Robot.suspend().
+
+ unsuspend is a method on a job.
+ Example:Job.my_job.unsuspend().
+ This causes the job to resume from a suspension. You can call it
+ from any JavaScript code such as in a function that's a do_list item.
+ A job cannot unsuspend itself.
+
+
+sync_point
+ A sync_point instruction cases all running jobs with the same-named sync_point
+ to pause until they all reach the sync_point. Once that happens, they
+ are all allowed to proceed executing their instructions.
+ Parameters
+ name The name of the sync point. Must be identical with other sync points
+ that you expect to be in-sync. There should only be one sync_point
+ with a given name in a job.
+ job_names An array of job names containing same_named sync points that
+ you want to all pause at the same place. A sync_point instruction may
+ contain the name of the job its in. Effectly that doesn't matter,
+ but does allow all the same-named sync points to have the same list of job_names.
+ Example: Robot.sync_point("midway", ["job_one", "job_two"])
+
+ If a sync point instruction has no job names, or only its own job name,
+ it will not wait but rather breeze right through its sync_point.
+ send_to_job can use such "labels" as marking insertion points for its
+ new instructions via the parameter where_to_insert.
+
+ By having different job_names, you can configure a sync_point in one job
+ to wait for the other job's sync point to be reached, yet not have
+ the other job wait for the first job. Any combination of such lop-sided
+ waits can be set up amongst jobs with same-named sync_points for
+ a lot of flexibility. This can increase the overall speed of a cooperating
+ robot group over merely "all pause at each same-named sync_points"
+ because it allows those jobs that can proceed to do so.
+
+
+send_to_job
+send_to_job inserts instructions into another job's do_list. It can also
+start, unsuspend and grab data from another job. send_to_job is complex, powerful,
+and rarely used. Example:
to_job_name The name of the job receiving the new instructions.
+
do_list_item An instruction or array of instructions to insert into the to_job.
+
where_to_insert The location in the do_list of the to_job to insert the do_list_item.
+ Such locations are always after the current program counter of to_job.
+ This must be one of:
+
"next_top_level" (the default). Inserts the do_list_item
+ after the program_counter and just before the next original do_list item.
+ If a function do_list item in to_job returns an array of instructions,
+ this ensures that the inserted do_list_item will not go in the middle of such instructions.
+ Thus if the instructions from the function must be executed as a continuous group,
+ "next_top_level" is a safe place to insert additional do_list items.
+
+
"after_pc" Immediately after the to_job's program_counter. Not as safe as "next_top_level".
+
"end" At the very end of the do_list.
+
sync_point name Immediately after the sync_point that is after the program_counter
+ and has this name. Note that you can have in the to_job do_list a sync_point instructions
+ with no jobs to sync to. In that case, the sync_point is a harmless label for a location
+ that can be used by send_to_job.
+
+
wait_until_done (default false) If true, the from_job will wait until the to_job
+ executes its newly inserted instructions.
+
start (default false) If true, and the to_job has yet to be started,
+ it will be started after the do_list_item is inserted into its do_list.
+
unsuspend (default false) If true, and the to_job is suspended,
+ the to_job will be unsuspended after the do_list_item is inserted into its do_list.
+
status_variable_name The name of a field placed in the user_data of the from_job.
+ It is initialized to "sent". When the inserted do_list_item has been executed,
+ this field is set to "done".
+
other variable names If a parameter to send_to_job is not one of the above,
+ it is assumed to be the name of a field to create in the user_data of the to_job.
+ "Other variable names" have a value of a function. After the do_list_item is executed,
+ the function for each of the other varible names is called within the to_job and
+ the returned value is set to its corresponding other variable name in the
+ user_data of the from_job. This allows the from_job to get data from the to_job
+ immediately after the do_list_item is run.
+
+
+
+sent_from_job
+This instruction is typically not created by users directly. send_to_job creates
+such an instruction and places it on the to_job as a container for the newly inserted
+instructions. However, if you want to extend the do_list of a job when starting it,
+you can pass an instance of sent_from_job as an option
+of start. This will insert the new instruction(s) just before the job is started.
+Example:
+do_list_item can be a single instruction or an array of instructions.
+where_to_insert See doc for send_to_job
+The inserted instructions will not be present if, after running the job,
+you call start with no argument.
+
+
+wait_until
+This instruction causes a job to pause until the supplied condition is met.
+Example:Robot.wait_until(1000)
+The one argument can be:
+
an integer The number of milliseconds for the wait.
+
an instance of Duration The amount of time to wait. Takes numerical arguments
+ of hours, minutes, seconds and milliseconds.
+ Example:new Duration(1, 59, 30, 500)
+ This causes a pause of 1 hour, 59 minutes, 30 seconds and 500 milliseconds.
+
+
an instance of Date Causes a wait until the JavaScript date occurs.
+ Careful, you can easily cause a job to wait for years!
+
a function The function is called at each do_loop iteration.
+ The function's return value is used in a JavaScript if statement.
+ false, undefined, null, 0, NaN, or the empty string ("") are considered to be false.
+ Anything else is considered to be true and the wait will be over.
+ The function is called with a this of the current job,
+ so you can access the entire job's state when determining whether
+ or not to return true.
+
+
+
+
+
+Brain
+Brain is a virtual robot used to manage other robots or do purely software tasks.
+It has no special instructions of its own, but inherits Robot's instructions, just
+like all the other robots.
+
+
+
+Dexter
+Dexter Dexter can perform instructions that command it to move. After it does
+an instruction, it sends back information from its sensors confirming where it has moved
+and additional data. This data can be used in subsequent instructions to both verify
+Dexter's position as well as respond to forces on the arm and other sensor data.
+
+An instance of Dexter is created like so:
+
new Dexter({name: "my_dex",
+ simulate: true
+ })
+
+Multiple jobs may use a given robot instance as their robot. It is up to the programmer
+to make sure such jobs don't screw each other up. You may not have more than one
+active robot with the same name or ip_address.
+new Dexter parameters
+The parameters used to define an instance of Dexter are:
+
+
name Any string, but must be unique across all robots.
+ The instance of the robot is stored in Robot.the_name
+
simulate true or false, default true.
+ If simulate is true, instructions will not be sent to the robot, but rather
+ simulated in software, fully under DDE's control. If simulate is false,
+ the instructions will be sent to the Dexter at the given ip_address.
+
+
ip_address A string of an ip_address such as: "192.168.1.1"
+ Default null. You can use a Dexter without an ip_address, but only with simulate: true
+
port An integer. Default 5000.
+
base_xyz An array of three numbers.
+ Indicates the position of Dexter on its table in microns. Default: [0, 0, 0]
+
base_plane Indicates the plane of Dexter. The default: [0, 0, 0]
+ means that Dexter is standing vertically on a horizontal table surface.
+
base_rotation A number of arc-seconds.
+ The rotation of Dexter's base on the base_plane. Default 0.
+
enable_heartbeat A Dexter instance sends a "heartbeat" to a Dexter robot to
+ keep the connection alive. If true, the default, that heartbeat will be sent.
+
+
+
+Dexter Instructions
+
+
+draw_dxf
+ This instruction accepts the name of a file as input and creates additional instructions
+ to move Dexter to "draw the lines" indicated by the dxf file.
+
filepath A string representing the name of the dxf file under the dde_apps folder
+ containing the dxf instructions. The file can be directly under dde_apps or
+ nested in subfolders of any depth.
+
+ The filepath is usually a string that ends in .dxf or
+ .DXF If it does not and is more than 512 characters long, it
+ will be assumed to be a string of actual dxf code.
+
+
scale
dxf files indicate line endpoint positions as dimensionless units.
+ DDE requires the x,y,z positions to be in microns. scale converts
+ the dxf positions to microns. If scale is a number, it multiplies the dxf
+ positions by that number. The default for scale is 1, meaning no transformation.
+ If the dxf positions are intended to be in millimeters, use 1000 for scale.
+
+ Scale can also be a string representing a scale factor.
+
String
Factor
+
"microns"
1
+
"millimeters"
1000
+
"centimeters"
10000
+
"meters"
1000000
+
"inches"
25400
+
"feet"
304800
+
+
up_distance The distance in microns to "lift the pen above the paper" when drawing a line.
+ Default: 2000
+
+Example:
+ new Job({name: "j1",
+ robot: new Dexter(),
+ do_list: [ Dexter.move_to([200000, 200000, 50000]),
+ Dexter.draw_dxf("UML.DXF")
+ ]})
+ Job.j1.start()
+
+
+empty_instruction_queue
+Parameters: None.
+A Dexter robot has an instruction queue which contains instructions that have been sent from
+DDE but not yet executed. As soon as Dexter recieves an instruction from DDE, it typically acknowledges receipt
+to DDE,
+which causes DDE to send the next instruction in the Job's do_list.
+An empty_instruction_queue instruction changes that behavior and causes all the instructions in the
+queue to be executed before DDE attempts to run another instruction on the do_list.
+
+
+empty_instruction_queue_immediately
+Parameters: None.
+A Dexter robot has an instruction queue which contains instructions that have been sent from
+DDE but not yet executed. As soon as Dexter recieves an instruction from DDE, it typically acknowledges receipt
+to DDE,
+which causes DDE to send the next instruction in the Job's do_list.
+An empty_instruction_queue_immediately instruction removes all the
+instructions from the instruction queue
+without executing them. It then informs DDE to send the next instruction.
+This is an unusual instruction as it implies that the instructions sent to Dexter were in error.
+You might want to do this in an emergency situation or if the environment unexpectedly changes.
+
+
+get_robot_status
+Paramenters: None
+Retrieves lots of information from Dexter. This is placed in an array that becomes the value of
+the job's robot_status field, and, if the job's keep_history is true, gets pushed onto the
+job's rs_history array.
+
+This instruction blocks further processing of the job's do_list instructions until
+all of the instructions on Dexter's instruction_queue are executed.
+
+
+get_robot_status_immediately
+Paramenters: None
+Retrieves lots of information from Dexter. This is placed in an array that becomes the value of
+the job's robot_status field, but is not placed on the job's rs_history array.
+
+Unlike get_robot_status, this instruction causes Dexter to return its data immediately,
+before any of the instructions on its instruction queue are executed.
+
+
+move_to
+This instruction commands Dexter to move from whereever it is, to position its
+end effector at the given x, y, z location. It is complicated by the fact that
+usually there is more than one configuration of Dexter's joints that
+can achieve that position and that Dexter is inherently limited by the
+lengths of its links.
+Parameters
+xyz tells Dexter to position its end effector to a position.
+An array of 3 numbers, each indicating microns from the position 0, 0, 0
+which is at the center of the base of Dexter, in its surface (think table) plane.
+Imagine yourself as Dexter facing forwards. The x-axis is to your left and right
+with left being negative and right being positive. The valid range is
+-747804 to 747804. The Y axis runs from behind you to in front of you with
+negative behind you and positive in front ranging from -747804 to 747804.
+The z axis is vertical with below the table being negative and above the
+table ranging from -582704 to 912904 with 0 being at the table surface.
+Note that not all of the x,y,z combinations are reachable by Dexter.
+If Dexter is on a table, then none of the negative y values are reachable,
+since they are below the table.
+The J5_direction parameter also affects reachability.
+
+J5_direction indicates the direction you want the end effector to be pointing.
+This is an array of 3 numbers (each ranging from -1 to 1)
+that you can think of as indicating a "point" off
+of the end of the end effector. The default is [0, 0, -1] which
+causes the end effector to point straight down. {needs work}
+
+config For most points within the reachability of Dexter, there are multiple
+ways in which Dexter can get there. config helps you specify your preference
+as to how Dexter configures its joints to get to the indicated x, y, z.
+There are 3 independent boolean values to determining this configuration.
+They are:
+
base-rotationLEFT means J1, the base joint has a negative value,
+ ie it is to the right of facing front. Looking down from the top at Dexter this would
+ mean its rotated counter clockwise. The opposite direction is RIGHT
+ or clockwise.
+
J3-position Joint 3 can be thought of as Dexter's elbow. The elbow can be either
+ UP i.e. away from the table or DOWN, closer to the table./li>
+
J4 Position Joint 4 can be thought of as Dexter's wrist. It can be pointing either
+ IN, towards the base, or OUT, away from the base.
+
+Config is most easily specified using one of 26 constants such as:
+Dexter.LEFT_DOWN_IN or Dexter.RIGHT_UP_OUT. You can omit 1 or 2 of these value as in
+Dexter.LEFT_IN or Dexer.OUT. The complete list is:
+The above list is in the series Robot/robot config.
+Not mentioning a boolean (null) means "don't care", ie let DDE figure it out. Since config limits
+the possible options, some configurations will be impossible with some xyz settings and/or
+J5_direction settings. Impossible settings cause an error.
+
+
+move_to_relative
+This function is the same as Dexter.move_to except that the xyz values are ADDED to Dexter's
+existing end effector xyz values, not taken as absolutes.
+
+
+move_all_joints
+move_all_joints is a lower level instruction than move_to, giving you the ability to dicate
+the angle of each of Dexter's 5 joints, J1 through J5. A joint's angle is specified in arc_seconds.
+(There are 3600 arc_seconds per degree and 648,000 per 180 degrees.)
+The min and max angles of each joint are in constants: Dexter.J1_ANGLE_MIN
+through Dexter.J5_ANGLE_MAX, all included in the series Dexter_constant.
+Examples:
+Dexter.move_all_joints(10000, null, 30000)
+Dexter.move_all_joints([10000, null, 30000])
+Both of these have the same function, i.e. you can pass in an array of up to 5 arc_seconds,
+or you can pass in individual numbers.
+null or the lack of enough numbers means keep the angle for that joint what it is at now.
+
+
+move_all_joints_relative
+The same as Dexter.move_all_joints except that the given angles are added to the current
+angles of the robot. null or missing angle increments default to 0.
+
+
+move_home
+Moves all joints to 0. J1 is facing forwards, J2, J3, J4 are straight up. J5
+causes Link 5 to be horizontal pointing forwards.
+Example: Dexter.move_home()
+
+
+make_ins
+Normally you should make instructions for Dexter using one of the high level method calls,
+ie Dexter.move_all_joints. However, we provide the function make_ins,
+useful in some low level situations. The first argument is the instruction type,
+a single letter string such as "a". The remaining arguments are whatever that instruction type
+accepts. Example:
+make_ins("a", 1, 2, 3, 4 ,5) creates an instruction that moves the 5 joints
+by 1, through 5 respectively.
+If you have the arguments in an array, you can use this syntax:
+make_ins("a", ...my_array)
+
+The returned value is an array that has its first several fields empty. DDE uses them
+for storing the job_id, instruction_id and some timing information.
+
+
+run_gcode
+This instruction accepts the name of a file as input and creates additional instructions
+to move Dexter to "draw the lines" indicated by the gcode file.
+
filepath A string representing the name of the gcode file under the dde_apps folder
+ containing the gcode instructions. The file can be directly under dde_apps or
+ nested in subfolders of any depth. Typically the filepath will have an extension of .gcode
+ but that isn't required by filepath.
+
scale
gcode files indicate line endpoint positions as dimensionless units.
+ DDE requires the x,y,z positions to be in microns. scale converts
+ the gcode positions to microns. If scale is a number, it multiplies the gcode
+ positions by that number. The default for scale is 1, meaning no transformation.
+ If the gcode positions are intended to be in millimeters, use 1000 for scale.
+
+ Scale can also be a string representing a scale factor.
+
String
Factor
+
"microns"
1
+
"millimeters"
1000
+
"centimeters"
10000
+
"meters"
1000000
+
"inches"
25400
+
"feet"
304800
+
+
+ run_gcode is similar to draw_dxf. run_gcode only handles G0 and G1 instructions,
+ and only their X, Y, and Z arguments.
+ It treats G0 and G1 the same.
+ run_gcode needs lots of work.
+
+
+
+sleep
+ Causes Dexter to "go to sleep" for the number of milliseconds in the one argument.
+ When Dexter receives the instruction, it waits for that number of milliseconds
+ before returning control to the DDE job.
+ Example:Dexter.sleep(1000)
+ Sleeps for 1 second.
+
+
+
+Dexter Utilities
+
+joint_angle
+Returns the present angle of the joint indicated in the argument in arc_seconds.
+Example: a_robot.joint_angle(2) => some_arc_seconds.
+The argument defaults to 1, ie the base joint.
+
+
+joint_angles
+Takes no arguments. Returns an array of the angles of the 5 joints in arc_seconds.
+Example: a_robot.joint_angles() =>
+[j1_arc_seconds, j2_arc_seconds, j3_arc_seconds, j4_arc_seconds, j5_arc_seconds]
+
+
+joint_xyz
+Takes one argument, an integer from 1 to 5 indicating a joint.
+Returns the present angle of the indicated joint in arc_seconds.
+Example: a_robot.joint_xyz(2) => some number in microns.
+The argument defaults to 5, ie the end effector.
+
+
+joint_xyzs
+Takes no arguments. Returns an array of the xyzs of the 5 joints with
+the base position prepended on the beginning of the returned array.
+Positions are in microns.
+Example: a_robot.joint_xyzs() =>
+
+
+xyz_invalid
+Returns false if the given xyz point does not collide with the table or Dexter.
+Returns joint number and microns below table if xyz is below the table.
+Parameters
+xyz An array of 3 numbers, x, y, and z in microns, in table coordinates.
+J5_direction The direction J5 is pointing as a point. Default: [0, 1, 0]
+config The 'config' of the joints. Default Dexter.RIGHT_UP_IN
+ See Dexter.move_to for explanation of 'config'.
+ Example: a_robot.xyz_invalid([10000, 20000, 30000]) => false
+
+
+
+Dexter Constants
+
+
+
+
+
+Human
+Human is a "robot" that is commanded to do things via pop up dialog boxes.
+Examples of its instructions are Human.task, and Human.enter_number.
+When a human instruction is run, a dialog box is shown and the job waits for a user to
+enter some information and click on a button to either cancel the job (and dependent jobs)
+or proceed.
+
+Human instructions are a way to encode tasks that Dexter can't do or information
+that it can't know. The inclusion of human instructions in DDE permits the design and
+running of jobs that need coodination between humans and machines.
+
+Although the "home" of human instructions is in the Human robot, you can use
+these instructions in a job with any robot. They do not attempt to
+access robot hardware.
+Human Instructions
+task
+ When run, all human instructions present a dialog box on the screen and waits until the
+ user clicks the button before allowing the job to proceed to the
+ next instruction in its do_list. A button is
+ also presented. If clicked, this job and its dependent jobs are stopped.
+ Parameters:
+ task Default: "". A string that will appear in the body of the dialog box. It is intended
+ as an English instruction to the human reading it. When the human has completed
+ the instruction, they should press .
+ If the human is unable to complete the task, they should press
+
+ dependent_job_names Default: []. The names of the jobs that will be stopped if the
+ user presses
+ title Default: the job name and "Human Task". A string shown in the title bar of the dialog.
+ To have no title, pass in "" .
+ x Default: 200. The number of pixels between the left edge of the dialog and the left edge of the DDE window.
+ y Default: 200. The number of pixels between the top edge of the dialog and the top edge of the DDE window.
+ width Default: 400. The width of the dialog box in pixels.
+ height Default: 400. The height of the dialog box in pixels.
+ background_color Default: "rgb(238, 238, 238)" i.e. light gray. The background color of the dialog box.
+ Each of the numbers for red, green, and blue can be between 0 and 255 inclusive. 0,0,0 is black.
+ All of these parameters are common to all human instructions.
+ All are optional. They affect the appearance of the dialog box, except fordependent_job_names.
+
+
+enter_choice
+ Presents a dialog allowing the user to choose one of several supplied options.
+ See Human.task for behavior common to all Human instructions.
+ Uncommon Paramaters:
+ choices Default: []. An array of strings.
+ The user is allowed to select one of the given choices.
+ show_choices_as_buttons true or false, default: false. When false, the choices are
+ shown in a menu with the first choice selected.
+ When true, each choice has a button and there is no button.
+ one_button_per_line true or false, default: false. If true, each button
+ appears on its own line in a vertical stack. If true, the buttons are positioned
+ left to right, taking up more than 1 line only when necessary to display the extra buttons.
+ user_data_variable_name Default: "choice". When the user clicks ,
+ the selected choice will be made the value of the variable named in this parameter.
+ That variable will be in the user_data of the current job.
+ Within another instruction in the same job, the selected choice will be accessible using
+ JavaScript. If the user_data_variable_name is 'my_color' and the choice is 'blue'.
+ then this.users_data.my_color'blue'.
+ You can access this value from another job via:
+ job.some-job-name.user_data.my_color.
+ Note that JavaScript from any job can also reset this value. For example:
+ job.some-job-name.user_data.my_color = 'green'.
+
+
+enter_instruction
+ Presents a dialog allowing the user to enter an instruction to be immediately run.
+ This can also record instructions and create a job with the recorded do_list.
+ See Human.task for behavior common to all Human instructions.
+ This instruction does not use user_data_variable_name.
+ This instruction can only be used on jobs with a Dexter robot.
+ Uncommon Paramaters:
+ instruction_type Default: "Dexter.move_all_joints". Set's the dialog's default instruction type.
+ instruction_args Default "5000, 5000, 5000, 5000, 5000".
+ Set's the dialog's default instruction args.
+ This instruction is a work in progress. See the tooltips in the dialog for help.
+
+
+enter_number
+ Presents a dialog allowing the user to enter a number via typing or clicking.
+ See Human.task for behavior common to all Human instructions.
+ See Human.enter_choice for documentation on the user_data_variable_name parameter.
+ Uncommon Paramaters:
+ initial_value Default: 0.
+ min Default 0. The minimun acceptable value.
+ max Default 100. The maximum acceptable value.
+ step Default 1. The step size that clicking on the increment and decriment arrows will add or subtract
+ to the current value.
+
+
+enter_text
+ Presents a dialog allowing the user to enter text via typing.
+ See Human.task for behavior common to all Human instructions.
+ See Human.enter_choice for documentation on the user_data_variable_name parameter.
+ Uncommon Paramaters:
+ initial_value Default: "OK".
+ line_count Default 1. The number of lines that the input control will be configured for.
+ If this is more than 1, a user will be able to drag the lower right corner of the text field
+ to increase the visible lines.
+
+
+notify
+ Displays information for the user.
+ See Human.task for behavior common to all Human instructions,
+ but unlike other Human instructions, notify does not have a user_data_variable_name parameter,
+ nor do its dialog boxes have buttons.
+ It also does not wait for a user action before allowing its job to continue to the next do_list item.
+ Uncommon Parameters:
+ window true or false, default: true. Whether or not to present the information in a window.
+ output_pane true or false, default: true. Whether or not to present the task in the output pane.
+ beep_count Non-negative integer, default: 0. How many beep 'alerts' to sound when
+ this instruction is run.
+ speak true or false, default: false. Whether or not to speak the title and task when this
+ instruction is run.
+
+
+
+
+
+
+Serial
+Serial is not a specific robot per se, its a connection to another computer via its serial port.
+This connection is very general. It knows nothing about the actual capabilities of what its
+connected to, only that it can send and receive strings on its serial port.
+
+DDE's Serial robot is quite similar to Dexter from DDE's perspective. It
+can be sent instructions from a Job's do_list and its output is interpreted as
+a "robot_status" similarly to Dexter's robot_status. The Serial robot has been
+used to connect to Arduino boards via its USB connector, and should work with Raspberry Pi and other
+similar devices.
+
+Arduino
+In order for the serial port connection to work with Arduino, you need to have
+the Arduino IDE installed. Its a free and easy download from
+https://www.arduino.cc
+If you don't get a connection, sometimes unplugging and replugging the
+USB cable will help. You can also try relaunching DDE.
+Another debugging techinque is using the Arduino IDE's menubar/Tools/Serial Monitor.
+The upper type in area is for a string that you want to send to the board.
+The lower area displays strings coming back from the board.
+
+
+Arduino and Mac
+Beware: It appears that Arduino plays poorly with Macintosh computers.
+We've been unsuccessful at connecting a Sparkfun RedBoard with Mac and
+have heard of other problems between Arduino's Uno R3 boards. We've had success
+with Arduino Leonardo and believe Arduino Micro will also work due to its
+similar communication architecture. (Feb 2017) The Arduino Micro cannot
+accomodate standard Arduino add-on (shield) boards but the Leonardo can.
+
+
+Create an instance of Serial similar to the other robots. Example:
+new Serial({name: "S1", ...})
+
+Parameters to new
+name A string. Makes this instance of a Serial Robot accessible from Robot.the_name
+
+simulate true or false. Default true. If true, no data is sent or recieved over
+the actual serial port.
+
+sim_fun A function. Default return_first_arg. Used only when simulate: true
+When a Serial.string.instruction is simulated, its argument, instruction_string is
+passed to the sim_fun. The value returned from calling sim_fun is the simulated return value (a string)
+from the serial port for this instruction. The function can use any JavaScript to compute
+the returned string.
+Consider the item_delimiter when making up this returned string. Often
+the string should end in the item_delimiter, but it doesn't have to.
+We're not expecting
+the sim_fun to do exactly what the Serial hardware would do. In fact if it could,
+there would be no need for the hardware! Rather sim_fun should perform as a diagnostic
+for at least one case or perhaps a few cases of instruction strings.
+The default value of return_first_arg just returns its input to help you verify that
+the basic communication path is working.
+
+path A string. Required. The label for the device connected to a serial port on the computer running DDE
+that you want this software robot to connect to.
+Valid paths can be seen
+by calling serial_show_devices(). On Windows, they look something like
+ "COM3" .
+On Mac, they look something like "/dev/tty.usbmodem1411".
+ In addition to the tty path, Mac's also have a "cu" path such as: "/dev/cu.usbmodem1411".
+ We've found both tty and cu paths to work with DDE.
+
+connect_options A literal object. Default {}.
+Example: {baudRate: 9600}
+9600 is the default baudRate (which is the same as bitrate, i.e. bits per second). All options documented at
+https://www.npmjs.com/package/serialport#serialport-path-options-opencallback
+
+capture_n_items A non-negative integer. Default 1.
+DDE waits until it has recieved capture_n_items from the device before calling the next instruction on
+the job's do_list. The string returned by the serial device is cut up by item_delimiter,
+to determine the number of items returned by the serial device.
+
+
+item_delimiter A string. Default "\\n". Note that Arduino's
+Serial.println("foo") will send out a 5 character string of "foo\\r\\n"
+
+trim_whitespace A boolean. Default true.
+If this is true, then an "item" (string) returned by the serial port, will have the
+whitespace at its beginning and end removed. Note that with the defaults in place
+of an item_delimiter of "\\n", and trim_whitespace of true,
+then when Arduino executes: Serial.println("hi") the actual 4 characters
+transmitted to DDE are: hi\\r\\n. It is recognized as one item because
+it ends in the delimiter, giving us a 3 character item, except that the trim_whitespace
+takes off that final \\r and we're left with hi, usually what you want.
+
+This arrangement gets around our society's failure to set one standard for the most important formatting
+operation, breaking up of lines, with \\n being used by Unix and Mac, and
+\\r\\n being used by Windows and Arduino. DDE tries to use the more
+sensible \\n where possible. Thus \\n can be our
+default item_delimiter and we still win calling Arduino's Serial.println.
+
+
+parse_items true or false. Default true. If true, the returned items will be converted from strings to
+primitive JS data types: booleans, numbers, arrays, literal objects, strings, and aggrigates of such.
+Example: In Arduino C, you could have a program that executes:
+ Serial.println("[1, 20, 300]");
+With parse_items: true that would result in DDE's robot_status array as an element of
+an array of three integers.
+
+capture_extras One of "error", "ignore" or "capture". Default "error".
+
"error" means that any extra data output by the board will cause an error, halting the current job.
+
"capture" means that extra output will be appended onto the end of the robot_status associated
+ with the last instruction sent. Beware that such data won't be available as soon as the expected
+ data of capture_n_items has been received.
+
"ignore" means that any items after capture_n_items and before the next instruction sent will
+ be thrown away, but will not cause an error.
+
+instruction_callback A function that is called when a valid return value is received
+to control what a job should do next. The default causes the next instruction in the Job's
+do_list to be executed. Usually you won't want to change this.
+
+
+Serial Instructions
+string_instruction
+Has one argument, a string, which is sent the the Serial robot.
+If the argument is not a string, it is converted to one using JSON.stringify .
+The functionality of that string is entirely dependent on how the device
+you are sending it to, interprets it.
+Example: Serial.string_instruction(4.5)
+sends the 3 character string: "4.5" to the serial robot.
+See Job Example 9 for an extended example.
+
+
+
+Debugging Serial
+Due to the interplay between two different computers (the one running DDE and the Serial device)
+and their entirely different software protocols, debugging Serial robot interfaces is challenging.
+DDE provides a number of low level functions that can be invoked without interacting with a job
+to help you verify connectivity.
+
+serial_devices() Returns an array of objects representing
+the available devices on serial ports. the comName field holds the path to the serial
+port that you can use to connect to that device.
+
+
+serial_path_to_info_map Holds the mapping between the
+path of a serial device and lots of properties about it, most of which come from defining
+the associated Serial robot. The value of this global variable is a JS literal object with
+keys of each path to which there is a serial connection, and values of
+another JS literal object holding useful properties of that connection, i.e. its "info".
+You can get the info for a path via
+serial_path_to_info_map[path]
+
+
+serial_connect_low_level("/dev/tty.some_device")
+Allows you to create a software connection between a serial device and DDE software NOT in a job.
+
+
+serial_send_low_level( "some_path", "some_string")
+Allows you to send a string to a serial device from DDE but NOT in a job.
+
+
+serial_disconnect("some_path") Disconnects an existing connection.
+
+
+serial_flush("some_path") Removes all bytes in the given path's input and output buffers.
+
+See Job Example 9 for examples.
+
+
+
+
+
+Window System
+Dealing with HTML, CSS and JavaScript of traditional web apps is complex.
+DDE uses those technologies but with a simplied wrapper for them to help
+users create interactive windows with the most needed features.
+
+show_window
+A call to show_window creates a dialog box using HTML and JavaScript.
+Parameters
+ title A string of the HTML displayed in the window's title bar. Default: "DDE Information"
+ width The number of pixels wide that the window will be. Default: 400
+ height The number of pixels tall that the window will be. Default: 400
+ x The number of pixels that the left edge of the window will be from the left edge of the DDE window.
+ Default: 200
+ y The number of pixels that the top edge of the window will be from the top edge of the DDE window.
+ Default: 200
+ content HTML to be rendered in the body of the window. input tags with type
+ attributes of button and submit will cause the window's
+ callback function to be called. submit will also cause the window to be closed.
+ HTML elements with a class of "clickable" will behave as a button. Clicking on them
+ will cause the window's callback button to be called with a clicked_button_value
+ property of the name, or if none, the id of the clicked on element.
+ Clicking on such HTML elements will not close the window.
+ Example:
+ show_window({
+ content:'<p id="p_id" class="clickable">some para</p>',
+ callback: function (vals){ append_in_ui("p_id", "<h1>hey</h1>")}
+ })
+ callback A function of one argument. It will be called when a the user clicks a button in
+ a show_window. It's argument will be a literal object. Many of its fields are x and y positions
+ reletive to the top-left of html elements in or containing the clicked position.
+ An example:
+ {x: 300, //relative to the parent of the elt clicked on
+ y: 213,
+ clientX: 300, //relative to the content area (the viewport) of the browser window
+ clientY: 213, //This point does not move even if the user moves a scrollbar from within the browser.
+ offsetX: 290, //relative to the html element that the user clicked in
+ offsetY: 68,
+ pageX: 300, //relative to the top left of the fully rendered content area in the browser.
+ pageY: 213,
+ screenX: 395, //relative to the physical display
+ screenY: 270,
+ altKey: false, //true if the alt key (option on Mc) was pressed when the mouse was clicked
+ ctrlKey: false, //control key
+ metaKey: false, //Windows key on Windows OS, command key on Mac
+ shiftKey: false,
+ tagName: "input", //html element tag clicked on.
+ window_index: "1", //a show_window instance identifier.
+ //close_window(window_index)
+ //will close the show_window window.
+ clicked_button_value: "my_in_id", //the 'name' or 'id' attribute of the clicked on element.
+ trim_strings: true}
+ Example show_window_call:
//Called when a button is clicked.
+function show_vals(vals){out(vals)} //this is the default callback
+show_window({
+ content:
+'text: <input type="text" name="my_text" value="Dexter">
+textarea: <textarea name="my_textarea">Hi Rez</textarea>
+checkbox: <input name="my_checkbox" type="checkbox" checked="checked"/>heated bed?
+ <!-- you can add the checked="checked" attribute to make it initially checked. -->
+radio:
+<input type="radio" name="my_radio_group" value="abs" />ABS
+<input type="radio" name="my_radio_group" value="carbon"/>Carbon Fiber
+<input type="radio" name="my_radio_group" value="pla" checked="checked"/>PLA
+ <!-- At most, only 1 radio button can be checked. If none are checked,
+ the return value for the group will be undefined . -->
+number: <input type="number" name="my_number" value="0.4" min="0" max="1" step="0.2"/>
+range: <input type="range" name="my_range" value="33" min="0" max="100"/>
+color: <input type="color" name="my_color" value="#00FF88"/>
+date: <input type="date" name="my_date" value="2017-01-20"/>
+select: <select name="size">
+ <option>Gihugeic</option>
+ <option selected="selected">Ginormace</option> <!--the inital value-->
+ <option>Gilossal</option>
+ </select>
+combo_box: <div name="my_combo_box" class="combo_box" style="display:inline-block;vertical-align:middle;">
+ <option>one</option>
+ <option selected="selected">two</option>
+ </div>
+button: <input type="button" value="Show settings"/>
+submit: <input type="submit" value="OK"/>',
+
+ width:380, height:450, title:"Printer Config", x:100, y:100,
+ callback: show_vals})
+For more examples of calling show_window see the menu Insert/show_window.
+
+
+Window Utilities
+
+close_window
+ Closes a window created with show_window.
+ Parameter:
+ window_index: When a show_window callback function is called, it will be passed a literal object
+ with a property of window_index that can be used as the argument
+ to close_window. This is a non-negative integer.
+ Example: close_window(window_index)
+
+
+append_in_ui
+Creates an element from HTML and inserts it into a window.
+Parameters:
+path_string: The path to a shown HTML element. Usually this will be the id of
+an element in a show_window window. The new element will become
+the new last child of the path element.
+new_htnl: A string of HTML to create the new element.
+Example: append_in_ui("my_in_id", "<h1>hello</h1>")
+where "my_ui_id" is the id of a currently displayed html tag, usually in
+the content of a show_window window.
+
+
+get_in_ui
+Gets the value of an attribute of an HTML tag (usually from a show_window window).
+Parameters:
+path_string The path to a shown html element. This is often
+the id of an element followed by a dot, follwed by an attribute name.
+callback A function that is called by get_in_ui with the value
+of the attribute indicated in the path_string.
+
+Example: get_in_ui("my_in_id.value", function(val){out("got val: " + val)})
+
+
+remove_in_ui
+Remove an HTML element (usually from a show_window window).
+Parameter:
+path_string The path to a shown html element. This is often just the id of an element.
+Example: remove_in_ui("my_in_id")
+
+
+replace_in_ui
+Replace an HTML element (usually from a show_window window).
+Parameters:
+path_string The path to a shown html element. This is often just the id of an element.
+new_html: A string of HTML to create the new element.
+Example: replace_in_ui("my_in_id", "<h2>hey</h2>")
+
+
+set_in_ui
+Set the value of an HTML element attribute (usually from a show_window window).
+Parameters:
+path_string The path to a shown html element's attribute.
+This is often the id of an element followed by a dot, followed by an attributre name.
+value: The value of an HTML element's attribute. Usually this is a string.
+Example: set_in_ui("my_in_id.value", "aluminum")
+
+
+
+SVG
+SVG stands for Scalable Vector Graphics. It is a way
+to draw 2D graphics on a web page. The drawn elements
+(circles, lines, etc.) are surrounded by a svg tag wrapper
+indicating the size of the drawing area. You can use
+svg tags directly in the content for a show_window.
+The methods documented below create that html from JavaScript calls,
+facilitating dynamic content creation as well as
+making static svg shapes a little easier to create.
+Parameters for all svg functions:
+id The html id of the element, useful in calls to window utility functions
+such as append_in_ui.
+html_class: Used to set the class attrbute of the element.
+Due to a name conflict with class in JavaScript, we had to name this
+html_class.
+style: A string setting the css style of the element. Note that some
+arguments to svg functions are actually rendered as style attributes, such as
+color, border_color, border_width.
+
+svg_svg
+svg shapes must be drawn as child elements of an svg element.
+The x and y of those child elements is relative to the upper left corner of
+the containing svg element. So for instance, if you draw a circle with
+x: 0, y: 0, you will see only the lower right corner of the circle
+in the upper left corner of the svg area.
+Parameters
+width: Width in pixels of the rectangle area to put svg shapes in.
+height: Height in pixels of the rectangle area to put svg shapes in.
+viewBox: A string of four space_separated numbers that controls the scale and positioning
+ of the contained svg elements.
+child_elements: Default: []. An array of strings of the html for
+ svg shapes. Usually these strings should be created with the svg shape creator functions
+ such as svg_circle.
+ Example:
+
+
+svg_circle
+svg_circle must be drawn as a child element of an svg element.
+Parameters
+cx: Default: 0. The x position of the center of the circle.
+cy: Default: 0. The y position of the center of the circle.
+r: Default: 10. The radius of the circle.
+color: Default: "black". The color of the interior of the circle.
+border_color: Default: "black". The color of the perimeter of the circle.
+border_width: Default: 1. The width of the perimeter of the circle.
+Example:
+svg_circle({cx: 100, cy: 50, r: 7, color: "red"})
+
+
+svg_ellipse
+svg_ellipse must be drawn as a child element of an svg element.
+Parameters
+cx: Default: 0. The x position of the center of the ellipse.
+cy: Default: 0. The y position of the center of the ellipse.
+rx: Default: 20. The x radius of the ellipse.
+ry: Default: 20. The y radius of the ellipse.
+
+color: Default: "black". The color of the interior of the ellipse.
+border_color: Default: "black". The color of the perimeter of the ellipse.
+border_width: Default: 1. The width of the perimeter of the ellipse.
+Example:
+svg_ellipse({cx: 100, cy: 50, r: 7, color: "red"})
+
+
+svg_html
+This renders arbitrary html at the location specified.
+svg_html must be drawn as a child element of an svg element.
+Parameters
+x: Default: 0. The x position of the upper left of the rendered HTML.
+y: Default: 0. The y position of the upper left of the rendered HTML.
+width: Default: 100. The width of the area to render the HTML into.
+height: Default: 100. The height of the area to render the HTML into.
+
+Unlike the other svg functions, svg_html does not take id, class
+and style arguments. If you desire these, they must be placed on the individual
+html tags within the value of the html argument. Note that
+here we need to spell the class attribute by its correct HTML name, class,
+not the special spelling used in the other svg functions of html_class.
+
+Example:
+
+
+
+svg_line
+svg_line must be drawn as a child element of an svg element.
+Parameters
+x1: Default: 0. The x position of the start of the line.
+y1: Default: 0. The y position of the start of the line.
+x2: Default: 100. The x position of the end of the line.
+y2: Default: 100. The x position of the end of the line.
+
+color: Default: "black". The color of the line.
+width: Default: 1. The width of the line.
+Example:
+svg_line({x1: 10, y1: 50, x2: 75, y2: 100, color: "red", width: 5})
+
+
+svg_rect
+svg_rect must be drawn as a child element of an svg element.
+Parameters
+x: Default: 0. The x position of the upper left corner of the rectangle.
+y: Default: 0. The y position of the upper left corner of the rectangle.
+width: Default: 100. The pixels between the left and right edges of the rectangle.
+height: Default: 100. The pixels between the top and bottom edges of the rectangle.
+rx: Default: 0. The x-axis radius of the ellipse used to round off the corners of the rectangle.
+ An rx of 0 and an ry of 0 (the defaults), gives square corners.
+ry: Default: 0. The y-axis radius of the ellipse used to round off the corners of the rectangle.
+color: Default: "black". The color of the interior of the rectangle.
+border_color: Default: "black". The color of the perimeter of the rectangle.
+border_width: Default: 1. The width of the perimeter of the rectangle.
+Example:
+svg_rect({x: 10, y: 50, width: 75, height: 25, color: "green"})
+
+
+svg_polygon
+Draws a closed figure with corners at the indicated x and y positions.
+svg_polygon must be drawn as a child element of an svg element.
+Parameters
+points: Default: []. The positions of the corners of the polygon.
+color: Default: "black". The color of the interior of the polygon.
+border_color: Default: "black". The color of the perimeter of the polygon.
+border_width: Default: 1. The width of the perimeter of the polygon.
+Example of a triangle:
+svg_polygon([[0, 0], [100, 0], [50, 50]], color: "lime"})
+
+
+svg_polyline
+Draws an open figure with corners at the indicated x and y positions.
+svg_polyline must be drawn as a child element of an svg element.
+Parameters
+points: Default: []. The positions of the end points of the line segments.
+color: Default: "black". The color of the line.
+width: Default: 1. The width of the line.
+Example of a triangle:
+svg_polyline({points: [[0, 0], [100, 0], [50, 50]], color: "brown"})
+
+
+svg_text
+Draws text at the indicated x and y position.
+svg_text must be drawn as a child element of an svg element.
+Parameters
+text: Default: "hi". The string to be displayed.
+x: Default: 20. The x position of the upper left corner of the text.
+y: Default: 20. The y position of the upper left corner of the text.
+size: Default: 16. The font size of the text.
+color: Default: "black". The color of the text.
+border_color: Default: "black". The color of the outline of the text.
+border_width: Default: 0. The width of the outline of the text.
+transform: Default: "rotate(0, 0, 0)". Modifies the position, orientation and scale of the text.
+ Details
+
+Example:
+svg_text([[0, 0], [100, 0], [50, 50]], color: "brown"})
+
+
+
+
+
+
+Object System
+Overview
+An object system helps you organize data that can inherit from
+other objects or classes. Most programming languages have a
+class-instance based object system. JavaScript's new class-based
+object system is a mediocre class-instance object system.
+But the original JavaScript object system is supposed to
+be a "prototype" object system. Good prototype object systems
+are simpler, more flexible and easier to learn than
+class-instance object systems. However, JS's original object
+system isn't a good prototype object system as demonstrated by
+the numerous object system varients added on to JS, including
+JS 6's class object system.
+
+One of the problems with class-instance object systems is that
+they force you to decide whether an object should be a class
+or an instance. But sometimes you want to use a particular object
+as both a class (to inherit from) and an instance (that
+you can set instance variables in). You may also want to
+"inhert" from an "instance". One of the most powerful
+descriptive mechanisms in natural language is to say
+something like "The chair I want is just like this one
+except its blue." This is using an instance of a chair
+to describe another instance of chair that inherits
+from the first instance. Class-instance object systems
+don't allow you to do this, but good prototype object systems
+and DDE's object system do.
+
+We've coerced JS's prototype object system into
+a more useful one by adding some methods to JavaScript.
+These new methods, in conjunction with existing JS functions,
+give you a pretty good prototype object system.
+
+
+
+New Object System Methods
+DDE augments JS with some new variables, functions and methods to
+help you get the most value out of a prototype object system.
+
+Root
+Root is a global constant that contains the root object of DDE's object system.
+
+
+newObject
+newObject let's you create a new object. It takes
+literal objects as arguments, usually just one.
+The properties of the arguments become the properties
+of the new object. If two of the input objects have a same named property,
+the property in the resulting object will have the value of the last argument.
+There are three properties that behave
+specially.
+
+prototype This property sets the "parent" object
+of the new object. prototype defaults to code>Root.
+Once you have the new object, new_obj.prototype gives you
+back that prototype. Unlike most other properties, you cannot set this property and win.
+Class-instance object systems don't allow you to change the class of an object.
+In practice, this usually isn't needed.
+
+name This optional property gives the new object a "name"
+property (as is normal), but it also creates a field in the prototype
+object with the new name and a value of the new object. By doing this,
+you have a path from the Root to this new object using the
+object names from the top on down separated by dot.
+The names immediately under the root object are global so
+you can omit Root from such paths.
+
+You should only supply a name when calling newObject, and never set it.
+Examples:
+newObject({
+ name: "vehicle",
+ color: "white",
+ weight: 3000})
+Root.vehicle => the new object
+Root.vehicle.name => "name"
+Root.vehicle.color => "white"
+newObject({
+ prototype: Root.vehicle,
+ name: "boat",
+ color: "blue"})
+Root.vehicle.boat => the new object
+Root.vehicle.boat.name => "boat"
+Root.vehicle.boat.color => "blue"
+Root.vehicle.boat.weight => 3000 //inheited from vehicle
+Root.vehicle.boat.color = "green"
+Root.vehicle.boat.color => "green"
+Root.vehicle.color => "white" // hasn't changed.
+Root.vehicle.weight = 2000
+Root.vehicle.boat.weight => 2000 //inherits the new value from vehicle
+Root.vehicle.launch = function(){return "set sail"}
+Root.vehicle.launch() => "set sail"
+Root.vehicle.boat.launch() => "set sail"
+
+constructor
+When creating an object, (or afterwards) you can set a property named
+constructor in the new object to a method. This method is called
+whenever a new object is created with newObject.
+Unlike its counterpart in JS6 classes, constructor
+is called with no arguments. However, this
+is our new object with all the fields populated from the properties
+passed in the call to newObject, saving a ton of boiler plate code.
+In the body of constructor, you can call any code you like,
+including code that modifies the passed in property values, create
+entirely new properties or remove ones from this.
+
+Example: newObject({name: "animal",
+ constructor: function(){ this.fur = "no"}})
+newObject({prototype: Root.animal,
+ name: "fido"})
+
+Above, during the first call to newObject, this is bound
+to the animal object. But when the 2nd call to newObect is
+made, the this in animal.constructor is bound to
+the object in Root.animal.fido.
+Here's the state of the relevant properties:
+
+Root.animal.fur => "no"
+Root.animal.fido.fur => "no"
+
+Each object has its own copy of the "fur" property.
+Setting one will not set the other.
+
+JS6 class constructor methods can have a call to super.
+It's counterpart in DDE is a method whose name makes sense:
+callPrototypeConstructor, documented below.
+
+
+callPrototypeConstructor
+When you have a hierarchy of objects, often you want an object low in the
+hierarchy to be initialized similarly to ones higher up, but with
+some modifications. Thus you'd have constructor on a "vehicle" object,
+then another one on a sub-object, "boat". The boat object should
+probably call the constructor for the vehicle object at the top
+of the boat constructor, and then make additional modifications to
+"this" in the bottom part of the boat constructor method.
+
+Example:
+newObject({name: "animal",
+ constructor: function(){ this.fur = "no"}})
+newObject({prototype: Root.animal, name: "mammal",
+ constructor: function(){
+ this.callPrototypeConstructor()
+ this.fur = "usually"
+ this.hair = "sometimes"
+ out("in mammal constructor")}})
+After running the above code,
+
+Root.animal.fur => "no".
+Root.animal.mammal.fur => "usually"
+Root.animal.mammal.hair => "sometimes"
+
+You don't have to call callPrototypeConstructor,
+and even if you do, it doesn't have to be before
+the lower level constructor function modifies this
+though usually these are good practices.
+
+
+isNewObject
+Returns true if the argument was created with newObject.
+Examples:
+Object.isNewObject({a:11}) => false
+Object.isNewObject(newObject({name: "trash"})) => true
+
+
+subObjects
+Returns an array of the named subojects of this
+Example:
+Root.subObjects() => array of the top level named new objects.
+
+
+isSubObject
+The primary relationship between objects in DDE's object system
+is the prototype relationship. An object inherits properties from
+its prototype. If you want an object to have a different value
+for a particular property than its prototype object does,
+ust create a property in the object, and that will effectiely
+"shadow" the prototype value and use the "local" value in the object
+for that property.
+
+An object always knows which object is its prototype. (All objects
+have a prototype except Root.) But prototypes only know
+what objects have them as their prototype if those other objects
+are named, which is optional.
+By giving an object a name, you automatically install a property
+in its prototype with a key of that name and a value of the object.
+Now the prototype knows about its "children". We used the term subObject
+to mean such named objects.
+
+With no argument,
+returns true if this is a named new object and that name is a
+property in this.prototype with a value of this.
+In other words: this == this.prototype[this.name]
+Example:
+newObject({prototype: Root, name: "junk"}).isSubObject() => true
+
+With an argument, the argument is the presumed prototype of this.
+If the argument is this's prototype, and the prototype has a field in it named the same as this,
+and its value is this, then isSubObect returns true.
+Example:
+newObject({prototype: Root, name: "junk"}).isSubObject(Root) => true
+
+
+
+isA
+Returns true if this is the same as or is
+an ancestor of the argument.
+Examples:
+newObject({name: "junk"}).isA(Root) => true
+newObject({name: "junk"}).isA(123) => false
+
+
+
+siblings
+Returns an array of the siblings of this.
+These will be the named objects that have the same prototype as this.
+Parameter
+include_this Default: false. If true, returns an array of all the
+ named objects that have the same prototype as this.
+ If false, excludes this from the returned array.
+Example:
+Root.siblings() => [] //the root never has siblings.
+
+
+
+areSiblings
+Returns true if all arguments have the same prototype,
+Otherwise returns false.
+Examples:
+Object.areSiblings(newObject({}), newObject({})) => true
+Object.areSiblings(newObject({}), "hey") => false
+
+
+
+inheritsPropertyFrom
+Returns the closest ancestor to this that contains the
+property named by the string in the argument. If this
+happens to have that name as a property, this will be returned.
+Returns null if no such prop name.
+Examples:
+newObject({}).inheritsPropertyFrom("isA") => Root
+newObject({}).inheritsPropertyFrom("isn't a prop name") => null
+
+
+
+ancestors
+Returns an array of the ancestors of this.
+Does not include this in the returned array.
+Examples:
+newObject().ancestors() => [Root]
+
+
+
+allCommonAncestors
+Returns an array of all the ancestors that the arguments have in common.
+Examples:
+Object.allCommonAncestors(newObject(), newObject()) => [Root]
+
+
+
+lowestCommonAncestor
+Returns the lowest common ancestor of the arguments. If none, return null.
+Examples:
+Object.lowestCommonAncestor(newObject(), newObject()) => Root
+
+
+
+normal_keys
+Returns an array of property names in, or inherited by, this.
+Parameters
+passing no args Allowing all 4 args to default to false.
+Example: vehicle.normal_keys() => ["color", "weight"]
+include_inherited Property names of all ancestors excluding Root are in the resulting array.
+The default is false.
+Example: vehicle.normal_keys(true) => ["color", "weight", "size"]
+include_functions Those properties whose values are functions are included.
+The default is false.
+Example: vehicle.normal_keys(true, true) => ["color", "weight", "size", "constructor"]
+The default is false.
+include_subobject_names The names of the subObjects will be included.
+These will be siblings, uncles, great uncles, etc. but not cousins.
+The default is false.
+Example: Root.vehicle.normal_keys(true, true, true) => ["color", "weight", "size", "constructor", "house"]
+include_name_and_prototype The keys "'name" and "prototype" will be included.
+The default is false.
+Example: Root.vehicle.normal_keys(true, true, true, true) => ["color", "weight", "size", "constructor", "house", "name", "prototype"]
+
+Note that you shouldn't depend on the order of the elements in the result array.
+If you want to force them into a consistent order, you can sort them alphabetically.
+
+The use of "normal" in this method's name indicates that by passing no args,
+it gets you what you'll most likely want, and passing in more and more true arguments
+gets you more of the less-frequently used properties. (Your milage may vary,
+but thats the general idea behind the name.)
+
+
+objectPath
+Returns a string of the path to this such as
+"Root.animal.lion" Evaluating the returned string
+will result in the object.
+Example:
+newObject({name: "junk"}).objectPath() => "junk"
+
+
+
+sourceCode
+Returns a string of source code for this.
+Evaluating the returned string will return a copy of this.
+Example:
+newObject({name: "junk"}).sourceCode() =>
+"{prototype: Root,\n name: \"junk\",\n prototype: Root}\n"
+
+
+
+
+Existing JS methods
+hasOwnProperty
+ Returns true if the argument is the name of a property directly in the subject.
+ Example
+ Root.vehicle.hasOwnProperty("color") => true
+
+
+getOwnPropertyNames
+ Returns an array of strings of the property names directly in the subject.
+ Example
+ Object.getOwnPropertyNames(Root.vehicle) => ["prototype", "name", "color", "weight"]
+
+
+keys
+ Returns an array of strings of the property names directly in the subject.
+ Example
+ Object.keys(Root.vehicle) => ["prototype", "name", "color", "weight"]
+ Note: This is the same as getOwnPropertyNames for DDE objects but on JS objects,
+ keys returns all the inherited properties too.
+
+
+
+
+
+entries
+ Returns an array of arrays. Each inner array has elemetns of a property
+ name and its value. Only includes properties directly in the subject.
+ Example
+ Object.entries(Root.vehicle) =>
+ [["prototype", Root],
+ ["name", "vehicle"],
+ ["color", "blue"],
+ ["weight", 3000]]
+
+
+is
+ Returns true if all the arguments are the same object, false otherwise.
+ Example
+ Object.is(Root.vehicle, Root.vehicle) => true
+
+
+isPrototypeOf
+ Returns true if the subject is the same as, or an ancestor of, the argument.
+ Example
+ Root.isPrototypeOf(Root.vehicle) => true
+ Note this is like isA (documented above) but with the
+ subject and argument swapped.
+
+
+getPrototypeOf
+ Returns the prototype of the argument.
+ Example
+ Object.getPrototypeOf(Root.vehicle) => Root
+ Note: this is the same functionality as vehicle.prototype
+
+
+toString
+ Returns a string representation of the subject.
+ Example
+ Root.vehicle.toString() => "[object, Object]"
+ Note: this is just as useless as for normal JS objects.
+ Use instead:
+ Root.vehicle.objectPath() => "Root.vehicle"
+
+
+
\ No newline at end of file
diff --git a/doc/release_notes.html b/doc/release_notes.html
new file mode 100644
index 00000000..0edbfba9
--- /dev/null
+++ b/doc/release_notes.html
@@ -0,0 +1,105 @@
+v 1.0.0, Feb 20, 2017
+Highlights: New Electron Framework, New instruction Robot.grab_robot_status,
+Serial Port extensions, file access improved, dxf improvements.
+
+
Electron Framework replaces Google Chrome App. Facilitates
+ single JavaScript environment and utilization of node.js packages.
+
+
The persistent db is now stored in a file named dde_apps/persistent.json
+ Unlike the previous DDE, you can now look at this file in text editor
+ and easily see exactly what's in it. If you edit this file.
+ do so when DDE is not running because dde will over-write it.
+ You can even move this file to another installation of DDE
+ and have it work.
+
+
Switching between files now remembers the old scroll position and
+ selection of a file so that if you switch back to it, it scrolls
+ to (almost) the same place and highlights the selection.
+
+
If the "file" you are editing is "new file", and you quit and
+ relaunch DDE, you will be showed an empty "new file" in the editor
+ instead of one of your previously edited files.
+
+
The get_page function is now syncrhonus. It does not
+ take a callback, and it returns the contents of the url
+ in its argument. A new function get_page_asynchronous
+ does take a callback and does not return
+ the contents of the url in its first argument.
+
+
+
Robot.get_page has changed slightly incompatibly
+ in a similar way to the get_page function call.
+ Its first argument is a url_or_options,
+ Its second arg is response_variable_name.
+ There are no other arguments.
+ The Get_page instruction cause the job to not advance to the next instruction
+ until the get_page request has completed.
+ If get_page has errored, the response_variable_name will contain
+ a string starting with: "Error: "
+
+
The Dexter and job for calibration is no longer defined upon start up.
+ You have to call:
+ init_calibration()
+ This returns the job, which you can then do:
+ init_calibration().start() to start the job.
+ We'll be making this easier in the near future.
+
+
+
job examples 3 & 7 improved.
+
+
file_content now doesn't take a callback and just returns the string
+ of the content of the file indicated in the path of its first argument.
+
+
load_files now doesn't take a callback and just returns the value of the
+ last expression in the last file loaded.
+ The "paths" parameter to load_files has been simplified. See the ref man doc.
+
+
minor improvements to SVG examples. All SVG examples work.
+
+
Documentation: added into the doc pane,
+ the url to the HDRobotic video page (under About) and the DDE video
+ (under "User Interface")
+
+
+
serial port improvements:
+
serial_devices() returns a list of available serial port devices.
+
serial_path_to_info_map holds an object for each connected serial port device.
+
New Job Example 9 for Serial Port & Arduino tutorial
+
+
+
Job Examples now on a submenu under the Jobs menu.
+
+
Removed job instance field: robot_status. It as redundant and error prone.
+ Use Job.j1.robot.rotbut_status to get it if you need it,
+ but you won't because ....
+
+
New instruction Robot.grab_robot_status makes getting at
+ data in robot_status much easier
+
+
newObject now ignores "name" arg if it is null or undefined.
+ But if it is some OTHER non-string, newObject errors.
+
+
Dexter.draw_dxf fixed bug that ignored the 3rd argument and always treated it as 2000
+
Dexter.draw_dxf first argument is usually a string <= 512 long
+ that ends in .dxf or .DXF. If it does not, the first argument
+ will be assumed to be a string of actual dxf code.
+
+
File access is restricted to files under the "dde_apps" folder in your
+ Documents folder. You no longer need to set up a server to access these files,
+ or to have edited them first.
+
+
You can now use the JavaScript functions: alert, confirm, prompt,
+ quite useful for debugging and rapid prototyping.
+
+
tweaks to the UI to make it "fit" better.
+
+
New "Eval Doc" button in the Doc pane. Let's you evaluated
+ a selected code example in the Doc pane and see the result
+ in the output pane.
+
+
Replaced the individual videos with
+ just one url to the hdrobotic.com video page.
+
+
+
+
diff --git a/dxf-parser.js b/dxf-parser.js
new file mode 100755
index 00000000..323cb86b
--- /dev/null
+++ b/dxf-parser.js
@@ -0,0 +1,2018 @@
+/*downloaded from https://github.com/gdsestimating/dxf-parser on Aug 15 by Fry and hacked
+to remove all the export junk.
+This version of the file contains all 3 of the color table, scanner, and parser.
+The last mod date on the file is May 27, 2016
+ */
+
+/**
+ * AutoCad files sometimes use an indexed color value between 1 and 255 inclusive.
+ * Each value corresponds to a color. index 1 is red, that is 16711680 or 0xFF0000.
+ * index 0 and 256, while included in this array, are actually reserved for inheritance
+ * values in AutoCad so they should not be used for index color lookups.
+ */
+
+var AUTO_CAD_COLOR_INDEX = [
+ 0,
+ 16711680,
+ 16776960,
+ 65280,
+ 65535,
+ 255,
+ 16711935,
+ 16777215,
+ 8421504,
+ 12632256,
+ 16711680,
+ 16744319,
+ 13369344,
+ 13395558,
+ 10027008,
+ 10046540,
+ 8323072,
+ 8339263,
+ 4980736,
+ 4990502,
+ 16727808,
+ 16752511,
+ 13382400,
+ 13401958,
+ 10036736,
+ 10051404,
+ 8331008,
+ 8343359,
+ 4985600,
+ 4992806,
+ 16744192,
+ 16760703,
+ 13395456,
+ 13408614,
+ 10046464,
+ 10056268,
+ 8339200,
+ 8347455,
+ 4990464,
+ 4995366,
+ 16760576,
+ 16768895,
+ 13408512,
+ 13415014,
+ 10056192,
+ 10061132,
+ 8347392,
+ 8351551,
+ 4995328,
+ 4997670,
+ 16776960,
+ 16777087,
+ 13421568,
+ 13421670,
+ 10000384,
+ 10000460,
+ 8355584,
+ 8355647,
+ 5000192,
+ 5000230,
+ 12582656,
+ 14679935,
+ 10079232,
+ 11717734,
+ 7510016,
+ 8755276,
+ 6258432,
+ 7307071,
+ 3755008,
+ 4344870,
+ 8388352,
+ 12582783,
+ 6736896,
+ 10079334,
+ 5019648,
+ 7510092,
+ 4161280,
+ 6258495,
+ 2509824,
+ 3755046,
+ 4194048,
+ 10485631,
+ 3394560,
+ 8375398,
+ 2529280,
+ 6264908,
+ 2064128,
+ 5209919,
+ 1264640,
+ 3099686,
+ 65280,
+ 8388479,
+ 52224,
+ 6736998,
+ 38912,
+ 5019724,
+ 32512,
+ 4161343,
+ 19456,
+ 2509862,
+ 65343,
+ 8388511,
+ 52275,
+ 6737023,
+ 38950,
+ 5019743,
+ 32543,
+ 4161359,
+ 19475,
+ 2509871,
+ 65407,
+ 8388543,
+ 52326,
+ 6737049,
+ 38988,
+ 5019762,
+ 32575,
+ 4161375,
+ 19494,
+ 2509881,
+ 65471,
+ 8388575,
+ 52377,
+ 6737074,
+ 39026,
+ 5019781,
+ 32607,
+ 4161391,
+ 19513,
+ 2509890,
+ 65535,
+ 8388607,
+ 52428,
+ 6737100,
+ 39064,
+ 5019800,
+ 32639,
+ 4161407,
+ 19532,
+ 2509900,
+ 49151,
+ 8380415,
+ 39372,
+ 6730444,
+ 29336,
+ 5014936,
+ 24447,
+ 4157311,
+ 14668,
+ 2507340,
+ 32767,
+ 8372223,
+ 26316,
+ 6724044,
+ 19608,
+ 5010072,
+ 16255,
+ 4153215,
+ 9804,
+ 2505036,
+ 16383,
+ 8364031,
+ 13260,
+ 6717388,
+ 9880,
+ 5005208,
+ 8063,
+ 4149119,
+ 4940,
+ 2502476,
+ 255,
+ 8355839,
+ 204,
+ 6710988,
+ 152,
+ 5000344,
+ 127,
+ 4145023,
+ 76,
+ 2500172,
+ 4129023,
+ 10452991,
+ 3342540,
+ 8349388,
+ 2490520,
+ 6245528,
+ 2031743,
+ 5193599,
+ 1245260,
+ 3089996,
+ 8323327,
+ 12550143,
+ 6684876,
+ 10053324,
+ 4980888,
+ 7490712,
+ 4128895,
+ 6242175,
+ 2490444,
+ 3745356,
+ 12517631,
+ 14647295,
+ 10027212,
+ 11691724,
+ 7471256,
+ 8735896,
+ 6226047,
+ 7290751,
+ 3735628,
+ 4335180,
+ 16711935,
+ 16744447,
+ 13369548,
+ 13395660,
+ 9961624,
+ 9981080,
+ 8323199,
+ 8339327,
+ 4980812,
+ 4990540,
+ 16711871,
+ 16744415,
+ 13369497,
+ 13395634,
+ 9961586,
+ 9981061,
+ 8323167,
+ 8339311,
+ 4980793,
+ 4990530,
+ 16711807,
+ 16744383,
+ 13369446,
+ 13395609,
+ 9961548,
+ 9981042,
+ 8323135,
+ 8339295,
+ 4980774,
+ 4990521,
+ 16711743,
+ 16744351,
+ 13369395,
+ 13395583,
+ 9961510,
+ 9981023,
+ 8323103,
+ 8339279,
+ 4980755,
+ 4990511,
+ 3355443,
+ 5987163,
+ 8684676,
+ 11382189,
+ 14079702,
+ 16777215
+]
+
+/**
+ * DxfArrayScanner
+ *
+ * Based off the AutoCad 2012 DXF Reference
+ * http://images.autodesk.com/adsk/files/autocad_2012_pdf_dxf-reference_enu.pdf
+ *
+ * Reads through an array representing lines of a dxf file. Takes an array and
+ * provides an easy interface to extract group code and value pairs.
+ * @param data - an array where each element represents a line in the dxf file
+ * @constructor
+ */
+function DxfArrayScanner(data) {
+ this._pointer = 0;
+ this._data = data;
+ this._eof = false;
+}
+
+/**
+ * Gets the next group (code, value) from the array. A group is two consecutive elements
+ * in the array. The first is the code, the second is the value.
+ * @returns {{code: Number}|*}
+ */
+DxfArrayScanner.prototype.next = function() {
+ var group;
+ if(!this.hasNext()) {
+ if(!this._eof)
+ throw new Error('Unexpected end of input: EOF group not read before end of file. Ended on code ' + this._data[this._pointer]);
+ else
+ throw new Error('Cannot call \'next\' after EOF group has been read');
+ }
+
+ group = {
+ code: parseInt(this._data[this._pointer])
+ };
+
+ this._pointer++;
+
+ group.value = parseGroupValue(group.code, this._data[this._pointer].trim());
+
+ this._pointer++;
+
+ if(group.code === 0 && group.value === 'EOF') this._eof = true;
+
+ return group;
+};
+
+/**
+ * Returns true if there is another code/value pair (2 elements in the array).
+ * @returns {boolean}
+ */
+DxfArrayScanner.prototype.hasNext = function() {
+ // Check if we have read EOF group code
+ if(this._eof) {
+ return false;
+ }
+
+ // We need to be sure there are two lines available
+ if(this._pointer > this._data.length - 2) {
+ return false;
+ }
+ return true;
+};
+
+/**
+ * Returns true if the scanner is at the end of the array
+ * @returns {boolean}
+ */
+DxfArrayScanner.prototype.isEOF = function() {
+ return this._eof;
+};
+
+/**
+ * Parse a value to its proper type.
+ * See pages 3 - 10 of the AutoCad DXF 2012 reference given at the top of this file
+ *
+ * @param code
+ * @param value
+ * @returns {*}
+ */
+function parseGroupValue(code, value) {
+ if(code <= 9) return value;
+ if(code >= 10 && code <= 59) return parseFloat(value);
+ if(code >= 60 && code <= 99) return parseInt(value);
+ if(code >= 100 && code <= 109) return value;
+ if(code >= 110 && code <= 149) return parseFloat(value);
+ if(code >= 160 && code <= 179) return parseInt(value);
+ if(code >= 210 && code <= 239) return parseFloat(value);
+ if(code >= 270 && code <= 289) return parseInt(value);
+ if(code >= 290 && code <= 299) return parseBoolean(value);
+ if(code >= 300 && code <= 369) return value;
+ if(code >= 370 && code <= 389) return parseInt(value);
+ if(code >= 390 && code <= 399) return value;
+ if(code >= 400 && code <= 409) return parseInt(value);
+ if(code >= 410 && code <= 419) return value;
+ if(code >= 420 && code <= 429) return parseInt(value);
+ if(code >= 430 && code <= 439) return value;
+ if(code >= 440 && code <= 459) return parseInt(value);
+ if(code >= 460 && code <= 469) return parseFloat(value);
+ if(code >= 470 && code <= 481) return value;
+ if(code === 999) return value;
+ if(code >= 1000 && code <= 1009) return value;
+ if(code >= 1010 && code <= 1059) return parseFloat(value);
+ if(code >= 1060 && code <= 1071) return parseInt(value);
+
+ console.log('WARNING: Group code does not have a defined type: %j', { code: code, value: value });
+ return value;
+}
+
+/**
+ * Parse a boolean according to a 1 or 0 value
+ * @param str
+ * @returns {boolean}
+ */
+function parseBoolean(str) {
+ if(str === '0') return false;
+ if(str === '1') return true;
+ throw TypeError('String \'' + str + '\' cannot be cast to Boolean type');
+}
+
+
+//fry comment out var log = require('loglevel');
+
+//log.setLevel('trace');
+//log.setLevel('debug');
+//log.setLevel('info');
+//log.setLevel('warn');
+//fry comment out log.setLevel('error');
+//log.setLevel('silent');
+
+
+function DxfParser(stream) {}
+
+DxfParser.prototype.parse = function(source, done) {
+ throw new Error("read() not implemented. Use readSync()");
+};
+
+DxfParser.prototype.parseSync = function(source) {
+ if(typeof(source) === 'string') {
+ return this._parse(source);
+ }else {
+ console.error('Cannot read dxf source of type `' + typeof(source));
+ return null;
+ }
+};
+
+DxfParser.prototype.parseStream = function(stream, done) {
+
+ var dxfString = "";
+ var self = this;
+
+ stream.on('data', onData);
+ stream.on('end', onEnd);
+ stream.on('error', onError);
+
+ function onData(chunk) {
+ dxfString += chunk;
+ }
+
+ function onEnd() {
+ try {
+ var dxf = self._parse(dxfString);
+ }catch(err) {
+ return done(err);
+ }
+ done(null, dxf);
+ }
+
+ function onError(err) {
+ done(err);
+ }
+};
+
+DxfParser.prototype._parse = function(dxfString) {
+ var scanner, curr, dxf = {}, lastHandle = 0;
+ var dxfLinesArray = dxfString.split(/\r\n|\r|\n/g);
+
+ scanner = new DxfArrayScanner(dxfLinesArray);
+ if(!scanner.hasNext()) throw Error('Empty file');
+
+ var parseAll = function() {
+ curr = scanner.next();
+ while(!scanner.isEOF()) {
+ if(curr.code === 0 && curr.value === 'SECTION') {
+ curr = scanner.next();
+
+ // Be sure we are reading a section code
+ if (curr.code !== 2) {
+ console.error('Unexpected code %s after 0:SECTION', debugCode(curr));
+ curr = scanner.next();
+ continue;
+ }
+
+ if (curr.value === 'HEADER') {
+ log.debug('> HEADER');
+ dxf.header = parseHeader();
+ log.debug('<');
+ } else if (curr.value === 'BLOCKS') {
+ log.debug('> BLOCKS');
+ dxf.blocks = parseBlocks();
+ log.debug('<');
+ } else if(curr.value === 'ENTITIES') {
+ log.debug('> ENTITIES');
+ dxf.entities = parseEntities(false);
+ log.debug('<');
+ } else if(curr.value === 'TABLES') {
+ log.debug('> TABLES');
+ dxf.tables = parseTables();
+ log.debug('<');
+ } else if(curr.value === 'EOF') {
+ log.debug('EOF');
+ } else {
+ log.warn('Skipping section \'%s\'', curr.value);
+ }
+ } else {
+ curr = scanner.next();
+ }
+ // If is a new section
+ }
+ };
+
+ var groupIs = function(code, value) {
+ return curr.code === code && curr.value === value;
+ };
+
+ /**
+ *
+ * @return {object} header
+ */
+ var parseHeader = function() {
+ // interesting variables:
+ // $ACADVER, $VIEWDIR, $VIEWSIZE, $VIEWCTR, $TDCREATE, $TDUPDATE
+ // http://www.autodesk.com/techpubs/autocad/acadr14/dxf/header_section_al_u05_c.htm
+ // Also see VPORT table entries
+ var currVarName = null, currVarValue = null;
+ var header = {};
+ // loop through header variables
+ curr = scanner.next();
+
+ while(true) {
+ if(groupIs(0, 'ENDSEC')) {
+ if(currVarName) header[currVarName] = currVarValue;
+ break;
+ } else if(curr.code === 9) {
+ if(currVarName) header[currVarName] = currVarValue;
+ currVarName = curr.value;
+ // Filter here for particular variables we are interested in
+ } else {
+ if(curr.code === 10) {
+ currVarValue = { x: curr.value };
+ } else if(curr.code === 20) {
+ currVarValue.y = curr.value;
+ } else if(curr.code === 30) {
+ currVarValue.z = curr.value;
+ } else {
+ currVarValue = curr.value;
+ }
+ }
+ curr = scanner.next();
+ }
+ // console.log(util.inspect(header, { colors: true, depth: null }));
+ curr = scanner.next(); // swallow up ENDSEC
+ return header;
+ };
+
+
+ /**
+ *
+ */
+ var parseBlocks = function() {
+ var blocks = {}, block;
+
+ curr = scanner.next();
+
+ while(curr.value !== 'EOF') {
+ if(groupIs(0, 'ENDSEC')) {
+ break;
+ }
+
+ if(groupIs(0, 'BLOCK')) {
+ log.debug('block {');
+ block = parseBlock();
+ log.debug('}');
+ ensureHandle(block);
+ if(!block.name)
+ log.error('block with handle "' + block.handle + '" is missing a name.');
+ else
+ blocks[block.name] = block;
+ } else {
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ }
+ }
+ return blocks;
+ };
+
+ var parseBlock = function() {
+ var block = {};
+ curr = scanner.next();
+
+ while(curr.value !== 'EOF') {
+ switch(curr.code) {
+ case 1:
+ block.xrefPath = curr.value;
+ curr = scanner.next();
+ break;
+ case 2:
+ block.name = curr.value;
+ curr = scanner.next();
+ break;
+ case 3:
+ block.name2 = curr.value;
+ curr = scanner.next();
+ break;
+ case 5:
+ block.handle = curr.value;
+ curr = scanner.next();
+ break;
+ case 8:
+ block.layer = curr.value;
+ curr = scanner.next();
+ break;
+ case 10:
+ block.position = parsePoint();
+ break;
+ case 67:
+ block.paperSpace = (curr.value && curr.value == 1) ? true : false;
+ curr = scanner.next();
+ break;
+ case 70:
+ if (curr.value != 0) {
+ //if(curr.value & BLOCK_ANONYMOUS_FLAG) console.log(' Anonymous block');
+ //if(curr.value & BLOCK_NON_CONSTANT_FLAG) console.log(' Non-constant attributes');
+ //if(curr.value & BLOCK_XREF_FLAG) console.log(' Is xref');
+ //if(curr.value & BLOCK_XREF_OVERLAY_FLAG) console.log(' Is xref overlay');
+ //if(curr.value & BLOCK_EXTERNALLY_DEPENDENT_FLAG) console.log(' Is externally dependent');
+ //if(curr.value & BLOCK_RESOLVED_OR_DEPENDENT_FLAG) console.log(' Is resolved xref or dependent of an xref');
+ //if(curr.value & BLOCK_REFERENCED_XREF) console.log(' This definition is a referenced xref');
+ block.type = curr.value;
+ }
+ curr = scanner.next();
+ break;
+ case 100:
+ // ignore class markers
+ curr = scanner.next();
+ break;
+ case 330:
+ block.ownerHandle = curr.value;
+ curr = scanner.next();
+ break;
+ case 0:
+ if(curr.value == 'ENDBLK')
+ break;
+ block.entities = parseEntities(true);
+ break;
+ default:
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ }
+
+ if(groupIs(0, 'ENDBLK')) {
+ curr = scanner.next();
+ break;
+ }
+ }
+ return block;
+ };
+
+ /**
+ * parseTables
+ * @return {Object} Object representing tables
+ */
+ var parseTables = function() {
+ var tables = {};
+ curr = scanner.next();
+ while(curr.value !== 'EOF') {
+ if(groupIs(0, 'ENDSEC'))
+ break;
+
+ if(groupIs(0, 'TABLE')) {
+ curr = scanner.next();
+
+ var tableDefinition = tableDefinitions[curr.value];
+ if(tableDefinition) {
+ log.debug(curr.value + ' Table {');
+ tables[tableDefinitions[curr.value].tableName] = parseTable();
+ log.debug('}');
+ } else {
+ log.debug('Unhandled Table ' + curr.value);
+ }
+ } else {
+ // else ignored
+ curr = scanner.next();
+ }
+ }
+
+ curr = scanner.next();
+ return tables;
+ };
+
+ const END_OF_TABLE_VALUE = 'ENDTAB';
+
+ var parseTable = function() {
+ var tableDefinition = tableDefinitions[curr.value],
+ table = {},
+ expectedCount = 0,
+ actualCount;
+
+ curr = scanner.next();
+ while(!groupIs(0, END_OF_TABLE_VALUE)) {
+
+ switch(curr.code) {
+ case 5:
+ table.handle = curr.value;
+ curr = scanner.next();
+ break;
+ case 330:
+ table.ownerHandle = curr.value;
+ curr = scanner.next();
+ break;
+ case 100:
+ if(curr.value === 'AcDbSymbolTable') {
+ // ignore
+ curr = scanner.next();
+ }else{
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ }
+ break;
+ case 70:
+ expectedCount = curr.value;
+ curr = scanner.next();
+ break;
+ case 0:
+ if(curr.value === tableDefinition.dxfSymbolName) {
+ table[tableDefinition.tableRecordsProperty] = tableDefinition.parseTableRecords();
+ } else {
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ }
+ break;
+ default:
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ }
+ }
+ var tableRecords = table[tableDefinition.tableRecordsProperty];
+ if(tableRecords) {
+ if(tableRecords.constructor === Array){
+ actualCount = tableRecords.length;
+ } else if(typeof(tableRecords) === 'object') {
+ actualCount = Object.keys(tableRecords).length;
+ }
+ if(expectedCount !== actualCount) log.warn('Parsed ' + actualCount + ' ' + tableDefinition.dxfSymbolName + '\'s but expected ' + expectedCount);
+ }
+ curr = scanner.next();
+ return table;
+ };
+
+ var parseViewPortRecords = function() {
+ var viewPorts = [], // Multiple table entries may have the same name indicating a multiple viewport configuration
+ viewPort = {};
+
+ log.debug('ViewPort {');
+ curr = scanner.next();
+ while(!groupIs(0, END_OF_TABLE_VALUE)) {
+
+ switch(curr.code) {
+ case 2: // layer name
+ viewPort.name = curr.value;
+ curr = scanner.next();
+ break;
+ case 10:
+ viewPort.lowerLeftCorner = parsePoint();
+ break;
+ case 11:
+ viewPort.upperRightCorner = parsePoint();
+ break;
+ case 12:
+ viewPort.center = parsePoint();
+ break;
+ case 13:
+ viewPort.snapBasePoint = parsePoint();
+ break;
+ case 14:
+ viewPort.snapSpacing = parsePoint();
+ break;
+ case 15:
+ viewPort.gridSpacing = parsePoint();
+ break;
+ case 16:
+ viewPort.viewDirectionFromTarget = parsePoint();
+ break;
+ case 17:
+ viewPort.viewTarget = parsePoint();
+ break;
+ case 42:
+ viewPort.lensLength = curr.value;
+ curr = scanner.next();
+ break;
+ case 43:
+ viewPort.frontClippingPlane = curr.value;
+ curr = scanner.next();
+ break;
+ case 44:
+ viewPort.backClippingPlane = curr.value;
+ curr = scanner.next();
+ break;
+ case 45:
+ viewPort.viewHeight = curr.value;
+ curr = scanner.next();
+ break;
+ case 50:
+ viewPort.snapRotationAngle = curr.value;
+ curr = scanner.next();
+ break;
+ case 51:
+ viewPort.viewTwistAngle = curr.value;
+ curr = scanner.next();
+ break;
+ case 79:
+ viewPort.orthographicType = curr.value;
+ curr = scanner.next();
+ break;
+ case 110:
+ viewPort.ucsOrigin = parsePoint();
+ break;
+ case 111:
+ viewPort.ucsXAxis = parsePoint();
+ break;
+ case 112:
+ viewPort.ucsYAxis = parsePoint();
+ break;
+ case 110:
+ viewPort.ucsOrigin = parsePoint();
+ break;
+ case 281:
+ viewPort.renderMode = curr.value;
+ curr = scanner.next();
+ break;
+ case 281:
+ // 0 is one distant light, 1 is two distant lights
+ viewPort.defaultLightingType = curr.value;
+ curr = scanner.next();
+ break;
+ case 292:
+ viewPort.defaultLightingOn = curr.value;
+ curr = scanner.next();
+ break;
+ case 330:
+ viewPort.ownerHandle = curr.value;
+ curr = scanner.next();
+ break;
+ case 63:
+ case 421:
+ case 431:
+ viewPort.ambientColor = curr.value;
+ curr = scanner.next();
+ break;
+ case 0:
+ // New ViewPort
+ if(curr.value === 'VPORT') {
+ log.debug('}');
+ viewPorts.push(viewPort);
+ log.debug('ViewPort {');
+ viewPort = {};
+ curr = scanner.next();
+ }
+ break;
+ default:
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ break;
+ }
+ }
+ // Note: do not call scanner.next() here,
+ // parseTable() needs the current group
+ log.debug('}');
+ viewPorts.push(viewPort);
+
+ return viewPorts;
+ };
+
+ var parseLineTypes = function() {
+ var ltypes = {},
+ ltypeName,
+ ltype = {},
+ length;
+
+ log.debug('LType {');
+ curr = scanner.next();
+ while(!groupIs(0, 'ENDTAB')) {
+
+ switch(curr.code) {
+ case 2:
+ ltype.name = curr.value;
+ ltypeName = curr.value;
+ curr = scanner.next();
+ break;
+ case 3:
+ ltype.description = curr.value;
+ curr = scanner.next();
+ break;
+ case 73: // Number of elements for this line type (dots, dashes, spaces);
+ length = curr.value;
+ if(length > 0) ltype.pattern = [];
+ curr = scanner.next();
+ break;
+ case 40: // total pattern length
+ ltype.patternLength = curr.value;
+ curr = scanner.next();
+ break;
+ case 49:
+ ltype.pattern.push(curr.value);
+ curr = scanner.next();
+ break;
+ case 0:
+ log.debug('}');
+ if(length > 0 && length !== ltype.pattern.length) log.warn('lengths do not match on LTYPE pattern');
+ ltypes[ltypeName] = ltype;
+ ltype = {};
+ log.debug('LType {');
+ curr = scanner.next();
+ break;
+ default:
+ curr = scanner.next();
+ }
+ }
+
+ log.debug('}');
+ ltypes[ltypeName] = ltype;
+ return ltypes;
+ };
+
+ var parseLayers = function() {
+ var layers = {},
+ layerName,
+ layer = {};
+
+ log.debug('Layer {');
+ curr = scanner.next();
+ while(!groupIs(0, 'ENDTAB')) {
+
+ switch(curr.code) {
+ case 2: // layer name
+ layer.name = curr.value;
+ layerName = curr.value;
+ curr = scanner.next();
+ break;
+ case 62: // color, visibility
+ layer.visible = curr.value <= 0;
+ // TODO 0 and 256 are BYBLOCK and BYLAYER respectively. Need to handle these values for layers?.
+ layer.color = getAcadColor(Math.abs(curr.value));
+ curr = scanner.next();
+ break;
+ case 0:
+ // New Layer
+ if(curr.value === 'LAYER') {
+ log.debug('}');
+ layers[layerName] = layer;
+ log.debug('Layer {');
+ layer = {};
+ layerName = undefined;
+ curr = scanner.next();
+ }
+ break;
+ default:
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ break;
+ }
+ }
+ // Note: do not call scanner.next() here,
+ // parseLayerTable() needs the current group
+ log.debug('}');
+ layers[layerName] = layer;
+
+ return layers;
+ };
+
+ var tableDefinitions = {
+ VPORT: {
+ tableRecordsProperty: 'viewPorts',
+ tableName: 'viewPort',
+ dxfSymbolName: 'VPORT',
+ parseTableRecords: parseViewPortRecords
+ },
+ LTYPE: {
+ tableRecordsProperty: 'lineTypes',
+ tableName: 'lineType',
+ dxfSymbolName: 'LTYPE',
+ parseTableRecords: parseLineTypes
+ },
+ LAYER: {
+ tableRecordsProperty: 'layers',
+ tableName: 'layer',
+ dxfSymbolName: 'LAYER',
+ parseTableRecords: parseLayers
+ }
+ };
+
+ /**
+ * Is called after the parser first reads the 0:ENTITIES group. The scanner
+ * should be on the start of the first entity already.
+ * @return {Array} the resulting entities
+ */
+ var parseEntities = function(forBlock) {
+ var entities = [];
+
+ var endingOnValue = forBlock ? 'ENDBLK' : 'ENDSEC';
+
+ if (!forBlock) {
+ curr = scanner.next();
+ }
+ while(true) {
+
+ if(curr.code === 0) {
+ if(curr.value === endingOnValue) {
+ break;
+ }
+
+ var entity;
+ // Supported entities here
+ if(curr.value === 'LWPOLYLINE') {
+ log.debug('LWPOLYLINE {');
+ entity = parseLWPOLYLINE();
+ log.debug('}')
+ } else if(curr.value === 'POLYLINE') {
+ log.debug('POLYLINE {');
+ entity = parsePOLYLINE();
+ log.debug('}');
+ } else if(curr.value === 'LINE') {
+ log.debug('LINE {');
+ entity = parseLINE();
+ log.debug('}');
+ } else if(curr.value === 'CIRCLE') {
+ log.debug('CIRCLE {');
+ entity = parseCIRCLE();
+ log.debug('}');
+ } else if(curr.value === 'ARC') {
+ log.debug('ARC {');
+ // similar properties to circle?
+ entity = parseCIRCLE();
+ log.debug('}')
+ } else if(curr.value === 'TEXT') {
+ log.debug('TEXT {');
+ entity = parseTEXT();
+ log.debug('}')
+ } else if(curr.value === 'DIMENSION') {
+ log.debug('DIMENSION {');
+ entity = parseDIMENSION();
+ log.debug('}')
+ } else if(curr.value === 'SOLID') {
+ log.debug('SOLID {');
+ entity = parseSOLID();
+ log.debug('}')
+ } else if(curr.value === 'POINT') {
+ log.debug('POINT {');
+ entity = parsePOINT();
+ log.debug('}')
+ } else if(curr.value === 'MTEXT') {
+ log.debug('MTEXT {');
+ entity = parseMTEXT();
+ log.debug('}')
+ } else if(curr.value === 'ATTDEF') {
+ log.debug('ATTDEF {');
+ entity = parseATTDEF();
+ log.debug('}')
+ } else {
+ log.warn('Unhandled entity ' + curr.value);
+ curr = scanner.next();
+ continue;
+ }
+ ensureHandle(entity);
+ entities.push(entity);
+ } else {
+ // ignored lines from unsupported entity
+ curr = scanner.next();
+ }
+ }
+ // console.log(util.inspect(entities, { colors: true, depth: null }));
+ if(endingOnValue == 'ENDSEC') curr = scanner.next(); // swallow up ENDSEC, but not ENDBLK
+ return entities;
+ };
+
+ /**
+ *
+ * @param entity
+ */
+ var checkCommonEntityProperties = function(entity) {
+ switch(curr.code) {
+ case 0:
+ entity.type = curr.value;
+ curr = scanner.next();
+ break;
+ case 5:
+ entity.handle = curr.value;
+ curr = scanner.next();
+ break;
+ case 6:
+ entity.lineType = curr.value;
+ curr = scanner.next();
+ break;
+ case 8: // Layer name
+ entity.layer = curr.value;
+ curr = scanner.next();
+ break;
+ case 48:
+ entity.lineTypeScale = curr.value;
+ curr = scanner.next();
+ break;
+ case 60:
+ entity.visible = curr.value === 0;
+ curr = scanner.next();
+ break;
+ case 62: // Acad Index Color. 0 inherits ByBlock. 256 inherits ByLayer. Default is bylayer
+ entity.colorIndex = curr.value;
+ entity.color = getAcadColor(Math.abs(curr.value));
+ curr = scanner.next();
+ break;
+ case 67:
+ entity.inPaperSpace = curr.value !== 0;
+ curr = scanner.next();
+ break;
+ case 330:
+ entity.ownerHandle = curr.value;
+ curr = scanner.next();
+ break;
+ case 347:
+ entity.materialObjectHandle = curr.value;
+ curr = scanner.next();
+ break;
+ case 370:
+ // This is technically an enum. Not sure where -2 comes from.
+ //From https://www.woutware.com/Forum/Topic/955/lineweight?returnUrl=%2FForum%2FUserPosts%3FuserId%3D478262319
+ // An integer representing 100th of mm, must be one of the following values:
+ // 0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211.
+ entity.lineweight = curr.value;
+ curr = scanner.next();
+ break;
+ case 420: // TrueColor Color
+ entity.color = curr.value;
+ curr = scanner.next();
+ break;
+ case 100:
+ //ignore
+ curr = scanner.next();
+ break;
+ default:
+ logUnhandledGroup(curr);
+ curr = scanner.next();
+ break;
+ }
+ };
+
+
+ var parseVertex = function() {
+ var entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10: // X
+ entity.x = curr.value;
+ curr = scanner.next();
+ break;
+ case 20: // Y
+ entity.y = curr.value;
+ curr = scanner.next();
+ break;
+ case 30: // Z
+ entity.z = curr.value;
+ curr = scanner.next();
+ break;
+ case 40: // start width
+ case 41: // end width
+ case 42: // bulge
+ curr = scanner.next();
+ break;
+ case 70: // flags
+ entity.curveFittingVertex = (curr.value & 1) !== 0;
+ entity.curveFitTangent = (curr.value & 2) !== 0;
+ entity.splineVertex = (curr.value & 8) !== 0;
+ entity.splineControlPoint = (curr.value & 16) !== 0;
+ entity.threeDPolylineVertex = (curr.value & 32) !== 0;
+ entity.threeDPolylineMesh = (curr.value & 64) !== 0;
+ entity.polyfaceMeshVertex = (curr.value & 128) !== 0;
+ curr = scanner.next();
+ break;
+ case 50: // curve fit tangent direction
+ case 71: // polyface mesh vertex index
+ case 72: // polyface mesh vertex index
+ case 73: // polyface mesh vertex index
+ case 74: // polyface mesh vertex index
+ curr = scanner.next();
+ break;
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ var parseSeqEnd = function() {
+ var entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr != 'EOF') {
+ if (curr.code == 0) break;
+ checkCommonEntityProperties(entity);
+ }
+
+ return entity;
+ };
+
+ /**
+ * Parses a 2D or 3D point, returning it as an object with x, y, and
+ * (sometimes) z property if it is 3D. It is assumed the current group
+ * is x of the point being read in, and scanner.next() will return the
+ * y. The parser will determine if there is a z point automatically.
+ * @return {Object} The 2D or 3D point as an object with x, y[, z]
+ */
+ var parsePoint = function() {
+ var point = {},
+ code = curr.code;
+
+ point.x = curr.value;
+
+ code += 10;
+ curr = scanner.next();
+ if(curr.code != code)
+ throw new Error('Expected code for point value to be ' + code +
+ ' but got ' + curr.code + '.');
+ point.y = curr.value;
+
+ code += 10;
+ curr = scanner.next();
+ if(curr.code != code)
+ return point;
+ point.z = curr.value;
+
+ curr = scanner.next(); // advance the scanner before returning
+ return point;
+ };
+
+ var parseLWPolylineVertices = function(n) {
+ if(!n || n <= 0) throw Error('n must be greater than 0 verticies');
+ var vertices = [], i;
+ var vertexIsStarted = false;
+ var vertexIsFinished = false;
+
+ for(i = 0; i < n; i++) {
+ var vertex = {};
+ while(curr !== 'EOF') {
+ if(curr.code === 0 || vertexIsFinished) break;
+
+ switch(curr.code) {
+ case 10: // X
+ if(vertexIsStarted) {
+ vertexIsFinished = true;
+ continue;
+ }
+ vertex.x = curr.value;
+ vertexIsStarted = true;
+ break;
+ case 20: // Y
+ vertex.y = curr.value;
+ break;
+ case 30: // Z
+ vertex.z = curr.value;
+ break;
+ case 40: // start width
+ vertex.startWidth = curr.value;
+ break;
+ case 41: // end width
+ vertex.endWidth = curr.value;
+ break;
+ case 42: // bulge
+ if(curr.value != 0) vertex.bulge = curr.value;
+ break;
+ default:
+ //todo: mark unhandled somehow?
+ curr = scanner.next();
+ continue;
+ }
+ curr = scanner.next();
+ }
+ // See https://groups.google.com/forum/#!topic/comp.cad.autocad/9gn8s5O_w6E
+ vertices.push(vertex);
+ vertexIsStarted = false;
+ vertexIsFinished = false;
+ }
+ return vertices;
+ };
+
+ var parsePolylineVertices = function() {
+ var vertices = [];
+ while (curr !== 'EOF') {
+ if (curr.code === 0) {
+ if (curr.value === 'VERTEX') {
+ vertices.push(parseVertex());
+ } else if (curr.value === 'SEQEND') {
+ parseSeqEnd();
+ break;
+ }
+ }
+ }
+ return vertices;
+ };
+
+ var parseMTEXT = function() {
+ var entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 1:
+ entity.text = curr.value;
+ curr = scanner.next();
+ break;
+ case 3:
+ entity.text += curr.value;
+ curr = scanner.next();
+ break;
+ case 10:
+ entity.position = parsePoint();
+ break;
+ case 40:
+ entity.height = curr.value;
+ curr = scanner.next();
+ break;
+ case 41:
+ entity.width = curr.value;
+ curr = scanner.next();
+ break;
+ case 71:
+ entity.attachmentPoint = curr.value;
+ curr = scanner.next();
+ break;
+ case 72:
+ entity.drawingDirection = curr.value;
+ curr = scanner.next();
+ break;
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ var parseATTDEF = function() {
+ var entity = {
+ type: curr.value,
+ scale: 1,
+ textStyle: 'STANDARD'
+ };
+ curr = scanner.next();
+ while (curr !== 'EOF') {
+ if (curr.code === 0) {
+ break;
+ }
+ switch(curr.code) {
+ case 1:
+ entity.text = curr.value;
+ curr = scanner.next();
+ break;
+ case 2:
+ entity.tag = curr.value;
+ curr = scanner.next();
+ break;
+ case 3:
+ entity.prompt = curr.value;
+ curr = scanner.next();
+ break;
+ case 7:
+ entity.textStyle = curr.value;
+ curr = scanner.next();
+ break;
+ case 10:
+ entity.x = curr.value;
+ curr = scanner.next();
+ break;
+ case 20:
+ entity.y = curr.value;
+ curr = scanner.next();
+ break;
+ case 30:
+ entity.z = curr.value;
+ curr = scanner.next();
+ break;
+ case 39:
+ entity.thickness = curr.value;
+ curr = scanner.next();
+ break;
+ case 40:
+ entity.textHeight = curr.value;
+ curr = scanner.next();
+ break;
+ case 41:
+ entity.scale = curr.value;
+ curr = scanner.next();
+ break;
+ case 50:
+ entity.rotation = curr.value;
+ curr = scanner.next();
+ break;
+ case 51:
+ entity.obliqueAngle = curr.value;
+ curr = scanner.next();
+ break;
+ case 70:
+ entity.invisible = !!(curr.value & 0x01);
+ entity.constant = !!(curr.value & 0x02);
+ entity.verificationRequired = !!(curr.value & 0x04);
+ entity.preset = !!(curr.value & 0x08);
+ curr = scanner.next();
+ break;
+ case 71:
+ entity.backwards = !!(curr.value & 0x02);
+ entity.mirrored = !!(curr.value & 0x04);
+ curr = scanner.next();
+ break;
+ case 72:
+ // TODO: enum values?
+ entity.horizontalJustification = curr.value;
+ curr = scanner.next();
+ break;
+ case 73:
+ entity.fieldLength = curr.value;
+ curr = scanner.next();
+ break;
+ case 74:
+ // TODO: enum values?
+ entity.verticalJustification = curr.value;
+ curr = scanner.next();
+ break;
+ case 100:
+ // subclass
+ curr = scanner.next();
+ break;
+ case 210:
+ entity.extrusionDirectionX = curr.value;
+ curr = scanner.next();
+ break;
+ case 220:
+ entity.extrusionDirectionY = curr.value;
+ curr = scanner.next();
+ break;
+ case 230:
+ entity.extrusionDirectionZ = curr.value;
+ curr = scanner.next();
+ break;
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+
+ return entity;
+ };
+
+ /**
+ * Called when the parser reads the beginning of a new entity,
+ * 0:LWPOLYLINE. Scanner.next() will return the first attribute of the
+ * entity.
+ * @return {Object} the entity parsed
+ */
+ var parseLWPOLYLINE = function() {
+ var entity = { type: curr.value, vertices: [] },
+ numberOfVertices = 0;
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 38:
+ entity.elevation = curr.value;
+ curr = scanner.next();
+ break;
+ case 39:
+ entity.depth = curr.value;
+ curr = scanner.next();
+ break;
+ case 70: // 1 = Closed shape, 128 = plinegen?, 0 = default
+ entity.shape = (curr.value === 1);
+ curr = scanner.next();
+ break;
+ case 90:
+ numberOfVertices = curr.value;
+ curr = scanner.next();
+ break;
+ case 10: // X coordinate of point
+ entity.vertices = parseLWPolylineVertices(numberOfVertices);
+ break;
+ case 43:
+ if(curr.value !== 0) entity.width = curr.value;
+ curr = scanner.next();
+ break;
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ /**
+ * Called when the parser reads the beginning of a new entity,
+ * 0:POLYLINE. Scanner.next() will return the first attribute of the
+ * entity.
+ * @return {Object} the entity parsed
+ */
+ var parsePOLYLINE = function() {
+ var entity = { type: curr.value, vertices: [] };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10: // always 0
+ case 20: // always 0
+ case 30: // elevation
+ case 39: // thickness
+ entity.thickness = curr.value;
+ curr = scanner.next();
+ break;
+ case 40: // start width
+ case 41: // end width
+ curr = scanner.next();
+ break;
+ case 70:
+ entity.shape = (curr.value & 1) !== 0;
+ entity.includesCurveFitVertices = (curr.value & 2) !== 0;
+ entity.includesSplineFitVertices = (curr.value & 4) !== 0;
+ entity.is3dPolyline = (curr.value & 8) !== 0;
+ entity.is3dPolygonMesh = (curr.value & 16) !== 0;
+ entity.is3dPolygonMeshClosed = (curr.value & 32) !== 0; // 32 = The polygon mesh is closed in the N direction
+ entity.isPolyfaceMesh = (curr.value & 64) !== 0;
+ entity.hasContinuousLinetypePattern = (curr.value & 128) !== 0;
+ curr = scanner.next();
+ break;
+ case 71: // Polygon mesh M vertex count
+ case 72: // Polygon mesh N vertex count
+ case 73: // Smooth surface M density
+ case 74: // Smooth surface N density
+ case 75: // Curves and smooth surface type
+ curr = scanner.next();
+ break;
+ case 210:
+ extrusionDirection = parsePoint();
+ break;
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+
+ entity.vertices = parsePolylineVertices();
+
+ return entity;
+ };
+
+
+ /**
+ * Called when the parser reads the beginning of a new entity,
+ * 0:LINE. Scanner.next() will return the first attribute of the
+ * entity.
+ * @return {Object} the entity parsed
+ */
+ var parseLINE = function() {
+ var entity = { type: curr.value, vertices: [] };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10: // X coordinate of point
+ entity.vertices.unshift(parsePoint());
+ break;
+ case 11:
+ entity.vertices.push(parsePoint());
+ break;
+ case 210:
+ entity.extrusionDirection = parsePoint();
+ break;
+ case 100:
+ if(curr.value == 'AcDbLine') {
+ curr = scanner.next();
+ break;
+ }
+ default:
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ /**
+ * Used to parse a circle or arc entity.
+ * @return {Object} the entity parsed
+ */
+ var parseCIRCLE = function() {
+ var entity, endAngle;
+ entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10: // X coordinate of point
+ entity.center = parsePoint();
+ break;
+ case 40: // radius
+ entity.radius = curr.value;
+ curr = scanner.next();
+ break;
+ case 50: // start angle
+ entity.startAngle = Math.PI / 180 * curr.value;
+ curr = scanner.next();
+ break;
+ case 51: // end angle
+ endAngle = Math.PI / 180 * curr.value;
+ if(endAngle < entity.startAngle)
+ entity.angleLength = endAngle + 2 * Math.PI - entity.startAngle;
+ else
+ entity.angleLength = endAngle - entity.startAngle;
+ entity.endAngle = endAngle;
+ curr = scanner.next();
+ break;
+ default: // ignored attribute
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ var parseTEXT = function() {
+ var entity;
+ entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+ switch(curr.code) {
+ case 10: // X coordinate of 'first alignment point'
+ entity.startPoint = parsePoint();
+ break;
+ case 11: // X coordinate of 'second alignment point'
+ entity.endPoint = parsePoint();
+ break;
+ case 40: // Text height
+ entity.textHeight = curr.value;
+ curr = scanner.next();
+ break;
+ case 41:
+ entity.xScale = curr.value;
+ curr = scanner.next();
+ break;
+ case 1: // Text
+ entity.text = curr.value;
+ curr = scanner.next();
+ break;
+ // NOTE: 72 and 73 are meaningless without 11 (second alignment point)
+ case 72: // Horizontal alignment
+ entity.halign = curr.value;
+ curr = scanner.next();
+ break;
+ case 73: // Vertical alignment
+ entity.valign = curr.value;
+ curr = scanner.next();
+ break;
+ default: // check common entity attributes
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+ return entity;
+ };
+
+ var parseDIMENSION = function() {
+ var entity;
+ entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 2: // Referenced block name
+ entity.block = curr.value;
+ curr = scanner.next();
+ break;
+ case 10: // X coordinate of 'first alignment point'
+ entity.anchorPoint = parsePoint();
+ break;
+ case 11:
+ entity.middleOfText = parsePoint();
+ break;
+ case 71: // 5 = Middle center
+ entity.attachmentPoint = curr.value;
+ curr = scanner.next();
+ break;
+ case 42: // Actual measurement
+ entity.actualMeasurement = curr.value;
+ curr = scanner.next();
+ break;
+ case 1: // Text entered by user explicitly
+ entity.text = curr.value;
+ curr = scanner.next();
+ break;
+ case 50: // Angle of rotated, horizontal, or vertical dimensions
+ entity.angle = curr.value;
+ curr = scanner.next();
+ break;
+ default: // check common entity attributes
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+
+ return entity;
+ };
+
+ var parseSOLID = function() {
+ var entity;
+ entity = { type: curr.value };
+ entity.points = [];
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10:
+ entity.points[0] = parsePoint();
+ break;
+ case 11:
+ entity.points[1] = parsePoint();
+ break;
+ case 12:
+ entity.points[2] = parsePoint();
+ break;
+ case 13:
+ entity.points[3] = parsePoint();
+ break;
+ case 210:
+ entity.extrusionDirection = parsePoint();
+ break;
+ default: // check common entity attributes
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+
+ return entity;
+ };
+
+ var parsePOINT = function() {
+ var entity;
+ entity = { type: curr.value };
+ curr = scanner.next();
+ while(curr !== 'EOF') {
+ if(curr.code === 0) break;
+
+ switch(curr.code) {
+ case 10:
+ entity.position = parsePoint();
+ break;
+ case 39:
+ entity.thickness = curr.value;
+ curr = scanner.next();
+ break;
+ case 210:
+ entity.extrusionDirection = parsePoint();
+ break;
+ case 100:
+ if(curr.value == 'AcDbPoint') {
+ curr = scanner.next();
+ break;
+ }
+ default: // check common entity attributes
+ checkCommonEntityProperties(entity);
+ break;
+ }
+ }
+
+ return entity;
+ };
+
+ var ensureHandle = function(entity) {
+ if(!entity) throw new TypeError('entity cannot be undefined or null');
+
+ if(!entity.handle) entity.handle = lastHandle++;
+ };
+
+ parseAll();
+ return dxf;
+};
+
+function logUnhandledGroup(curr) {
+ log.debug('unhandled group ' + debugCode(curr));
+}
+
+
+function debugCode(curr) {
+ return curr.code + ':' + curr.value;
+}
+
+/**
+ * Returns the truecolor value of the given AutoCad color index value
+ * @return {Number} truecolor value as a number
+ */
+function getAcadColor(index) {
+ return AUTO_CAD_COLOR_INDEX[index];
+}
+
+const BLOCK_ANONYMOUS_FLAG = 1;
+const BLOCK_NON_CONSTANT_FLAG = 2;
+const BLOCK_XREF_FLAG = 4;
+const BLOCK_XREF_OVERLAY_FLAG = 8;
+const BLOCK_EXTERNALLY_DEPENDENT_FLAG = 16;
+const BLOCK_RESOLVED_OR_DEPENDENT_FLAG = 32;
+const BLOCK_REFERENCED_XREF = 64;
+
+//*! loglevel - v1.4.1 - https://github.com/pimterry/loglevel - (c) 2016 Tim Perry - licensed MIT */
+(function (root, definition) {
+ "use strict";
+ if (typeof define === 'function' && define.amd) {
+ define(definition);
+ } else if (typeof module === 'object' && module.exports) {
+ module.exports = definition();
+ } else {
+ root.log = definition();
+ }
+}(this, function () {
+ "use strict";
+ var noop = function() {};
+ var undefinedType = "undefined";
+
+ function realMethod(methodName) {
+ if (typeof console === undefinedType) {
+ return false; // We can't build a real method without a console to log to
+ } else if (console[methodName] !== undefined) {
+ return bindMethod(console, methodName);
+ } else if (console.log !== undefined) {
+ return bindMethod(console, 'log');
+ } else {
+ return noop;
+ }
+ }
+
+ function bindMethod(obj, methodName) {
+ var method = obj[methodName];
+ if (typeof method.bind === 'function') {
+ return method.bind(obj);
+ } else {
+ try {
+ return Function.prototype.bind.call(method, obj);
+ } catch (e) {
+ // Missing bind shim or IE8 + Modernizr, fallback to wrapping
+ return function() {
+ return Function.prototype.apply.apply(method, [obj, arguments]);
+ };
+ }
+ }
+ }
+
+ // these private functions always need `this` to be set properly
+
+ function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
+ return function () {
+ if (typeof console !== undefinedType) {
+ replaceLoggingMethods.call(this, level, loggerName);
+ this[methodName].apply(this, arguments);
+ }
+ };
+ }
+
+ function replaceLoggingMethods(level, loggerName) {
+ /*jshint validthis:true */
+ for (var i = 0; i < logMethods.length; i++) {
+ var methodName = logMethods[i];
+ this[methodName] = (i < level) ?
+ noop :
+ this.methodFactory(methodName, level, loggerName);
+ }
+ }
+
+ function defaultMethodFactory(methodName, level, loggerName) {
+ /*jshint validthis:true */
+ return realMethod(methodName) ||
+ enableLoggingWhenConsoleArrives.apply(this, arguments);
+ }
+
+ var logMethods = [
+ "trace",
+ "debug",
+ "info",
+ "warn",
+ "error"
+ ];
+
+ function Logger(name, defaultLevel, factory) {
+ var self = this;
+ var currentLevel;
+ var storageKey = "loglevel";
+ if (name) {
+ storageKey += ":" + name;
+ }
+
+ function persistLevelIfPossible(levelNum) {
+ var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
+
+ // Use localStorage if available
+ /* fry commented out to get rid of console.log message
+ try {
+ window.localStorage[storageKey] = levelName;
+ return;
+ } catch (ignore) {}
+ */
+ // Use session cookie as fallback
+ try {
+ window.document.cookie =
+ encodeURIComponent(storageKey) + "=" + levelName + ";";
+ } catch (ignore) {}
+ }
+
+ function getPersistedLevel() { //might return undefined
+ var storedLevel;
+
+ /* fry commented out to get rid of console.log error message
+ try {
+ storedLevel = window.localStorage[storageKey];
+ } catch (ignore) {}
+ */
+
+ if (typeof storedLevel === undefinedType) {
+ try {
+ var cookie = window.document.cookie;
+ var location = cookie.indexOf(
+ encodeURIComponent(storageKey) + "=");
+ if (location != -1) {
+ storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
+ }
+ } catch (ignore) {}
+ }
+
+ // If the stored level is not valid, treat it as if nothing was stored.
+ if (self.levels[storedLevel] === undefined) {
+ storedLevel = undefined;
+ }
+
+ return storedLevel;
+ }
+
+ /*
+ *
+ * Public API
+ *
+ */
+
+ self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
+ "ERROR": 4, "SILENT": 5};
+
+ self.methodFactory = factory || defaultMethodFactory;
+
+ self.getLevel = function () {
+ return currentLevel;
+ };
+
+ self.setLevel = function (level, persist) {
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
+ level = self.levels[level.toUpperCase()];
+ }
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
+ currentLevel = level;
+ if (persist !== false) { // defaults to true
+ persistLevelIfPossible(level);
+ }
+ replaceLoggingMethods.call(self, level, name);
+ if (typeof console === undefinedType && level < self.levels.SILENT) {
+ return "No console available for logging";
+ }
+ } else {
+ throw "log.setLevel() called with invalid level: " + level;
+ }
+ };
+
+ self.setDefaultLevel = function (level) {
+ if (!getPersistedLevel()) {
+ self.setLevel(level, false);
+ }
+ };
+
+ self.enableAll = function(persist) {
+ self.setLevel(self.levels.TRACE, persist);
+ };
+
+ self.disableAll = function(persist) {
+ self.setLevel(self.levels.SILENT, persist);
+ };
+
+ // Initialize with the right level
+ var initialLevel = getPersistedLevel();
+ if (initialLevel == null) {
+ initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
+ }
+ self.setLevel(initialLevel, false);
+ }
+
+ /*
+ *
+ * Package-level API
+ *
+ */
+
+ var defaultLogger = new Logger();
+
+ var _loggersByName = {};
+ defaultLogger.getLogger = function getLogger(name) {
+ if (typeof name !== "string" || name === "") {
+ throw new TypeError("You must supply a name when creating a logger.");
+ }
+
+ var logger = _loggersByName[name];
+ if (!logger) {
+ logger = _loggersByName[name] = new Logger(
+ name, defaultLogger.getLevel(), defaultLogger.methodFactory);
+ }
+ return logger;
+ };
+
+ // Grab the current global log variable in case of overwrite
+ var _log = (typeof window !== undefinedType) ? window.log : undefined;
+ defaultLogger.noConflict = function() {
+ if (typeof window !== undefinedType &&
+ window.log === defaultLogger) {
+ window.log = _log;
+ }
+
+ return defaultLogger;
+ };
+
+ return defaultLogger;
+}));
diff --git a/editor.js b/editor.js
new file mode 100644
index 00000000..b48cd12f
--- /dev/null
+++ b/editor.js
@@ -0,0 +1,1432 @@
+/**Created by Fry on 10/29/15.*/
+/* this has bugs. Conclusion: codemirror not really deignd for npm, too many plug-ins, etc.
+so load the old fashion way in index.html
+window.CodeMirror = require("codemirror") //now in index.html because this didn't work
+require("codemirror/mode/javascript/javascript")
+//require("eslint")
+//require("codemirror/addon/lint/lint.js")
+require("codemirror-lint-eslint")
+
+require("codemirror/addon/dialog/dialog.js") //maybe used by find ???
+require("codemirror/addon/search/searchcursor.js")
+require("codemirror/addon/search/search.js")
+require("codemirror/addon/edit/matchbrackets.js")
+require("codemirror/addon/fold/foldcode.js")
+require("codemirror/addon/fold/foldgutter.js")
+require("codemirror/addon/fold/brace-fold.js")
+require("codemirror/addon/fold/comment-fold.js")
+*/
+
+var myCodeMirror
+
+function Editor(){} //just a namespace of *some* internal fns
+Editor.current_file_path = null //could be "new file" or "/Users/.../foo.fs"
+
+Editor.init_editor = function(){
+ myCodeMirror = CodeMirror.fromTextArea(js_textarea,
+ {lineNumbers: true,
+ //lineWrapping: true,
+ mode: "javascript",
+ matchBrackets: true,
+ foldGutter: true,
+ //extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, works ony when on line that can be folded
+ gutters: ["CodeMirror-linenumbers", "CodeMirror-lint-markers", "CodeMirror-foldgutter"],
+ lint: true,
+ smartIndent: false, //default is true but that screws up a lot. false is suppose to
+ //indent each line to the line above it when you hit Return
+ extraKeys:{"Left": Series.ts_or_replace_sel_left,
+ "Right": Series.ts_or_replace_sel_right,
+ "Shift-Right" : Series.ts_sel_shift_right, //no non ts semantics
+ "Up": Series.ts_or_replace_sel_up,
+ "Down": Series.ts_or_replace_sel_down,
+ "Cmd-E": eval_button_action //the correct Cmd-e doesn't work
+ }
+ });
+ undo_id.onclick = function(){Editor.undo}
+ redo_id.onclick = function(){myCodeMirror.getDoc().redo()}
+ find_id.onclick = function(){CodeMirror.commands.findPersistent(myCodeMirror)}
+ replace_id.onclick = function(){CodeMirror.commands.replace(myCodeMirror)} //allows user to also replace all.
+ fold_all_id.onclick = function(){CodeMirror.commands.foldAll(myCodeMirror)}
+ unfold_all_id.onclick = function(){CodeMirror.commands.unfoldAll(myCodeMirror)}
+ select_call_id.onclick = function(){Editor.select_call()}
+ select_all_id.onclick = function(){CodeMirror.commands.selectAll(myCodeMirror); myCodeMirror.focus()}
+
+ myCodeMirror.on("mousedown",
+ function(cm, mouse_event){
+ if(mouse_event.altKey) {
+ var line_char = myCodeMirror.coordsChar({left: mouse_event.x, top: mouse_event.y})
+ myCodeMirror.getDoc().setCursor(line_char)
+ if (Editor.select_call()){
+ mouse_event.preventDefault()
+ }
+ }
+ //I didn't need this setTimeout in ChromeApps,
+ //I could just call Editor.show_identifier_info directly
+ //but in Electron when I do that, you have to click twice
+ //to get the right click help to show up.
+ //Wrapping the setTimout fixes that bug.
+ setTimeout(function() {Editor.show_identifier_info()}, 1)
+ myCodeMirror.focus()
+ })
+}
+
+//used both from JS pane Edit menu undo item AND by App builder (called from sandbox))
+Editor.undo = function(){ myCodeMirror.getDoc().undo() }
+//fold examples. How do I implement menu items for fold all and unfold all?
+//editor_html.foldCode(CodeMirror.Pos(0, 0));
+//editor_html.foldCode(CodeMirror.Pos(21, 0));
+
+//called from ui only
+Editor.index_of_path_in_file_menu = function(path){
+ for(let i in file_name_id.children){
+ let a_path = file_name_id.children[i].innerHTML
+ if (a_path == path) { return parseInt(i) }
+ }
+ return null
+}
+
+Editor.add_path_to_files_menu = function(path){
+ let existing_index = Editor.index_of_path_in_file_menu(path)
+ let new_index = 0
+ if (existing_index === null) {
+ var opt = document.createElement("OPTION")
+ var textelt = document.createTextNode(path); // Create a text node
+ opt.appendChild(textelt);
+ if (file_name_id.hasChildNodes()){
+ file_name_id.insertBefore(opt, file_name_id.firstChild)
+ }
+ else{
+ file_name_id.add(opt)
+ }
+ file_name_id.selectedIndex = new_index
+ Editor.current_file_path = path
+ let paths = persistent_get("files_menu_paths")
+ paths.unshift(path)
+ if (paths.length > 20) { paths = paths.slice(0, 20) }
+ persistent_set("files_menu_paths", paths)
+ }
+ else {
+ new_index = existing_index
+ file_name_id.selectedIndex = new_index
+ Editor.current_file_path = path
+ }
+
+}
+
+Editor.restore_files_menu_paths_and_last_file = function(){ //called by on ready
+ const paths = persistent_get("files_menu_paths")
+ var html = ""
+ for(let path of paths){
+ html += "
" + path + "
"
+ }
+ if (paths.length > 0) {
+ file_name_id.innerHTML = html
+ Editor.edit_file(paths[0])
+ }
+}
+
+Editor.get_javascript = function(use_selection=false){
+ //if use_selection is true, return it.
+ // if false, return whole buffer.
+ // if "auto", then if sel, return it, else return whole buffer.
+ var full_src = myCodeMirror.doc.getValue() //$("#js_textarea").val() //careful: js_textarea.value returns a string with an extra space on the end! A crhome bug that jquery fixes
+ if (use_selection){
+ //var textComponent = document.getElementById('js_textarea')
+ //var sel_text = all_text.substring(textComponent.selectionStart,textComponent.selectionEnd )
+ var sel_text = full_src.substring(Editor.selection_start(), Editor.selection_end())
+ if (use_selection === true) { return sel_text}
+ else if (use_selection == "auto") {
+ if (sel_text == "") { return full_src}
+ else { return sel_text }
+ }
+ //if (sel_text == ""){
+ // return all_text
+ //}
+ //else { return sel_text }
+ }
+ else { return full_src }
+}
+
+Editor.set_javascript = function(text){
+ //$("#js_textarea").val(text)
+ myCodeMirror.doc.setValue(text)
+}
+
+Editor.selection_start = function(){
+ return myCodeMirror.indexFromPos(myCodeMirror.getCursor("start"))
+}
+
+Editor.selection_column_number = function(){
+ return myCodeMirror.getCursor("start").ch
+}
+
+Editor.selection_line_number = function(){
+ return myCodeMirror.getCursor("start").line
+}
+
+Editor.line_number = function (src, pos) { //all numbers zero based. assume src linefeeds are just 1 char ie \n
+ //and make that newline char be the last char on the line, not the first char of the next line.
+ var cur_line = -1
+ var cur_col = 0
+ var line_number = 0
+ for (var i = pos; i > 0; i--) {
+ var char = src.charAt(i)
+ if (char == '\n')
+ line_number++
+ }
+ return line_number
+}
+
+Editor.selection_end = function(){
+ return myCodeMirror.indexFromPos(myCodeMirror.getCursor("end"))
+}
+
+Editor.is_selection = function(){
+ return Editor.selection_start() !== Editor.selection_end()
+}
+
+
+Editor.select_javascript = function(start, end=start){
+ //js_textarea.setSelectionRange(start, end)
+ //$('#js_textarea').focus() //scroll to make the selection visible .. Wierdly bad var refs get a squiggly red underline voer the whole var name, but not sure how this happens. But its good.
+ //$('#js_textarea').scrollTop(start); //doesnt' scroll all the way
+ var doc = myCodeMirror.getDoc()
+ var cm_start_pos = doc.posFromIndex(start)
+ var cm_end_pos = doc.posFromIndex(end)
+ doc.setSelection(cm_start_pos, cm_end_pos, {scroll:true}) //documented to force the initial char of the selection to be in view, but doesn't work
+ //important for inserting the TestSuite example for example.
+ //Codemirror doc claims the default is true, but apparently not
+ if(cm_start_pos.ch < 21){ //column less than 21, just make it move to 0
+ myCodeMirror.scrollIntoView({line: cm_start_pos.line, ch:0 })
+ }
+ else { //otherwise, give me 8 chars of "context" to the left.
+ myCodeMirror.scrollIntoView({line: cm_start_pos.line, ch: cm_start_pos.ch - 8 })
+ }
+ myCodeMirror.focus()
+}
+
+//2nd arg can be boolean or a number which is a position relative to the
+//actual editor start pos of the new_text to be inserted.
+//3rd arg (if any) is also relative to the editor start pos.
+//it defaults to the end of the new_text inserted.
+//If 3rd arg is neg, it means relative to the designated start of the selection + length of the new_text
+//so 3rd arg of -1 means one char in from the end of the new inserted text.
+//to select all of the inserted text, just make 2nd arg true.
+//to select in from the end give a 2nd arg of some int, (could be 0) and a neg number for 3rd arg.
+Editor.replace_selection = function(new_text, select_new_text=false, end_pos_of_selection_relative=null){
+ var doc = myCodeMirror.getDoc()
+ var select_arg
+ if (select_new_text === false) { doc.replaceSelection(new_text, "start")}
+ else if (select_new_text === true) { doc.replaceSelection(new_text, "around")}
+ else if (typeof(select_new_text) == "number"){
+ var editor_start_pos = Editor.selection_start()
+ var start_sel
+ if (select_new_text < 0){ //menas fron the end of the new_text
+ start_sel = editor_start_pos + new_text.length + select_new_text
+ }
+ else {
+ start_sel = editor_start_pos + select_new_text
+ }
+ var end_sel = editor_start_pos + new_text.length
+ if (typeof(end_pos_of_selection_relative) == "number"){
+ if (end_pos_of_selection_relative < 0){
+ end_sel = editor_start_pos + new_text.length + end_pos_of_selection_relative
+ }
+ else {
+ end_sel = editor_start_pos + end_pos_of_selection_relative
+ }
+ }
+ doc.replaceSelection(new_text)
+ Editor.select_javascript(start_sel, end_sel)
+ }
+ setTimeout(function(){myCodeMirror.focus()})
+}
+
+Editor.path_to_sel_map = {}
+
+Editor.store_selection_in_map = function (){
+ Editor.path_to_sel_map[Editor.current_file_path] = [Editor.selection_start(), Editor.selection_end()]
+}
+//doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)
+
+Editor.restore_selection_from_map = function(){
+ const start_end = Editor.path_to_sel_map[Editor.current_file_path]
+ if (start_end){
+ Editor.select_javascript(start_end[0], start_end[1])
+ }
+}
+
+Editor.edit_file = function(path){ //path could be "new file"
+ if(Editor.current_file_path){ //false when we first boot up.
+ Editor.store_selection_in_map()
+ if ((Editor.current_file_path != "new file") &&
+ persistent_get("save_on_eval")){
+ Editor.save_current_file()
+ }
+ }
+ const path_already_in_menu = Editor.select_file_in_file_menu(path)
+ if (!path_already_in_menu) { Editor.add_path_to_files_menu(path) }
+ var content
+ if (path == "new file"){ content = "" }
+ else { content = file_content(path) }
+ Editor.set_javascript(content)
+ Editor.current_file_path = path
+ Editor.restore_selection_from_map()
+ myCodeMirror.focus()
+}
+
+Editor.save_current_file = function(){
+ write_file(Editor.current_file_path, Editor.get_javascript())
+}
+
+Editor.save_as = function(){ //also called by onclick save
+ const title = 'save "' + Editor.current_file_path + '" as'
+ const default_path = ((Editor.current_file_path == "new file") ? dde_apps_dir : Editor.current_file_path)
+ const path = choose_save_file({title: title, defaultPath: default_path}) //sychronous! good
+ if(path) { //path will be undefined IF user canceled the dialog
+ let content = Editor.get_javascript()
+ write_file(path, content)
+ Editor.add_path_to_files_menu(path)
+ }
+}
+
+Editor.select_file_in_file_menu = function(path){
+ var the_opt_elts = file_name_id.children
+ for (var index = 0; index < the_opt_elts.length; index++){
+ var elt = the_opt_elts[index]
+ if (elt.innerText == path){
+ file_name_id.selectedIndex = index
+ return true
+ }
+ }
+ return false //no such path in file menu
+}
+
+
+//replace selected text with new text.
+Editor.insert = function(text, insertion_pos="replace_selection", select_new_text=false){ //insertion_pos defaults to the current editor selection start.
+ if (insertion_pos == null) { insertion_pos = "replace_selection" }
+ if (["replace_selection", "selection_start", "selection_end", "start", "end", "whole"].includes(insertion_pos) ||
+ (typeof(insertion_pos) == "number")) {
+ text = decode_quotes(text) //replace all ddqq with a double quote
+ //var ta = document.getElementById("js_textarea")
+ var orig_text = Editor.get_javascript()
+ var orig_cursor_start = Editor.selection_start()
+ var orig_cursor_start_object = myCodeMirror.getCursor("start")
+ let s, e
+ if ((insertion_pos == "replace_selection") || (insertion_pos == null))
+ { s = orig_cursor_start; e = Editor.selection_end() }
+ else if (insertion_pos == "selection_start"){ s = orig_cursor_start; e = s }
+ else if (insertion_pos == "selection_end") { s = Editor.selection_end(); e = s }
+ else if (insertion_pos == "start") { s = 0; e = s }
+ else if (insertion_pos == "end") { s = orig_text.length; e = s }
+ else if (insertion_pos == "whole") { s = 0; e = orig_text.length}
+ else if (typeof(insertion_pos) == "number") { s = insertion_pos; e = s }
+ //the below shouldn't happen because the real checking is done in the sandbox part of this fn.
+ else{ throw(TypeError("Editor.insert passed insertion_pos of: " + insertion_pos +
+ " but the only legal values are: 'start', 'end', 'selection_start', 'selection_end'," +
+ " an integer, 'whole' (meaning replace the whole editor content) and " +
+ " 'replace_selection' -- the default (meaning replace the selection)."))
+ }
+ var new_text = orig_text.substr(0, s) + text + orig_text.substr(e)
+ Editor.set_javascript(new_text) //$('#js_textarea').val(new_text);
+ var new_sel_end = e + text.length
+ if (insertion_pos !== undefined) {new_sel_end = orig_cursor_start + text.length} //so cursor will be semantically where it started
+ if (select_new_text){
+ Editor.select_javascript(s, s + text.length)
+ }
+ else {
+ var doc = myCodeMirror.getDoc()
+ var new_cursor_pos = doc.posFromIndex(new_sel_end)
+ myCodeMirror.setCursor(new_cursor_pos)
+ }
+ myCodeMirror.focus()
+ myCodeMirror.scrollIntoView(orig_cursor_start_object) //orig_cursor_start_object can be
+ //way off when insertion_pos == "whole", but that seems to not screw up so leave it.
+ }
+ else{
+ throw(TypeError("Editor.insert passed insertion_pos of: " + insertion_pos +
+ " but the only legal values are: " +
+ " 'start', 'end', 'selection_start', 'selection_end', an integer," +
+ " 'whole' (meaning replace the whole editor content) and " +
+ " 'replace_selection' -- the default (meaning replace the selection)."))
+ }
+}
+
+/*Editor.insert_and_hide_window = function(text){
+ Editor.insert(text)
+ rde.hide_window()
+}*/
+
+//only used in ui as of feb, 2016. no support in sandbox
+Editor.wrap_around_selection = function(prefix, suffix, if_no_selection_text){
+ prefix = decode_quotes(prefix) //replace all ddqq with a double quote
+ suffix = decode_quotes(suffix) //replace all ddqq with a double quote
+ if(if_no_selection_text == undefined){
+ if_no_selection_text = ""
+ }
+ if_no_selection_text = decode_quotes(if_no_selection_text)
+ var orig_text = Editor.get_javascript()
+ var s = Editor.selection_start()
+ var e = Editor.selection_end()
+ var sel_text = orig_text.slice(s, e)
+ if (sel_text.length == 0){
+ sel_text = if_no_selection_text
+ }
+ else if (sel_text[sel_text.length - 1] == "\n"){
+ e = e - 1 //good when inserting /* */ to comment out a whole line.
+ sel_text = sel_text.slice(0, sel_text.length - 1)
+ }
+ var new_text = orig_text.slice(0, s) + prefix + sel_text + suffix + orig_text.substr(e)
+ Editor.set_javascript(new_text) //$('#js_textarea').val(new_text);
+ var new_sel_start = s + prefix.length
+ var new_sel_end = new_sel_start + sel_text.length
+ var doc = myCodeMirror.getDoc()
+ //var new_cursor_pos = doc.posFromIndex(new_sel_end)
+ //myCodeMirror.setCursor(new_cursor_pos)
+ Editor.select_javascript(new_sel_start, new_sel_end)
+}
+
+//not as good as inside out parser code way below.
+Editor.start_and_end_of_js_call_at_pos = function(js_src, js_cursor_pos){
+ //assumes cursor is somewhere in text like "Editor.some_fn("
+ //return array of start and end pos, ie [34, 47]
+ var start = -1
+ var end = -1
+ //first look for end of "Editor.some_fn("
+ var max_last_char_pos = Math.min(js_cursor_pos + 25, js_src.length - 1)
+ for(var i = 0; i < 25; i++){ //
+ var end_pos_maybe = js_cursor_pos + i
+ if (end_pos_maybe > max_last_char_pos){
+ break;
+ }
+ var char = js_src[end_pos_maybe]
+ if (char == "("){ //good
+ end = end_pos_maybe
+ break;
+ }
+ else if (char == '\n') { //bad
+ break;
+ }
+ else if (is_alphanumeric(char) || (char == " ") || (char == ".")){
+ //allow the dot in Editor.foo". JS also allows spaces between fn name and open paren ie "dexster.foo ("
+ null //keep looping
+ }
+ else { break; }
+ }
+ if (end == -1) return null
+ //find the start of the Editor.foo call "
+ for(var i = 0; i < 25; i++){ //
+ var start_pos_maybe = js_cursor_pos - i
+ if (start_pos_maybe < 0){
+ break;
+ }
+ var char = js_src[start_pos_maybe]
+ if (js_src.indexOf("Editor.", start_pos_maybe) == start_pos_maybe) { //bingo
+ start = start_pos_maybe
+ }
+ }
+ if (start == -1) return null
+ else { return [start, end] }
+}
+
+
+//assumes that editor cursor is after end_action_name
+//returns string error message or true for success
+//ui fn
+Editor.train_for_loop_insert = function (task_name, repeat_from_action_name, repeat_through_action_name,
+ repetitions, train_task_for_loops_made){
+ var orig_start_pos = Editor.selection_start()
+ Editor.select_javascript(orig_start_pos, orig_start_pos) //collapse selection if any.
+ var orig_doc_text = Editor.get_javascript()
+ var start_loop_body = Editor.find_start_loop(orig_doc_text, orig_start_pos, repeat_from_action_name, task_name)
+ if (typeof(start_loop_body) == "string") {
+ out(start_loop_body, "red")
+ return
+ }
+ var end_loop_body = Editor.find_end_loop(orig_doc_text, orig_start_pos, repeat_through_action_name, task_name)
+ if (typeof(end_loop_body) == "string") {
+ out(end_loop_body, "red")
+ return
+ }
+ if (start_loop_body > end_loop_body){
+ out("Error: the start_action_name of: " + repeat_from_action_name +
+ " occurs after the end_action_name of: " + repeat_through_action_name + " ", "red")
+ return
+ }
+ var loop_var = String.fromCharCode("i".charCodeAt(0) + train_task_for_loops_made) //so that the 2nd loop in a task will have var j, not i
+ var for_start = " for(var " + loop_var + " = 0; " + loop_var + " < " + repetitions + "; " + loop_var + "++){\n" //indent 2 spaces because body will be indented 4.
+ var for_end = " }\n"
+ var for_body = orig_doc_text.slice(start_loop_body, end_loop_body)
+ var new_doc_text = orig_doc_text.slice(0, start_loop_body) +
+ for_start + for_body + for_end +
+ orig_doc_text.slice(end_loop_body)
+ Editor.set_javascript(new_doc_text)
+ var new_cursor_pos = orig_start_pos + for_start.length + for_end.length
+ Editor.select_javascript(new_cursor_pos, new_cursor_pos)
+}
+
+//returns int or string error message
+Editor.find_start_loop = function(orig_doc_text, orig_start_pos, repeat_from_action_name, task_name){
+ var upward_limit_string = "function " + task_name + "(" //don't search up beyond this.
+ var action_search_string = "//" + repeat_from_action_name + " "
+ var action_pos = orig_doc_text.lastIndexOf(action_search_string, orig_start_pos)
+ if (action_pos == -1) {
+ action_search_string = "//" + repeat_from_action_name + "\n"
+ action_pos = orig_doc_text.lastIndexOf(action_search_string, orig_start_pos)
+ if (action_pos == -1) {
+ return "Error: could not find action named: " + repeat_from_action_name + " in task: " + task_name + " "
+ }
+ }
+ var limit_string_pos = orig_doc_text.lastIndexOf(upward_limit_string, orig_start_pos)
+ if (limit_string_pos == -1) { return "Error: could not find task named: " + task_name }
+ else if (action_pos > limit_string_pos) { //success
+ var newline_pos = orig_doc_text.lastIndexOf("\n", action_pos) //really should always find this before begin of file
+ return newline_pos + 1
+ }
+ else {return "Error: could not find action named: " + repeat_from_action_name + "in task: " + task_name +
+ " but did find " + repeat_from_action_name + " above " + task_name + "."}
+
+}
+
+Editor.find_end_loop = function(orig_doc_text, orig_start_pos, repeat_through_action_name, task_name){
+ var upward_limit_string = "function " + task_name + "(" //don't search up beyond this.
+ var action_search_string = "//" + repeat_through_action_name + " "
+ var action_pos = orig_doc_text.lastIndexOf(action_search_string, orig_start_pos)
+ if (action_pos == -1) {
+ action_search_string = "//" + repeat_through_action_name + "\n"
+ action_pos = orig_doc_text.lastIndexOf(action_search_string, orig_start_pos)
+ if (action_pos == -1) {
+ return "Error: could not find action named: " + repeat_through_action_name + " in task: " + task_name + " "
+ }
+ }
+ var limit_string_pos = orig_doc_text.lastIndexOf(upward_limit_string, orig_start_pos)
+ if (limit_string_pos == -1) { return "Error: could not find task named: " + task_name }
+ else if (action_pos > limit_string_pos) { //success
+ var newline_pos = orig_doc_text.indexOf("\n", action_pos) //really should always find this before begin of file
+ return newline_pos + 1
+ }
+ else {return "Error: could not find action named: " + repeat_through_action_name + "in task: " + task_name +
+ " but did find " + repeat_through_action_name + " above " + task_name + "."}
+}
+//build_app and train utilties below here
+
+Editor.insert_before_fn_def = function(fn_name, code){
+ var orig_doc_text = Editor.get_javascript()
+ var cursor_pos = Editor.selection_start()
+ var fn_start_pos = Editor.find_task_start(orig_doc_text, cursor_pos, fn_name)
+ Editor.insert(code, fn_start_pos)
+}
+
+Editor.close_app_builder_temp_windows = function(){
+ var temp_wins = $('.app_builder_temp_window')
+ if ((temp_wins.length > 0) && temp_wins.jqxWindow("isOpen")){
+ temp_wins.jqxWindow('close')
+ }
+}
+Editor.run_unfinished_app_builder_window = function (task_name, opening_code, closing_code){
+ if (opening_code == undefined) { opening_code = "" }
+ if (closing_code == undefined) { closing_code = "" } //closing code is "}" for training dexter, but is much more for App Builder.
+ var orig_doc_text = Editor.get_javascript()
+ var cursor_pos = Editor.selection_start()
+ var fn_start_pos = Editor.find_task_start(orig_doc_text, cursor_pos, task_name)
+ if (typeof(fn_start_pos) == "string") { //error message
+ out("Error: " + fn_start_pos, "red")
+ }
+ else{
+ var fn_partial_source = orig_doc_text.slice(fn_start_pos, cursor_pos)
+ var temp_wins = $('.app_builder_temp_window')
+ var new_x_code = ""
+ var new_y_code = ""
+ if ((temp_wins.length > 0) && temp_wins.jqxWindow("isOpen")){
+ var old_win_pos = temp_wins.position() //temp_wins.jqxWindow("position") warning: crap jqWin position returns that last pos programmatically set NOT the pos dragged to by the user, which is what I want.
+ temp_wins.jqxWindow('close')
+ if (old_win_pos && ((old_win_pos.top != 200) || (old_win_pos.left != 200))){
+ //hack fn_partial_source to have the old_win_pos
+ new_x_code = 'x: "' + old_win_pos.left + 'px", '
+ var x_colon_pos = fn_partial_source.indexOf(" x:")//space in front of x: *might* not get some x: instances, but should get most. hward to work around
+ if(x_colon_pos != -1){
+ var x_comma_pos = fn_partial_source.indexOf(",", x_colon_pos)
+ var old_x_code = fn_partial_source.substring(x_colon_pos, x_comma_pos)
+ fn_partial_source.replace(old_x_code, new_x_code)
+ new_x_code = "" //used it already
+ }
+ new_y_code = ' y: "' + old_win_pos.top + 'px", '
+ var y_colon_pos = fn_partial_source.indexOf(" y:") //must have space in from of y: or we'll match font-family:
+ if(y_colon_pos != -1){
+ var y_comma_pos = fn_partial_source.indexOf(",", y_colon_pos)
+ var old_y_code = fn_partial_source.substring(y_colon_pos, y_comma_pos)
+ fn_partial_source.replace(old_y_code, new_y_code)
+ new_y_code = "" //used it already
+ }
+ }
+ }
+ fn_partial_source = fn_partial_source.replace("{content:", "{" + new_x_code + new_y_code + 'window_class:"app_builder_temp_window", content:')
+
+ var full_src = opening_code + fn_partial_source + closing_code +"\n" + task_name + "()"
+ eval_js_part2(full_src)
+ }
+}
+
+
+Editor.run_unfinished_task = function (task_name){
+ var orig_doc_text = Editor.get_javascript()
+ var cursor_pos = Editor.selection_start()
+ var fn_start_pos = Editor.find_task_start(orig_doc_text, cursor_pos, task_name)
+ if (typeof(fn_start_pos) == "string") { //error message
+ out("Error: " + fn_start_pos, "red")
+ }
+ else{
+ var fn_partial_source = orig_doc_text.slice(fn_start_pos, cursor_pos)
+ var full_src = "(" + fn_partial_source + "})()"
+ eval_js_part2(full_src)
+ }
+}
+
+Editor.find_task_start = function(orig_doc_text, cursor_pos, task_name){
+ //look up from cursor_pos to the beginning of the function its in.
+ var fn_begin_text = "function " + task_name + "("
+ var task_fn_pos = orig_doc_text.lastIndexOf(fn_begin_text, cursor_pos)
+ if (task_fn_pos != -1) {return task_fn_pos}
+ else { return "Could not find " + fn_begin_text + " so can't run " + task_name + "'s actions." }
+}
+
+//checks if pos is between slash_slash and newline
+Editor.in_a_comment = function(src, pos){
+ var slash_slash_pos = src.lastIndexOf("//", pos)
+ if (slash_slash_pos == -1) {return false}
+ else{
+ var return_pos = src.indexOf("\n", slash_slash_pos)
+ if ((slash_slash_pos < pos) && (return_pos > pos)) { return true }
+ else { return false }
+ }
+}
+
+//____________select_call______________
+//return true if found selection and false if doesn't.
+Editor.select_call = function(){
+ var full_src = Editor.get_javascript()
+ var cursor_pos = Editor.selection_start()
+ var start_and_end = Editor.find_call_start_end_from_end(full_src, cursor_pos)
+ if (!start_and_end){
+ start_and_end = Editor.find_call_start_end_from_start(full_src, cursor_pos)
+ }
+ if (!start_and_end){ //user clicked in middle of a call not very end and not a fn name.
+ var fwd_nearest_delim_pos = Editor.find_forward_delimiter(full_src, cursor_pos)
+ var delim_char = full_src[fwd_nearest_delim_pos]
+ if (Editor.is_close_delimiter(delim_char)){
+ start_and_end = Editor.find_call_start_end_from_end(full_src, fwd_nearest_delim_pos + 1)
+ }
+ else {
+ var bwd_nearest_delim_pos = Editor.find_backward_delimiter(full_src, cursor_pos)
+ var delim_char = full_src[bwd_nearest_delim_pos]
+ if (Editor.is_open_delimiter(delim_char)){
+ var close_delim = Editor.find_matching_delimiter(full_src, bwd_nearest_delim_pos)
+ if (close_delim == null) {return false}
+ else { start_and_end = Editor.find_call_start_end_from_end(full_src, close_delim + 1)}
+ }
+ }
+ }
+ if (start_and_end){
+ Editor.select_javascript(start_and_end[0], start_and_end[1])
+ return true
+ }
+ return false
+
+}
+
+//if right before cursor_pos is ");" or ")" then this returns the start and end pos of the call
+//otherwise retruns null
+Editor.find_call_start_end_from_end = function(full_src, cursor_pos){
+ var temp_cur = cursor_pos
+ if (Editor.find_backwards_string(full_src, cursor_pos, ";")){ //there's a semi before the cursor
+ temp_cur -= 1 //temp_cur now pointing at the semi
+ }
+ if (temp_cur > 0) {
+ temp_cur -= 1 //maybe pointing at a close delim
+ var close_delim_maybe = full_src[temp_cur]
+ if (Editor.is_close_delimiter(close_delim_maybe)){
+ temp_cur = Editor.find_matching_delimiter(full_src, temp_cur) //searches backwards
+ if (temp_cur != null){
+ var open_delim = full_src[temp_cur]
+ if (open_delim == "[") { return [temp_cur, cursor_pos]} //done selecting array
+ else if (open_delim == "(") {
+ if (temp_cur > 0){
+ var meth_name_start = Editor.find_call_start_from_open_paren(full_src, temp_cur)
+ if (meth_name_start || (meth_name_start == 0)) {
+ if (meth_name_start > 0){
+ var before_ws = Editor.backup_over_whitespace(full_src, meth_name_start - 1)
+ if (before_ws || (before_ws == 0)){
+ var new_pos_start = Editor.find_backwards_string(full_src, before_ws + 1, "new")
+ if (new_pos_start || (new_pos_start == 0)){ meth_name_start = new_pos_start}
+ }
+ }
+ return [meth_name_start, cursor_pos]
+ }
+ }
+ }
+ else if (open_delim == "{") { //maybe got a fn def
+ var close_paren_pos = Editor.find_backwards(full_src, temp_cur, ")")
+ if (close_paren_pos && (close_paren_pos > 1)){ //at least 1 char fn name
+ var open_paren_pos = Editor.find_matching_delimiter(full_src, close_paren_pos)
+ if ((open_paren_pos != null) && (open_paren_pos > 0)){
+ var last_char_before_whitespace_pos = Editor.backup_over_whitespace(full_src, open_paren_pos - 1)
+ if (last_char_before_whitespace_pos &&
+ (last_char_before_whitespace_pos > 0) &&
+ (last_char_before_whitespace_pos < open_paren_pos)){
+ var identifier_bounds = Editor.bounds_of_identifier(full_src, last_char_before_whitespace_pos)
+ if (identifier_bounds){
+ var identifier = full_src.substring(identifier_bounds[0], identifier_bounds[1])
+ if(["catch", "else if", "function", "function*", "for", "if", "switch", "while"].indexOf(identifier) != -1) { //anonymous fn, etc.
+ return [identifier_bounds[0], cursor_pos]
+ }
+ else if (identifier_bounds[0] > 0) { //named fn
+ last_char_before_whitespace_pos = Editor.backup_over_whitespace(full_src, identifier_bounds[0] - 1)
+ if (last_char_before_whitespace_pos &&
+ (last_char_before_whitespace_pos > 0) &&
+ (last_char_before_whitespace_pos < open_paren_pos)){
+ identifier_bounds = Editor.bounds_of_identifier(full_src, last_char_before_whitespace_pos)
+ if (identifier_bounds){
+ var identifier = full_src.substring(identifier_bounds[0], identifier_bounds[1])
+ if((identifier == "function") || (identifier == "function*")) { return [identifier_bounds[0], cursor_pos] } //anonymous fn
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ else { //got curely close and open, but the curly open not preceeed by clsoe paren, so maybe its a "try" or "else"
+ var last_char_before_whitespace_pos = Editor.backup_over_whitespace(full_src, temp_cur - 1)
+ if (last_char_before_whitespace_pos &&
+ (last_char_before_whitespace_pos > 0)){
+ var identifier_bounds = Editor.bounds_of_identifier(full_src, last_char_before_whitespace_pos)
+ var id = full_src.substring(identifier_bounds[0], identifier_bounds[1])
+ if (["else", "try"].indexOf(id) != -1){
+ return [identifier_bounds[0], cursor_pos]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return null
+}
+
+//cursor_pos pointing at open paren
+Editor.find_call_start_from_open_paren = function(full_src, cursor_pos){
+ var temp_cur = Editor.backup_over_whitespace(full_src, cursor_pos - 1)
+ if (temp_cur == -1) { return null } //only whitespace between open paren and doc begin
+ else {
+ var identifier_bounds = Editor.bounds_of_identifier(full_src, temp_cur)
+ if (!identifier_bounds) {return null}
+ else { return identifier_bounds[0] }
+ //fn_name_start = Editor.backup_to_whitespace(full_src, temp_cur)
+ //if (fn_name_start <= temp_cur){
+ // return fn_name_start
+ //}
+ }
+ return null
+}
+
+Editor.find_call_start_end_from_start = function(full_src, cursor_pos){
+ var identifier_bounds = Editor.bounds_of_identifier(full_src, cursor_pos)
+ if (identifier_bounds){
+ var identifier = full_src.substring(identifier_bounds[0], identifier_bounds[1])
+ if (["catch", "else if", "function", "function*", "for", "if", "switch", "while"].indexOf(identifier) != -1){
+ var open_paren_pos = Editor.find_forward_delimiter(full_src, identifier_bounds[1])
+ var delim_char = full_src[open_paren_pos]
+ if (delim_char != "("){ return null }
+ else {
+ var close_paren_pos = Editor.find_matching_delimiter(full_src, open_paren_pos)
+ if (close_paren_pos == null){ return null }
+ else {
+ var open_curley_pos = Editor.find_forward_delimiter(full_src, close_paren_pos + 1)
+ if (!open_curley_pos) { return null }
+ else{
+ var close_curley_pos = Editor.find_matching_delimiter(full_src, open_curley_pos)
+ if (close_curley_pos == null) { return null }
+ else { return [identifier_bounds[0], close_curley_pos + 1] }
+ }
+ }
+ }
+ }
+ else if (["else", "try"].indexOf(identifier) != -1){
+ var open_curley_pos = Editor.find_forward_delimiter(full_src, identifier_bounds[1])
+ if (!open_curley_pos) { return null }
+ else if (full_src[open_curley_pos] == "{"){
+ var close_curley_pos = Editor.find_matching_delimiter(full_src, open_curley_pos)
+ if (close_curley_pos == null) { return null }
+ else { return [identifier_bounds[0], close_curley_pos + 1] }
+ }
+ }
+ else if (identifier == "new"){
+ var open_paren_pos = Editor.find_forward_delimiter(full_src, identifier_bounds[1])
+ var delim_char = full_src[open_paren_pos]
+ if (delim_char != "("){ return null }
+ else {
+ var close_paren_pos = Editor.find_matching_delimiter(full_src, open_paren_pos)
+ if (close_paren_pos != null){
+ var close_paren_char = full_src[close_paren_pos]
+ if (close_paren_char == ")") {return [identifier_bounds[0], close_paren_pos + 1]}
+ }
+ }
+ }
+ }
+ var open_pos = Editor.find_forward_open_delimiter(full_src, cursor_pos)
+ if (open_pos || (open_pos == 0)){
+ var close_pos = Editor.find_forward_close_delimiter(full_src, cursor_pos)
+ if (close_pos < open_pos) { return null }
+ var close_pos = Editor.find_matching_delimiter(full_src, open_pos)
+ if (close_pos != null) {
+ var open_char = full_src[open_pos]
+ if (open_char == "[") {
+ if ((open_pos == cursor_pos) ||
+ ((open_pos - 1) == cursor_pos) ||
+ ((open_pos + 1) == cursor_pos)){
+ return [open_pos, close_pos + 1] }
+ else { return null }
+ }
+ else if(open_char == "(") {
+ temp_cur = Editor.find_call_start_from_open_paren(full_src, open_pos)
+ if (temp_cur !== null) { //beware, if fn starts on first char of file, temp_cur will be 0
+ //ALSO: if we have src function foo(a){return 2} and user clicks on
+ //the close paran, we don't want to select the whole fn def because
+ //user could be trying to get an example fn call to the fn and copy & paste
+ //it somewhere else. //however, if preceeded by "new ", we want to select that.
+ if (temp_cur > 0){
+ var ws = Editor.backup_over_whitespace(full_src, temp_cur - 1)
+ if (ws < temp_cur){ //found some whitespace
+ var new_pos_start = Editor.find_backwards_string(full_src, ws + 1, "new")
+ if ((new_pos_start == 0) || new_pos_start){ temp_cur = new_pos_start}
+ }
+ }
+ return [temp_cur, close_pos + 1]
+ }
+ }
+ }
+ }
+ return null
+}
+
+Editor.is_close_delimiter = function(char){
+ if (")]}".indexOf(char) == -1) {return false}
+ else {return true}
+}
+
+Editor.is_open_delimiter = function(char){
+ if ("([{".indexOf(char) == -1) {return false}
+ else {return true}
+}
+
+Editor.is_delimiter = function(char){
+ return Editor.is_open_delimiter(char) || Editor.is_close_delimiter(char)
+}
+
+Editor.matching_delimiter = function(char){
+ if (char == "(") {return ")"}
+ else if (char == ")") {return "("}
+
+ else if (char == "[") {return "]"}
+ else if (char == "]") {return "["}
+
+ else if (char == "{") {return "}"}
+ else if (char == "}") {return "{"}
+ else { shouldnt("Got char: " + char + " that is not a known delimiter.") }
+}
+
+
+Editor.find_forward_delimiter = function(full_src, cursor_pos=0){
+ full_src = full_src.substring(cursor_pos)
+ var match = full_src.match(/[\(|\[|\{\)\]\}]|\/\//);
+ if (match === null) {return null}
+ else if (match[0] == "//"){ //we want to exclude from matching any parens that are between // and newline as they are in a comment.
+ var new_line_pos = full_src.indexOf("\n", match.index)
+ if (new_line_pos == -1) {return null} //no newline, so no text after the // in full_src, so there can't be any parents ,etc after the //
+ else { return Editor.find_forward_delimiter(full_src, cursor_pos + new_line_pos + 1) }
+ }
+ else {
+ return cursor_pos + match.index
+ }
+}
+
+//skips over // comments
+Editor.find_backward_delimiter = function(full_src, cursor_pos){
+ full_src = full_src.substring(0, cursor_pos)
+ full_src = reverse_string(full_src)
+ var result = Editor.find_forward_delimiter(full_src, 0)
+ result = full_src.length - result - 1
+ return result
+}
+
+
+//does not bypass // comments.
+Editor.find_forward_open_delimiter = function(full_src, cursor_pos=0){
+ full_src = full_src.substring(cursor_pos)
+ var match = full_src.match(/[\(|\[|\{]/);
+ if (match === null) {return null}
+ else {
+ return cursor_pos + match.index
+ }
+}
+
+//does not bypass // comments.
+Editor.find_forward_close_delimiter = function(full_src, cursor_pos=0){
+ full_src = full_src.substring(cursor_pos)
+ var match = full_src.match(/[\)|\]|\}]/);
+ if (match === null) {return null}
+ else {
+ return cursor_pos + match.index
+ }
+}
+
+//cursor_pos is pointing at a ()[]{}. Returns the pos of the matching one or null
+Editor.find_matching_delimiter = function(full_src, cursor_pos=0){
+ var cursor_pos_delim = full_src[cursor_pos]
+ if (Editor.is_open_delimiter(cursor_pos_delim)) { return Editor.find_matching_close(full_src, cursor_pos) } //looking for ),}, or ]
+ else { return Editor.find_matching_open( full_src, cursor_pos) } //looking for (,{, or [
+}
+
+
+//expects cur_pos to point at close paren, searches backwards
+Editor.find_matching_open = function(full_src, cursor_pos=0){
+ var close_delim = full_src[cursor_pos]
+ var open_delim = Editor.matching_delimiter(close_delim)
+ var opens_needed = 0
+ for (var i = cursor_pos; i >= 0; i--){
+ var char = full_src[i]
+ if (char == close_delim) { opens_needed += 1 } //expected to hit on first iteration
+ else if (char == open_delim){
+ opens_needed -= 1
+ if (opens_needed == 0) { return i }
+ }
+ else if (char == "\n"){
+ var slash_slash_pos = Editor.backup_over_slash_slash(full_src, i - 1)
+ if (slash_slash_pos) {
+ if (slash_slash_pos == 0) {return null}
+ else {i = slash_slash_pos}
+ }
+ }
+ }
+ return null
+}
+
+//expects cur_pos to point at open paren, searches fowwards
+Editor.find_matching_close = function(full_src, cursor_pos=0){
+ var open_delim = full_src[cursor_pos]
+ var close_delim = Editor.matching_delimiter(open_delim)
+ var closes_needed = 0
+ for (var i = cursor_pos; i < full_src.length; i++){
+ var char = full_src[i]
+ if (char == open_delim) closes_needed += 1
+ else if (char == close_delim){
+ closes_needed -= 1
+ if (closes_needed == 0) { return i }
+ }
+ else if ("\"'`".includes(char)){
+ let quote_end_pos = Editor.find_forwards_matching_quote(full_src, i)
+ if (quote_end_pos != -1){
+ i = quote_end_pos //skip over literal string. note that quote_end_pos points at the
+ //quote but when we get to the top of the loop, i is incremented so
+ //the next char we process will be after the quote.
+ }
+ else {} // weird situation. For now ignore it but not a good condition.
+ }
+ else if ((char == "/") &&
+ (i < (full_src.length - 1)) &&
+ (full_src[i + 1] == "/")){
+ var newline_pos = full_src.indexOf("\n", i)
+ if (newline_pos) { i = newline_pos }
+ else return null //no chars after the // comment
+ }
+ }
+ return null
+}
+
+//returns pos of start of string_to_find or null
+//string is only looked for immedeately before cursor_pos
+Editor.find_backwards_string = function(full_src, cursor_pos, string_to_find){
+ if (string_to_find.length > cursor_pos) {return null}
+ else {
+ var start_pos_maybe = cursor_pos - string_to_find.length
+ var index = full_src.indexOf(string_to_find, start_pos_maybe)
+ if (index == start_pos_maybe) {return start_pos_maybe}
+ else { return null }
+ }
+}
+
+//finds starting pos of occurance of string_to_find that's close to, but before cursor_pos.
+//skips over // comments
+//returns -1 if can't find string_to_find
+Editor.find_backwards = function(full_src, cursor_pos, string_to_find){
+ var pos = full_src.lastIndexOf(string_to_find, cursor_pos)
+ if(Editor.in_a_comment(full_src, pos)) {
+ var slash_slash_pos = full_src.lastIndexOf("//", pos)
+ return Editor.find_backwards(full_src, slash_slash_pos, string_to_find)
+ }
+ else { return pos }
+}
+
+
+//might return -1 if none. returns pos of the quote
+Editor.find_forwards_any_kind_of_quote = function(full_src, cursor_pos=0){
+ let double_pos = full_src.indexOf('"', cursor_pos)
+ let single_pos = full_src.indexOf("'", cursor_pos)
+ let backtick_pos = full_src.indexOf('`', cursor_pos)
+ if (double_pos == -1) { double_pos = 1000000}
+ if (single_pos == -1) { single_pos = 1000000}
+ if (backtick_pos == -1) { backtick_pos = 1000000}
+ let result = Math.min(double_pos, single_pos, backtick_pos)
+ if (result == 1000000) {return -1}
+ else {return result}
+}
+
+//might return -1 if none. returns pos of the quote
+Editor.find_backwards_any_kind_of_quote = function(full_src, cursor_pos){
+ let double_pos = full_src.lastIndexOf('"', cursor_pos)
+ let single_pos = full_src.lastIndexOf("'", cursor_pos)
+ let backtick_pos = full_src.lastIndexOf('`', cursor_pos)
+ return Math.max(double_pos, single_pos, backtick_pos)
+}
+
+Editor.find_forwards_matching_quote = function(full_src, cursor_pos=0){
+ let quote_char = full_src[cursor_pos]
+ let pos = full_src.indexOf(quote_char, cursor_pos + 1)
+ return pos
+}
+
+Editor.find_backwards_matching_quote = function(full_src, cursor_pos){
+ if (cursor_pos == 0) { return -1 }
+ let quote_char = full_src[cursor_pos]
+ let pos = full_src.lastIndexOf(quote_char, cursor_pos - 1)
+ return pos
+}
+//returns the pos of the start of a comment but doesn't go beyond a newline.
+//cursor_pos is expected to be just before a newline, and if no
+//slash_slash on the line, return null
+Editor.backup_over_slash_slash = function(full_src, cursor_pos){
+ var slash_slash_pos = full_src.lastIndexOf("//", cursor_pos)
+ if (slash_slash_pos == -1) { return null } //no slash_slashes in preceeding whole doc.
+ else {
+ var newline_pos = full_src.lastIndexOf("\n", cursor_pos)
+ if (newline_pos == -1) { return slash_slash_pos } //we're on the top line, and there's a slash_slash on its end
+ else if(slash_slash_pos > newline_pos) { return slash_slash_pos } //the nearest slash-slash is indeed on the line we're looing at, so return its pos so we can back up over it.
+ else { return null } //no slash_slash in the line
+ }
+}
+
+//returns index of the first char before a whitespace group, or, if none, cursor_pos
+//in any case, returned index char will not point at whitespace,
+//and may be the last char before a whitespace group
+//if all whtespace from cursor_pos back to doc start, returns -1
+//If this fn is to backup at all, cursor_pos should point at whitespace.
+Editor.backup_over_whitespace = function(full_src, cursor_pos){
+ for (var i = cursor_pos; i >= 0; i--){
+ if( !(/\s/.test(full_src[i]))){
+ return i
+ }
+ else if (i == 0) { //we found no whitespace all the way to the begin of doc,
+ //so consider the begin of doc to be whitespace
+ return 0
+ }
+ }
+ return -1 //whitespace including cursor_pos and all the way to front of doc.
+}
+
+//cursorpos is expected to not be on whitespace, though it might be
+//when we find whitespace, return pos of first char after it.
+//if find begin of file before we find whitespace, return 0.
+//if cursorpos is whitespace, then returns cursor_pos + 1
+Editor.backup_to_whitespace = function(full_src, cursor_pos){
+ for (var i = cursor_pos; i >= 0; i--){
+ if((/\s/.test(full_src[i]))){
+ return i + 1
+ }
+ }
+ return 0 //no whitespace to front of doc.
+}
+
+//returns null if cursor pos not in a function def
+Editor.bounds_of_function_def = function(full_src, cursor_pos){
+ var function_pos = Editor.find_backwards(full_src, cursor_pos, "function")
+ if (function_pos == -1){ return null }
+ var end_of_params_pos = full_src.indexOf("){", function_pos)
+ if (end_of_params_pos == -1){ return null }
+ var function_end_pos = Editor.find_matching_delimiter(full_src, end_of_params_pos + 1)
+ if (function_end_pos == null){ return null }
+ else return [function_pos, function_end_pos]
+}
+
+//returns null if cursor_pos not in a function
+Editor.function_params_and_locals = function(full_src, cursor_pos){
+ var bounds = Editor.bounds_of_function_def(full_src, cursor_pos)
+ if (!bounds) { return null } //not in a function
+ var params_start_pos = full_src.indexOf("(", bounds[0])
+ if (params_start_pos == -1) { return null }
+ else {
+ var fn_name = full_src.substring(bounds[0] + 9, params_start_pos)
+ fn_name.trim()
+ params_start_pos += 1 //skip over open paren
+ }
+ var params_end_pos = full_src.indexOf("){", params_start_pos)
+ if (params_end_pos == -1) { return null }
+ var params_full_string = full_src.substring(params_start_pos, params_end_pos) //excludes parens
+ var params_and_defaults_array = params_full_string.split(",")
+ var param_names = []
+ for(var param_and_default of params_and_defaults_array){
+ param_and_default = param_and_default.trim()
+ if (param_and_default.startsWith("{")){
+ var inner_params_and_defaults = param_and_default.substring(1, param_and_default.length -1) //cut off { and }
+ var inner_params_and_defaults_array = inner_params_and_defaults.split(",")
+ for(var inner_param_and_default of inner_params_and_defaults_array){
+ inner_param_and_default = inner_param_and_default.trim()
+ var the_match = inner_param_and_default.match(/^[A-Za-z_-]+/)
+ if (!the_match) {return null} //invalid syntax
+ var the_param = the_match[0]
+ param_names.push(the_param)
+ }
+ }
+ else {
+ var equal_pos = param_and_default.indexOf("=")
+ var the_param
+ if (equal_pos != -1){
+ the_param = param_and_default.substring(0, equal_pos)
+ the_param = the_param.trim()
+ }
+ else {
+ the_param = param_and_default
+ }
+ param_names.push(the_param)
+ }
+ }
+ var fn_src = full_src.substring(bounds[0], bounds[1])
+ var matches = fn_src.match(/var\s+[A-Za-z_-]+/g)
+ var var_names = []
+ if (matches){
+ for (var match of matches){
+ var_names.push(match.substring(4))
+ }
+ }
+ matches = fn_src.match(/let\s+[A-Za-z_-]+/g)
+ var let_names = []
+ if (matches){
+ for (var match of matches){
+ let_names.push(match.substring(4))
+ }
+ }
+ return {fn_name: fn_name, param_names: param_names, params_full_string: params_full_string, var_names: var_names, let_names: let_names}
+}
+
+//returns null if pos_of_char_in_identifier does not point at an identifier char,
+//or returns [start_pos_of_identifier, identifier_last_char_pos_plus_1]
+Editor.bounds_of_identifier = function(full_src, pos_of_char_in_indentifier, identifier_regex=/[a-zA-Z0-9\-\._]/){
+ //var identifier_regex = /[a-zA-Z0-9\-\._]/
+ if (!identifier_regex.test(full_src[pos_of_char_in_indentifier])){ return null}
+ var start_pos = null
+ for(var i = pos_of_char_in_indentifier; i >= 0; i--) {
+ var char = full_src[i]
+ if (!identifier_regex.test(char)) {
+ start_pos = i + 1;
+ break;
+ }
+ else if (i == 0) { start_pos = 0 }
+ }
+ var end_pos = null
+ for(var i = pos_of_char_in_indentifier; i < full_src.length; i++) {
+ var char = full_src[i]
+ if (!identifier_regex.test(char)) {
+ end_pos = i;
+ break;
+ }
+ else if (i == (full_src.length - 1)) { end_pos = full_src.length }
+ }
+ if (end_pos == null) { return null }
+ var id = full_src.substring(start_pos, end_pos)
+ //hack to turn "else if" into a single identifier
+ if (id == "else") {
+ var end_of_else_if_maybe = end_pos + 3
+ if ((full_src.length -1) >= end_of_else_if_maybe){
+ var the_if_suffix = full_src.substring(end_pos, end_of_else_if_maybe)
+ if (the_if_suffix == " if") { end_pos = end_of_else_if_maybe}
+ }
+ }
+ else if (id == "if"){
+ var start_of_else_if_maybe = start_pos - 5
+ if (start_of_else_if_maybe >= 0){
+ var the_else_prefix = full_src.substring(start_of_else_if_maybe, start_pos)
+ if (the_else_prefix == "else ") { start_pos = start_of_else_if_maybe}
+ }
+ }
+ else if (id == "function"){ //do we have function* ???
+ if ((full_src.length > end_pos) && full_src[end_pos] == "*"){
+ end_pos += 1
+ }
+ }
+ else if (id == "yield"){ //do we have yield* ???
+ if ((full_src.length > end_pos) && full_src[end_pos] == "*"){
+ end_pos += 1
+ }
+ }
+ return [start_pos, end_pos]
+}
+
+Editor.identifier_at_pos = function(){
+ var pos = Editor.selection_start()
+ var full_text = Editor.get_javascript()
+ var bounds = Editor.bounds_of_identifier(Editor.get_javascript(), pos)
+ if (bounds){
+ return full_text.slice(bounds[0], bounds[1])
+ }
+ else { return null }
+}
+
+Editor.bounds_of_operator = function(full_src, pos_of_char_in_identifier){
+ return Editor.bounds_of_identifier(full_src, pos_of_char_in_identifier, /[<>=!\+\-\*/%|&]/)
+}
+
+Editor.bounds_of_string_literal = function(full_src, pos_of_char_in_identifier){
+ var first_char = full_src[pos_of_char_in_identifier]
+ if ((first_char == '"') || (first_char == "'") || (first_char == "`")){
+ var ending_quote_pos = full_src.indexOf(first_char, pos_of_char_in_identifier + 1)
+ if (ending_quote_pos != -1){
+ var newline_pos = full_src.indexOf("\n", pos_of_char_in_identifier + 1)
+ if ((first_char == "`") || (newline_pos == -1) || (newline_pos > ending_quote_pos)){
+ return [pos_of_char_in_identifier, ending_quote_pos + 1] //we use counds in slice so ending quote needs to me 1 more than the actual pos of the ending quote
+ }
+ }
+ var starting_quote_pos = full_src.lastIndexOf(first_char, pos_of_char_in_identifier - 1)
+ if (starting_quote_pos != -1){
+ var newline_pos = full_src.lastIndexOf("\n", pos_of_char_in_identifier)
+ if ((first_char == "`") || (newline_pos == -1) || (newline_pos < starting_quote_pos)){
+ return [starting_quote_pos, pos_of_char_in_identifier + 1]
+ }
+ }
+ }
+ if (pos_of_char_in_identifier > 0){
+ var last_char = full_src[pos_of_char_in_identifier - 1]
+ if ((last_char == '"') || (last_char == "'") || (last_char == "`")){
+ var starting_quote_pos = full_src.lastIndexOf(last_char, pos_of_char_in_identifier - 2)
+ if (starting_quote_pos != -1){
+ var newline_pos = full_src.lastIndexOf("\n", pos_of_char_in_identifier + 1)
+ if ((first_char == "`") || (newline_pos == -1) || (newline_pos < starting_quote_pos)){
+ return [starting_quote_pos, pos_of_char_in_identifier]
+ }
+ }
+ }
+ }
+ return null
+}
+
+//returns null if we have {} since that could be the empty body of a fn, etc.
+//this is pretty flakey so do it at the end.
+//only matches on "{foo:..."
+Editor.bounds_of_object_literal = function(full_src, pos_of_char_in_identifier){
+ var first_char = full_src[pos_of_char_in_identifier]
+ if (first_char == '{'){
+ var ending_brace = full_src.indexOf("}", pos_of_char_in_identifier + 1)
+ if (ending_brace != -1){
+ for (var i = pos_of_char_in_identifier + 1; i < full_src.length; i++){
+ var char = full_src[i]
+ if(is_whitespace(char)){ } //keep looping//got first char of identifier
+ else if(is_letter_or_underscore(char)){ //got first char of first identifier in obj lit.
+ var ident_bounds = Editor.bounds_of_identifier(full_src, i )
+ if (ident_bounds) {
+ if (full_src[ident_bounds[1]] == ":"){
+ return [pos_of_char_in_identifier, ending_brace + 1]
+ }
+ else { return null }
+ }
+ else { return null }
+ }
+ else { return null } //got non whitespace and non first letter of a var so no go
+ }
+ }
+ else { return null }
+ }
+ else if (pos_of_char_in_identifier > 0){
+ var last_char = full_src[pos_of_char_in_identifier - 1]
+ if (last_char == '}'){
+ var starting_brace = full_src.lastIndexOf("{", pos_of_char_in_identifier - 2)
+ if (starting_brace != -1){
+ return Editor.bounds_of_object_literal(full_src, starting_brace)
+ }
+ }
+ }
+ return null
+}
+
+Editor.bounds_of_array_literal = function(full_src, pos_of_char_in_identifier){
+ var first_char = full_src[pos_of_char_in_identifier]
+ if (first_char == '['){
+ var ending_brace = Editor.find_matching_delimiter(full_src, pos_of_char_in_identifier)
+ if (ending_brace != null){
+ return [pos_of_char_in_identifier, ending_brace + 1]
+ }
+ else { return null }
+ }
+ else if (first_char == "]"){
+ var start_brace = Editor.find_matching_delimiter(full_src, pos_of_char_in_identifier)
+ if (start_brace != null){
+ return [start_brace, pos_of_char_in_identifier + 1]
+ }
+ else { return null }
+ }
+ else if (pos_of_char_in_identifier > 0){
+ var prev_char = full_src[pos_of_char_in_identifier - 1]
+ if (prev_char == "]"){
+ var start_pos = Editor.find_matching_delimiter(full_src, pos_of_char_in_identifier - 1)
+ if (start_pos != null){
+ return [start_pos, pos_of_char_in_identifier]
+ }
+ else { return null }
+ }
+ else { return null }
+ }
+ else { return false }
+}
+
+Editor.in_whitespace = function(full_src, pos){
+ if (pos >= full_src.length) { return true } //questionable, but what probably happened is user
+ //licked beyond the end of the last char, and the "pos" found in such cases will
+ //be the length of full_src, hence full_src[pos] will fail. So
+ //just call it whitespace.
+ else if (is_whitespace(full_src[pos])){
+ if (pos == 0){ return true }
+ else { return is_whitespace(full_src[pos - 1])}
+ }
+ else { return false }
+}
+
+Editor.identifier_or_operator = function(){
+ var pos = Editor.selection_start()
+ var full_src = Editor.get_javascript()
+ if (full_src.length == 0){
+ return "_the_editor_is_empty"
+ }
+ if (pos >= full_src.length){ //if we've clicked beyond the end of the buffer, back up one.
+ pos = pos - 1
+ if (is_whitespace(full_src[pos])){ return " " } //1 whitespace on end and clicking off the end is a whitespace click
+ }
+ var cur_char = full_src[pos]
+ if (is_whitespace(cur_char) && (pos > 0) && !is_whitespace(full_src[pos -1 ])){
+ pos = pos -1 // we probably have a situation like "foo " and the user clicked right after "foo",
+ //so pretend they really clicked on the last o of foo.
+ cur_char = full_src[pos]
+ }
+ if (cur_char == ",") { return ","}
+ else if (cur_char == ";") { return ";"}
+ else if (cur_char == ":") { return ":"}
+ else if (cur_char == "{") { return "{"}
+ else if (cur_char == "}") { return "}"}
+ else if (cur_char == "(") { return "("}
+ else if (cur_char == ")") { return ")"}
+ else if ((cur_char == ".") && (pos > 0) && !is_digit(full_src[pos - 1])){ return "." } //NOT a decimal point
+ var bounds = Editor.bounds_of_identifier(full_src, pos)
+ if (bounds){
+ var identifier = full_src.slice(bounds[0], bounds[1])
+ var fn_data = Editor.function_params_and_locals(full_src, pos)
+ if (fn_data){
+ if (fn_data.param_names.includes(identifier)){
+ return ["param_name", identifier, fn_data.fn_name]
+ }
+ else if (fn_data.var_names.includes(identifier)){
+ return ["var_name", identifier, fn_data.fn_name]
+ }
+ else if (fn_data.let_names.includes(identifier)){
+ return ["let_name", identifier, fn_data.fn_name]
+ }
+ else if (fn_data.fn_name == identifier){
+ return ["fn_name", identifier, fn_data.params_full_string //fn_data.param_names
+ ]
+ }
+ else { return identifier }
+ }
+ else { return identifier }
+ }
+ bounds = Editor.bounds_of_operator(full_src, pos)
+ if (bounds){return full_src.slice(bounds[0], bounds[1])}
+ bounds = Editor.bounds_of_string_literal(full_src, pos)
+ if (bounds){return full_src.slice(bounds[0], bounds[1])}
+ bounds = Editor.bounds_of_object_literal(full_src, pos)
+ if (bounds){return full_src.slice(bounds[0], bounds[1])}
+ bounds = Editor.bounds_of_array_literal(full_src, pos)
+ if (bounds){return full_src.slice(bounds[0], bounds[1])}
+ if (pos >= full_src.length) { return "_the_eof_token" } //never happens now that I back up 1 char if user clicks at end
+ if (Editor.in_whitespace(full_src, pos)){
+ return " " //note this won't likely be the actual string of whitespace but for our purposes, we
+ //only really care if its any whitespace
+ }
+ return null
+}
+
+//not now called apr 2016. functionalty taken over by identifier_or_operator
+Editor.variable_info = function(identifier){
+ if (/[a-zA-Z]/.test(identifier[0])){
+ var full_src = Editor.get_javascript()
+ var pos = Editor.selection_start()
+ var start_pos = Editor.find_backwards(full_src, pos, "function")
+ //I don't handle nested fn defs so probably will just break with them.
+ if (start_pos != -1){
+ var [fn_def_start, fn_def_end] = Editor.find_call_start_end_from_start(full_src, start_pos)
+ if (fn_def_end == -1) { //hmm, if no valid end, then presume we're writing the fn now
+ fn_def_end = full_src.length
+ }
+ var param_open_paren = full_src.indexOf("(", start_pos)
+ if ((param_open_paren != -1) && (pos < fn_def_end)){
+ var param_close_paren = Editor.find_matching_close(full_src, param_open_paren)
+ if (param_close_paren != -1){
+ var params_string = full_src.slice(param_open_paren + 1, param_close_paren)
+ var params_array = params_string.split(",")
+ for (let param of params_array){
+ param = param.trim()
+ if (param == identifier) { return "function parameter" }
+ else if (param.startsWith(identifier)){
+ var char_after_identifier = param[identifier.length]
+ if ([" ", "\n", "="].indexOf(char_after_identifier) != -1){
+ { return "function parameter" }
+ }
+ }
+ }
+ }
+ }
+ var var_identifier = "var " + identifier
+ var var_pos = full_src.indexOf(var_identifier, start_pos)
+ if ((var_pos != -1) && (var_identifier != -1) && (var_pos < pos) && (var_pos < fn_def_end)){ //note,
+ //we might find the var but if its beyond the end of the fn def, then not so good.
+ var char_after_identifier = full_src[var_pos + var_identifier.length]
+ if ([" ", "\n", "="].indexOf(char_after_identifier) != -1){
+ return "a local variable " + Js_info.make_atag("var", "var")
+ }
+ }
+ //I don't pretend to get the let scoping right, just check if let is declared between fn begin and cursor pos
+ var_identifier = "let " + identifier
+ var_pos = full_src.indexOf(var_identifier)
+ if ((var_pos != -1) && (var_identifier != -1) && (var_pos < pos) && (var_pos < fn_def_end)){
+ var char_after_identifier = full_src[var_pos + var_identifier.length]
+ if ([" ", "\n", "="].indexOf(char_after_identifier) != -1){
+ return "probably a local variable " + Js_info.make_atag("let", "let")
+ }
+ }
+ if (window[identifier]){
+ return "a global variable with value: " + window[identifier]
+ }
+ }
+ }
+ return null
+}
+
+Editor.show_identifier_info = function(){
+ var identifier = Editor.identifier_or_operator()
+ if (identifier){
+ var info = Js_info.get_info_string(identifier)
+ /* this is now implemented in identifier_or_operator that returns a potential array with var, let and param into in it.
+ if (!info){
+ info = Editor.variable_info(identifier)
+ if (info){ info = "" + identifier + " is " + info }
+ }*/
+ if (info){
+ out(info, null, true)
+ }
+ }
+}
diff --git a/eslint-lint.js b/eslint-lint.js
new file mode 100755
index 00000000..9fb829fa
--- /dev/null
+++ b/eslint-lint.js
@@ -0,0 +1,257 @@
+// CodeMirror Lint addon to use ESLint, copyright (c) by Angelo ZERR and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Depends on eslint.js from https://github.com/eslint/eslint
+//CodeMirror = //require("codemirror")
+
+(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";
+
+ var defaultConfig = {
+ "globals": { //cfry added this whole section
+ "ab": false,
+ "append_in_ui": false,
+ "beep": false,
+ "beeps": false,
+ "Brain": false,
+ "class": false, //I still get a warning for class as a "reserved word"
+ "close_window": false,
+ "console": false, //permit using "console" without warning, but don't permit the setting of it.
+ "Dexter": false,
+ "dex": false,
+ "Duration": false,
+ "editor": false,
+ //"funciton*: false, doesn't work in getting rid of warning.
+ "get_in_ui": false,
+ "Human": false,
+ "Job": false,
+ "out": false,
+ "rde": false,
+ "remove_in_ui": false,
+ "replace_in_ui": false,
+ "Robot": false,
+ "setTimeout": false,
+ "set_in_ui": false,
+ "Serial": false,
+ "show_window": false,
+ "Sim": false,
+ "svg_svg": false,
+ "svg_circle": false,
+ "svg_ellipse": false,
+ "svg_html": false,
+ "svg_polygon": false,
+ "svg_polyline": false,
+ "svg_line": false,
+ "svg_rect": false,
+ "svg_text": false,
+ "TestSuite": false
+ },
+ "parserOptions": {
+ "ecmaVersion": 6,
+ "ecmaFeatures": {
+ "forOf": true, //cfry added forOf to not warn when "for ... of"
+ //"backtick": true //cfry this doesn't work. I get errors when using backtick. apparently no feature to allow backticks
+ "class": true
+ }
+ },
+ "env": {
+ "browser": true, //cfry default is false,
+ "es6": true, //cfry default was not to have this line here
+ "node": false,
+ "amd": false,
+ "mocha": false,
+ "jasmine": false
+ },
+ "rules": { //0 = "off" or "turn the rule off", 1 = warn, 2 = on
+ "no-alert": 2,
+ "no-array-constructor": 2,
+ "no-bitwise": 0,
+ "no-caller": 2,
+ "no-catch-shadow": 2,
+ "no-comma-dangle": 2,
+ "no-cond-assign": 2,
+ "no-console": 0, //cfry default is 2, but that causes warnings when using it.
+ "no-constant-condition": 2,
+ "no-control-regex": 2,
+ "no-debugger": 0, //cfry default is 2,
+ "no-delete-var": 2,
+ "no-div-regex": 0,
+ "no-dupe-keys": 2,
+ "no-else-return": 0,
+ "no-empty": 2,
+ "no-empty-class": 2,
+ "no-empty-label": 2,
+ "no-eq-null": 0,
+ "no-eval": 2,
+ "no-ex-assign": 2,
+ "no-extend-native": 2,
+ "no-extra-bind": 2,
+ "no-extra-boolean-cast": 2,
+ "no-extra-parens": 0,
+ "no-extra-semi": 2,
+ "no-extra-strict": 2,
+ "no-fallthrough": 2,
+ "no-floating-decimal": 0,
+ "no-func-assign": 2,
+ "no-implied-eval": 2,
+ "no-inline-comments": 0,
+ "no-inner-declarations": [2, "functions"],
+ "no-invalid-regexp": 2,
+ "no-irregular-whitespace": 2,
+ "no-iterator": 2,
+ "no-label-var": 2,
+ "no-labels": 2,
+ "no-lone-blocks": 2,
+ "no-lonely-if": 0,
+ "no-loop-func": 2,
+ "no-mixed-requires": [0, false],
+ "no-mixed-spaces-and-tabs": [0, false], //was 2
+ "no-multi-spaces": 2,
+ "no-multi-str": 2,
+ "no-multiple-empty-lines": [0, {"max": 2}],
+ "no-native-reassign": 2,
+ "no-negated-in-lhs": 2,
+ "no-nested-ternary": 0,
+ "no-new": 0, //cfry default is 2, neaming that "new foo()" causes warning whereas bar = new foo() does not.
+ //cfry set to 0 because "new Job()" is good code in DDE because new Job("j2") gives a name to the job
+ // and makes Job.j2 work in returing the new instance.
+ "no-new-func": 2,
+ "no-new-object": 2,
+ "no-new-require": 0,
+ "no-new-wrappers": 2,
+ "no-obj-calls": 2,
+ "no-octal": 2,
+ "no-octal-escape": 2,
+ "no-path-concat": 0,
+ "no-plusplus": 0,
+ "no-process-env": 0,
+ "no-process-exit": 2,
+ "no-proto": 2,
+ "no-redeclare": 2,
+ "no-regex-spaces": 2,
+ "no-reserved-keys": 0,
+ "no-restricted-modules": 0,
+ "no-return-assign": 2,
+ "no-script-url": 2,
+ "no-self-compare": 0,
+ "no-sequences": 2,
+ "no-shadow": 2,
+ "no-shadow-restricted-names": 2,
+ "no-space-before-semi": 2,
+ "no-spaced-func": 2,
+ "no-sparse-arrays": 2,
+ "no-sync": 0,
+ "no-ternary": 0,
+ "no-trailing-spaces": 0, //cfry default 2
+ "no-undef": 2,
+ "no-undef-init": 2,
+ "no-undefined": 0,
+ "no-underscore-dangle": 2,
+ "no-unreachable": 2,
+ "no-unused-expressions": 2,
+ "no-unused-vars": [2, {"vars": "all", "args": "after-used"}],
+ "no-use-before-define": 2,
+ "no-void": 0,
+ "no-var": 0,
+ "no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],
+ "no-with": 2,
+ "no-wrap-func": 2,
+ "block-scoped-var": 0,
+ "brace-style": [0, "1tbs"],
+ "camelcase": 0, //cfry default of 2 requires fn names to be camel cased. yuck
+ "comma-spacing": 2,
+ "comma-style": 0,
+ "complexity": [0, 11],
+ "consistent-return": 2,
+ "consistent-this": [0, "that"],
+ "curly": [2, "all"],
+ "default-case": 0,
+ "dot-notation": [2, { "allowKeywords": true }],
+ "eol-last": 0, //cfry default of 2 requires a newline at end of file. 0 allows there to be no newline.
+ "eqeqeq": 2,
+ "func-names": 0,
+ "func-style": [0, "declaration"],
+ "generator-star": 0,
+ "global-strict": [2, "never"],
+ "guard-for-in": 0,
+ "handle-callback-err": 0,
+ "key-spacing": [2, { "beforeColon": false, "afterColon": true }],
+ "max-depth": [0, 4],
+ "max-len": [0, 80, 4],
+ "max-nested-callbacks": [0, 2],
+ "max-params": [0, 3],
+ "max-statements": [0, 10],
+ "new-cap": 2,
+ "new-parens": 2,
+ "one-var": 0,
+ "operator-assignment": [0, "always"],
+ "padded-blocks": 0,
+ "quote-props": 0,
+ "quotes": 0, //[2, "backtick"], //cfry using 0 (not the default) allows surrounding strings with both double and single quotes but not backtick
+ "radix": 0,
+ "semi": 0, //cfry default was: 2. using 0 turn offs warning for no semicolons.
+ "sort-vars": 0,
+ "space-after-function-name": [0, "never"],
+ "space-after-keywords": [0, "always"],
+ "space-before-blocks": [0, "always"],
+ "space-in-brackets": [0, "never"],
+ "space-in-parens": [0, "never"],
+ "space-infix-ops": 2,
+ "space-return-throw-case": 2,
+ "space-unary-ops": [2, { "words": true, "nonwords": false }],
+ "spaced-line-comment": [0, "always"],
+ "strict": 0, //default 2, cfry changed to 0 because if I have "forOf": true as above to not warn on forOf, then if strict: 2, every line in programis underlined in red.
+ // https://jslinterrors.com/missing-use-strict-statement
+ "use-isnan": 2,
+ "valid-jsdoc": 0,
+ "valid-typeof": 2,
+ "vars-on-top": 0,
+ "wrap-iife": 0,
+ "wrap-regex": 0,
+ "yoda": [2, "never"]
+ }
+ }
+
+ function validator(text, options) {
+ var result = [], config = defaultConfig;
+ var errors = eslint.verify(text, config);
+ for (var i = 0; i < errors.length; i++) {
+ var error = errors[i];
+ result.push({message: error.message,
+ severity: getSeverity(error),
+ from: getPos(error, true),
+ to: getPos(error, false)});
+ }
+ return result;
+ }
+
+ CodeMirror.registerHelper("lint", "javascript", validator);
+
+ function getPos(error, from) {
+ var line = error.line-1, ch = from ? error.column : error.column+1;
+ if (error.node && error.node.loc) {
+ line = from ? error.node.loc.start.line -1 : error.node.loc.end.line -1;
+ ch = from ? error.node.loc.start.column : error.node.loc.end.column;
+ }
+ return CodeMirror.Pos(line, ch);
+ }
+
+ function getSeverity(error) {
+ switch(error.severity) {
+ case 1:
+ return "warning";
+ case 2:
+ return "error";
+ default:
+ return "error";
+ }
+ }
+
+});
diff --git a/eslint.js b/eslint.js
new file mode 100755
index 00000000..f3f48b80
--- /dev/null
+++ b/eslint.js
@@ -0,0 +1,22835 @@
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.eslint=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && this._events[type].length > m) {
+ this._events[type].warned = true;
+ console.error('(node) warning: possible EventEmitter memory ' +
+ 'leak detected. %d listeners added. ' +
+ 'Use emitter.setMaxListeners() to increase limit.',
+ this._events[type].length);
+ if (typeof console.trace === 'function') {
+ // not supported in IE 10
+ console.trace();
+ }
+ }
+ }
+
+ return this;
+};
+
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+
+EventEmitter.prototype.once = function(type, listener) {
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
+
+ var fired = false;
+
+ function g() {
+ this.removeListener(type, g);
+
+ if (!fired) {
+ fired = true;
+ listener.apply(this, arguments);
+ }
+ }
+
+ g.listener = listener;
+ this.on(type, g);
+
+ return this;
+};
+
+// emits a 'removeListener' event iff the listener was removed
+EventEmitter.prototype.removeListener = function(type, listener) {
+ var list, position, length, i;
+
+ if (!isFunction(listener))
+ throw TypeError('listener must be a function');
+
+ if (!this._events || !this._events[type])
+ return this;
+
+ list = this._events[type];
+ length = list.length;
+ position = -1;
+
+ if (list === listener ||
+ (isFunction(list.listener) && list.listener === listener)) {
+ delete this._events[type];
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+
+ } else if (isObject(list)) {
+ for (i = length; i-- > 0;) {
+ if (list[i] === listener ||
+ (list[i].listener && list[i].listener === listener)) {
+ position = i;
+ break;
+ }
+ }
+
+ if (position < 0)
+ return this;
+
+ if (list.length === 1) {
+ list.length = 0;
+ delete this._events[type];
+ } else {
+ list.splice(position, 1);
+ }
+
+ if (this._events.removeListener)
+ this.emit('removeListener', type, listener);
+ }
+
+ return this;
+};
+
+EventEmitter.prototype.removeAllListeners = function(type) {
+ var key, listeners;
+
+ if (!this._events)
+ return this;
+
+ // not listening for removeListener, no need to emit
+ if (!this._events.removeListener) {
+ if (arguments.length === 0)
+ this._events = {};
+ else if (this._events[type])
+ delete this._events[type];
+ return this;
+ }
+
+ // emit removeListener for all listeners on all events
+ if (arguments.length === 0) {
+ for (key in this._events) {
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+ this.removeAllListeners('removeListener');
+ this._events = {};
+ return this;
+ }
+
+ listeners = this._events[type];
+
+ if (isFunction(listeners)) {
+ this.removeListener(type, listeners);
+ } else {
+ // LIFO order
+ while (listeners.length)
+ this.removeListener(type, listeners[listeners.length - 1]);
+ }
+ delete this._events[type];
+
+ return this;
+};
+
+EventEmitter.prototype.listeners = function(type) {
+ var ret;
+ if (!this._events || !this._events[type])
+ ret = [];
+ else if (isFunction(this._events[type]))
+ ret = [this._events[type]];
+ else
+ ret = this._events[type].slice();
+ return ret;
+};
+
+EventEmitter.listenerCount = function(emitter, type) {
+ var ret;
+ if (!emitter._events || !emitter._events[type])
+ ret = 0;
+ else if (isFunction(emitter._events[type]))
+ ret = 1;
+ else
+ ret = emitter._events[type].length;
+ return ret;
+};
+
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+
+function isUndefined(arg) {
+ return arg === void 0;
+}
+
+},{}],4:[function(require,module,exports){
+// shim for using process in browser
+
+var process = module.exports = {};
+var queue = [];
+var draining = false;
+
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ draining = true;
+ var currentQueue;
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ var i = -1;
+ while (++i < len) {
+ currentQueue[i]();
+ }
+ len = queue.length;
+ }
+ draining = false;
+}
+process.nextTick = function (fun) {
+ queue.push(fun);
+ if (!draining) {
+ setTimeout(drainQueue, 0);
+ }
+};
+
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+
+function noop() {}
+
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
+
+// TODO(shtylman)
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
+
+},{}],5:[function(require,module,exports){
+/*
+ Copyright (C) 2012-2014 Yusuke Suzuki
+ Copyright (C) 2014 Dan Tao
+ Copyright (C) 2013 Andrew Eisenberg
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+(function () {
+ 'use strict';
+
+ var VERSION,
+ typed,
+ jsdoc,
+ esutils,
+ isArray,
+ hasOwnProperty;
+
+ // Sync with package.json.
+ VERSION = require('./package.json').version;
+
+ esutils = require('esutils');
+
+ function sliceSource(source, index, last) {
+ return source.slice(index, last);
+ }
+
+ isArray = Array.isArray;
+ if (!isArray) {
+ isArray = function isArray(ary) {
+ return Object.prototype.toString.call(ary) === '[object Array]';
+ };
+ }
+
+ hasOwnProperty = (function () {
+ var func = Object.prototype.hasOwnProperty;
+ return function hasOwnProperty(obj, name) {
+ return func.call(obj, name);
+ };
+ }());
+
+ function shallowCopy(obj) {
+ var ret = {}, key;
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
+ }
+
+ function isASCIIAlphanumeric(ch) {
+ return (ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */) ||
+ (ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */) ||
+ (ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */);
+ }
+
+ function isTypeName(ch) {
+ return '><(){}[],:*|?!='.indexOf(String.fromCharCode(ch)) === -1 && !esutils.code.isWhiteSpace(ch) && !esutils.code.isLineTerminator(ch);
+ }
+
+ function isParamTitle(title) {
+ return title === 'param' || title === 'argument' || title === 'arg';
+ }
+
+ function isProperty(title) {
+ return title === 'property' || title === 'prop';
+ }
+
+ function isNameParameterRequired(title) {
+ return isParamTitle(title) || isProperty(title) ||
+ title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires';
+ }
+
+ function isAllowedName(title) {
+ return isNameParameterRequired(title) || title === 'const' || title === 'constant';
+ }
+
+ function isAllowedNested(title) {
+ return isProperty(title) || isParamTitle(title);
+ }
+
+ function isTypeParameterRequired(title) {
+ return isParamTitle(title) || title === 'define' || title === 'enum' ||
+ title === 'implements' || title === 'return' ||
+ title === 'this' || title === 'type' || title === 'typedef' ||
+ title === 'returns' || isProperty(title);
+ }
+
+ // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required
+ // This would require changes to 'parseType'
+ function isAllowedType(title) {
+ return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' ||
+ title === 'namespace' || title === 'member' || title === 'var' || title === 'module' ||
+ title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' ||
+ title === 'public' || title === 'private' || title === 'protected';
+ }
+
+ function DoctrineError(message) {
+ this.name = 'DoctrineError';
+ this.message = message;
+ }
+ DoctrineError.prototype = (function () {
+ var Middle = function () { };
+ Middle.prototype = Error.prototype;
+ return new Middle();
+ }());
+ DoctrineError.prototype.constructor = DoctrineError;
+
+ function throwError(message) {
+ throw new DoctrineError(message);
+ }
+
+ function assert(cond, text) {
+ if (VERSION.slice(-3) === 'dev') {
+ if (!cond) {
+ throwError(text);
+ }
+ }
+ }
+
+ function trim(str) {
+ return str.replace(/^\s+/, '').replace(/\s+$/, '');
+ }
+
+ function unwrapComment(doc) {
+ // JSDoc comment is following form
+ // /**
+ // * .......
+ // */
+ // remove /**, */ and *
+ var BEFORE_STAR = 0,
+ STAR = 1,
+ AFTER_STAR = 2,
+ index,
+ len,
+ mode,
+ result,
+ ch;
+
+ doc = doc.replace(/^\/\*\*?/, '').replace(/\*\/$/, '');
+ index = 0;
+ len = doc.length;
+ mode = BEFORE_STAR;
+ result = '';
+
+ while (index < len) {
+ ch = doc.charCodeAt(index);
+ switch (mode) {
+ case BEFORE_STAR:
+ if (esutils.code.isLineTerminator(ch)) {
+ result += String.fromCharCode(ch);
+ } else if (ch === 0x2A /* '*' */) {
+ mode = STAR;
+ } else if (!esutils.code.isWhiteSpace(ch)) {
+ result += String.fromCharCode(ch);
+ mode = AFTER_STAR;
+ }
+ break;
+
+ case STAR:
+ if (!esutils.code.isWhiteSpace(ch)) {
+ result += String.fromCharCode(ch);
+ }
+ mode = esutils.code.isLineTerminator(ch) ? BEFORE_STAR : AFTER_STAR;
+ break;
+
+ case AFTER_STAR:
+ result += String.fromCharCode(ch);
+ if (esutils.code.isLineTerminator(ch)) {
+ mode = BEFORE_STAR;
+ }
+ break;
+ }
+ index += 1;
+ }
+
+ return result;
+ }
+
+ // Type Expression Parser
+
+ (function (exports) {
+ var Syntax,
+ Token,
+ source,
+ length,
+ index,
+ previous,
+ token,
+ value;
+
+ Syntax = {
+ NullableLiteral: 'NullableLiteral',
+ AllLiteral: 'AllLiteral',
+ NullLiteral: 'NullLiteral',
+ UndefinedLiteral: 'UndefinedLiteral',
+ VoidLiteral: 'VoidLiteral',
+ UnionType: 'UnionType',
+ ArrayType: 'ArrayType',
+ RecordType: 'RecordType',
+ FieldType: 'FieldType',
+ FunctionType: 'FunctionType',
+ ParameterType: 'ParameterType',
+ RestType: 'RestType',
+ NonNullableType: 'NonNullableType',
+ OptionalType: 'OptionalType',
+ NullableType: 'NullableType',
+ NameExpression: 'NameExpression',
+ TypeApplication: 'TypeApplication'
+ };
+
+ Token = {
+ ILLEGAL: 0, // ILLEGAL
+ DOT_LT: 1, // .<
+ REST: 2, // ...
+ LT: 3, // <
+ GT: 4, // >
+ LPAREN: 5, // (
+ RPAREN: 6, // )
+ LBRACE: 7, // {
+ RBRACE: 8, // }
+ LBRACK: 9, // [
+ RBRACK: 10, // ]
+ COMMA: 11, // ,
+ COLON: 12, // :
+ STAR: 13, // *
+ PIPE: 14, // |
+ QUESTION: 15, // ?
+ BANG: 16, // !
+ EQUAL: 17, // =
+ NAME: 18, // name token
+ STRING: 19, // string
+ NUMBER: 20, // number
+ EOF: 21
+ };
+
+ function Context(previous, index, token, value) {
+ this._previous = previous;
+ this._index = index;
+ this._token = token;
+ this._value = value;
+ }
+
+ Context.prototype.restore = function () {
+ previous = this._previous;
+ index = this._index;
+ token = this._token;
+ value = this._value;
+ };
+
+ Context.save = function () {
+ return new Context(previous, index, token, value);
+ };
+
+ function advance() {
+ var ch = source.charAt(index);
+ index += 1;
+ return ch;
+ }
+
+ function scanHexEscape(prefix) {
+ var i, len, ch, code = 0;
+
+ len = (prefix === 'u') ? 4 : 2;
+ for (i = 0; i < len; ++i) {
+ if (index < length && esutils.code.isHexDigit(source.charCodeAt(index))) {
+ ch = advance();
+ code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
+ } else {
+ return '';
+ }
+ }
+ return String.fromCharCode(code);
+ }
+
+ function scanString() {
+ var str = '', quote, ch, code, unescaped, restore; //TODO review removal octal = false
+ quote = source.charAt(index);
+ ++index;
+
+ while (index < length) {
+ ch = advance();
+
+ if (ch === quote) {
+ quote = '';
+ break;
+ } else if (ch === '\\') {
+ ch = advance();
+ if (!esutils.code.isLineTerminator(ch.charCodeAt(0))) {
+ switch (ch) {
+ case 'n':
+ str += '\n';
+ break;
+ case 'r':
+ str += '\r';
+ break;
+ case 't':
+ str += '\t';
+ break;
+ case 'u':
+ case 'x':
+ restore = index;
+ unescaped = scanHexEscape(ch);
+ if (unescaped) {
+ str += unescaped;
+ } else {
+ index = restore;
+ str += ch;
+ }
+ break;
+ case 'b':
+ str += '\b';
+ break;
+ case 'f':
+ str += '\f';
+ break;
+ case 'v':
+ str += '\v';
+ break;
+
+ default:
+ if (esutils.code.isOctalDigit(ch.charCodeAt(0))) {
+ code = '01234567'.indexOf(ch);
+
+ // \0 is not octal escape sequence
+ // Deprecating unused code. TODO review removal
+ //if (code !== 0) {
+ // octal = true;
+ //}
+
+ if (index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) {
+ //TODO Review Removal octal = true;
+ code = code * 8 + '01234567'.indexOf(advance());
+
+ // 3 digits are only allowed when string starts
+ // with 0, 1, 2, 3
+ if ('0123'.indexOf(ch) >= 0 &&
+ index < length &&
+ esutils.code.isOctalDigit(source.charCodeAt(index))) {
+ code = code * 8 + '01234567'.indexOf(advance());
+ }
+ }
+ str += String.fromCharCode(code);
+ } else {
+ str += ch;
+ }
+ break;
+ }
+ } else {
+ if (ch === '\r' && source.charCodeAt(index) === 0x0A /* '\n' */) {
+ ++index;
+ }
+ }
+ } else if (esutils.code.isLineTerminator(ch.charCodeAt(0))) {
+ break;
+ } else {
+ str += ch;
+ }
+ }
+
+ if (quote !== '') {
+ throwError('unexpected quote');
+ }
+
+ value = str;
+ return Token.STRING;
+ }
+
+ function scanNumber() {
+ var number, ch;
+
+ number = '';
+ ch = source.charCodeAt(index);
+
+ if (ch !== 0x2E /* '.' */) {
+ number = advance();
+ ch = source.charCodeAt(index);
+
+ if (number === '0') {
+ if (ch === 0x78 /* 'x' */ || ch === 0x58 /* 'X' */) {
+ number += advance();
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!esutils.code.isHexDigit(ch)) {
+ break;
+ }
+ number += advance();
+ }
+
+ if (number.length <= 2) {
+ // only 0x
+ throwError('unexpected token');
+ }
+
+ if (index < length) {
+ ch = source.charCodeAt(index);
+ if (esutils.code.isIdentifierStart(ch)) {
+ throwError('unexpected token');
+ }
+ }
+ value = parseInt(number, 16);
+ return Token.NUMBER;
+ }
+
+ if (esutils.code.isOctalDigit(ch)) {
+ number += advance();
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!esutils.code.isOctalDigit(ch)) {
+ break;
+ }
+ number += advance();
+ }
+
+ if (index < length) {
+ ch = source.charCodeAt(index);
+ if (esutils.code.isIdentifierStart(ch) || esutils.code.isDecimalDigit(ch)) {
+ throwError('unexpected token');
+ }
+ }
+ value = parseInt(number, 8);
+ return Token.NUMBER;
+ }
+
+ if (esutils.code.isDecimalDigit(ch)) {
+ throwError('unexpected token');
+ }
+ }
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!esutils.code.isDecimalDigit(ch)) {
+ break;
+ }
+ number += advance();
+ }
+ }
+
+ if (ch === 0x2E /* '.' */) {
+ number += advance();
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!esutils.code.isDecimalDigit(ch)) {
+ break;
+ }
+ number += advance();
+ }
+ }
+
+ if (ch === 0x65 /* 'e' */ || ch === 0x45 /* 'E' */) {
+ number += advance();
+
+ ch = source.charCodeAt(index);
+ if (ch === 0x2B /* '+' */ || ch === 0x2D /* '-' */) {
+ number += advance();
+ }
+
+ ch = source.charCodeAt(index);
+ if (esutils.code.isDecimalDigit(ch)) {
+ number += advance();
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!esutils.code.isDecimalDigit(ch)) {
+ break;
+ }
+ number += advance();
+ }
+ } else {
+ throwError('unexpected token');
+ }
+ }
+
+ if (index < length) {
+ ch = source.charCodeAt(index);
+ if (esutils.code.isIdentifierStart(ch)) {
+ throwError('unexpected token');
+ }
+ }
+
+ value = parseFloat(number);
+ return Token.NUMBER;
+ }
+
+
+ function scanTypeName() {
+ var ch, ch2;
+
+ value = advance();
+ while (index < length && isTypeName(source.charCodeAt(index))) {
+ ch = source.charCodeAt(index);
+ if (ch === 0x2E /* '.' */) {
+ if ((index + 1) >= length) {
+ return Token.ILLEGAL;
+ }
+ ch2 = source.charCodeAt(index + 1);
+ if (ch2 === 0x3C /* '<' */) {
+ break;
+ }
+ }
+ value += advance();
+ }
+ return Token.NAME;
+ }
+
+ function next() {
+ var ch;
+
+ previous = index;
+
+ while (index < length && esutils.code.isWhiteSpace(source.charCodeAt(index))) {
+ advance();
+ }
+ if (index >= length) {
+ token = Token.EOF;
+ return token;
+ }
+
+ ch = source.charCodeAt(index);
+ switch (ch) {
+ case 0x27: /* ''' */
+ case 0x22: /* '"' */
+ token = scanString();
+ return token;
+
+ case 0x3A: /* ':' */
+ advance();
+ token = Token.COLON;
+ return token;
+
+ case 0x2C: /* ',' */
+ advance();
+ token = Token.COMMA;
+ return token;
+
+ case 0x28: /* '(' */
+ advance();
+ token = Token.LPAREN;
+ return token;
+
+ case 0x29: /* ')' */
+ advance();
+ token = Token.RPAREN;
+ return token;
+
+ case 0x5B: /* '[' */
+ advance();
+ token = Token.LBRACK;
+ return token;
+
+ case 0x5D: /* ']' */
+ advance();
+ token = Token.RBRACK;
+ return token;
+
+ case 0x7B: /* '{' */
+ advance();
+ token = Token.LBRACE;
+ return token;
+
+ case 0x7D: /* '}' */
+ advance();
+ token = Token.RBRACE;
+ return token;
+
+ case 0x2E: /* '.' */
+ if (index + 1 < length) {
+ ch = source.charCodeAt(index + 1);
+ if (ch === 0x3C /* '<' */) {
+ advance(); // '.'
+ advance(); // '<'
+ token = Token.DOT_LT;
+ return token;
+ }
+
+ if (ch === 0x2E /* '.' */ && index + 2 < length && source.charCodeAt(index + 2) === 0x2E /* '.' */) {
+ advance(); // '.'
+ advance(); // '.'
+ advance(); // '.'
+ token = Token.REST;
+ return token;
+ }
+
+ if (esutils.code.isDecimalDigit(ch)) {
+ token = scanNumber();
+ return token;
+ }
+ }
+ token = Token.ILLEGAL;
+ return token;
+
+ case 0x3C: /* '<' */
+ advance();
+ token = Token.LT;
+ return token;
+
+ case 0x3E: /* '>' */
+ advance();
+ token = Token.GT;
+ return token;
+
+ case 0x2A: /* '*' */
+ advance();
+ token = Token.STAR;
+ return token;
+
+ case 0x7C: /* '|' */
+ advance();
+ token = Token.PIPE;
+ return token;
+
+ case 0x3F: /* '?' */
+ advance();
+ token = Token.QUESTION;
+ return token;
+
+ case 0x21: /* '!' */
+ advance();
+ token = Token.BANG;
+ return token;
+
+ case 0x3D: /* '=' */
+ advance();
+ token = Token.EQUAL;
+ return token;
+
+ default:
+ if (esutils.code.isDecimalDigit(ch)) {
+ token = scanNumber();
+ return token;
+ }
+
+ // type string permits following case,
+ //
+ // namespace.module.MyClass
+ //
+ // this reduced 1 token TK_NAME
+ assert(isTypeName(ch));
+ token = scanTypeName();
+ return token;
+ }
+ }
+
+ function consume(target, text) {
+ assert(token === target, text || 'consumed token not matched');
+ next();
+ }
+
+ function expect(target) {
+ if (token !== target) {
+ throwError('unexpected token');
+ }
+ next();
+ }
+
+ // UnionType := '(' TypeUnionList ')'
+ //
+ // TypeUnionList :=
+ // <>
+ // | NonemptyTypeUnionList
+ //
+ // NonemptyTypeUnionList :=
+ // TypeExpression
+ // | TypeExpression '|' NonemptyTypeUnionList
+ function parseUnionType() {
+ var elements;
+ consume(Token.LPAREN, 'UnionType should start with (');
+ elements = [];
+ if (token !== Token.RPAREN) {
+ while (true) {
+ elements.push(parseTypeExpression());
+ if (token === Token.RPAREN) {
+ break;
+ }
+ expect(Token.PIPE);
+ }
+ }
+ consume(Token.RPAREN, 'UnionType should end with )');
+ return {
+ type: Syntax.UnionType,
+ elements: elements
+ };
+ }
+
+ // ArrayType := '[' ElementTypeList ']'
+ //
+ // ElementTypeList :=
+ // <>
+ // | TypeExpression
+ // | '...' TypeExpression
+ // | TypeExpression ',' ElementTypeList
+ function parseArrayType() {
+ var elements;
+ consume(Token.LBRACK, 'ArrayType should start with [');
+ elements = [];
+ while (token !== Token.RBRACK) {
+ if (token === Token.REST) {
+ consume(Token.REST);
+ elements.push({
+ type: Syntax.RestType,
+ expression: parseTypeExpression()
+ });
+ break;
+ } else {
+ elements.push(parseTypeExpression());
+ }
+ if (token !== Token.RBRACK) {
+ expect(Token.COMMA);
+ }
+ }
+ expect(Token.RBRACK);
+ return {
+ type: Syntax.ArrayType,
+ elements: elements
+ };
+ }
+
+ function parseFieldName() {
+ var v = value;
+ if (token === Token.NAME || token === Token.STRING) {
+ next();
+ return v;
+ }
+
+ if (token === Token.NUMBER) {
+ consume(Token.NUMBER);
+ return String(v);
+ }
+
+ throwError('unexpected token');
+ }
+
+ // FieldType :=
+ // FieldName
+ // | FieldName ':' TypeExpression
+ //
+ // FieldName :=
+ // NameExpression
+ // | StringLiteral
+ // | NumberLiteral
+ // | ReservedIdentifier
+ function parseFieldType() {
+ var key;
+
+ key = parseFieldName();
+ if (token === Token.COLON) {
+ consume(Token.COLON);
+ return {
+ type: Syntax.FieldType,
+ key: key,
+ value: parseTypeExpression()
+ };
+ }
+ return {
+ type: Syntax.FieldType,
+ key: key,
+ value: null
+ };
+ }
+
+ // RecordType := '{' FieldTypeList '}'
+ //
+ // FieldTypeList :=
+ // <>
+ // | FieldType
+ // | FieldType ',' FieldTypeList
+ function parseRecordType() {
+ var fields;
+
+ consume(Token.LBRACE, 'RecordType should start with {');
+ fields = [];
+ if (token === Token.COMMA) {
+ consume(Token.COMMA);
+ } else {
+ while (token !== Token.RBRACE) {
+ fields.push(parseFieldType());
+ if (token !== Token.RBRACE) {
+ expect(Token.COMMA);
+ }
+ }
+ }
+ expect(Token.RBRACE);
+ return {
+ type: Syntax.RecordType,
+ fields: fields
+ };
+ }
+
+ function parseNameExpression() {
+ var name = value;
+ expect(Token.NAME);
+ return {
+ type: Syntax.NameExpression,
+ name: name
+ };
+ }
+
+ // TypeExpressionList :=
+ // TopLevelTypeExpression
+ // | TopLevelTypeExpression ',' TypeExpressionList
+ function parseTypeExpressionList() {
+ var elements = [];
+
+ elements.push(parseTop());
+ while (token === Token.COMMA) {
+ consume(Token.COMMA);
+ elements.push(parseTop());
+ }
+ return elements;
+ }
+
+ // TypeName :=
+ // NameExpression
+ // | NameExpression TypeApplication
+ //
+ // TypeApplication :=
+ // '.<' TypeExpressionList '>'
+ // | '<' TypeExpressionList '>' // this is extension of doctrine
+ function parseTypeName() {
+ var expr, applications;
+
+ expr = parseNameExpression();
+ if (token === Token.DOT_LT || token === Token.LT) {
+ next();
+ applications = parseTypeExpressionList();
+ expect(Token.GT);
+ return {
+ type: Syntax.TypeApplication,
+ expression: expr,
+ applications: applications
+ };
+ }
+ return expr;
+ }
+
+ // ResultType :=
+ // <>
+ // | ':' void
+ // | ':' TypeExpression
+ //
+ // BNF is above
+ // but, we remove <> pattern, so token is always TypeToken::COLON
+ function parseResultType() {
+ consume(Token.COLON, 'ResultType should start with :');
+ if (token === Token.NAME && value === 'void') {
+ consume(Token.NAME);
+ return {
+ type: Syntax.VoidLiteral
+ };
+ }
+ return parseTypeExpression();
+ }
+
+ // ParametersType :=
+ // RestParameterType
+ // | NonRestParametersType
+ // | NonRestParametersType ',' RestParameterType
+ //
+ // RestParameterType :=
+ // '...'
+ // '...' Identifier
+ //
+ // NonRestParametersType :=
+ // ParameterType ',' NonRestParametersType
+ // | ParameterType
+ // | OptionalParametersType
+ //
+ // OptionalParametersType :=
+ // OptionalParameterType
+ // | OptionalParameterType, OptionalParametersType
+ //
+ // OptionalParameterType := ParameterType=
+ //
+ // ParameterType := TypeExpression | Identifier ':' TypeExpression
+ //
+ // Identifier is "new" or "this"
+ function parseParametersType() {
+ var params = [], optionalSequence = false, expr, rest = false;
+
+ while (token !== Token.RPAREN) {
+ if (token === Token.REST) {
+ // RestParameterType
+ consume(Token.REST);
+ rest = true;
+ }
+
+ expr = parseTypeExpression();
+ if (expr.type === Syntax.NameExpression && token === Token.COLON) {
+ // Identifier ':' TypeExpression
+ consume(Token.COLON);
+ expr = {
+ type: Syntax.ParameterType,
+ name: expr.name,
+ expression: parseTypeExpression()
+ };
+ }
+ if (token === Token.EQUAL) {
+ consume(Token.EQUAL);
+ expr = {
+ type: Syntax.OptionalType,
+ expression: expr
+ };
+ optionalSequence = true;
+ } else {
+ if (optionalSequence) {
+ throwError('unexpected token');
+ }
+ }
+ if (rest) {
+ expr = {
+ type: Syntax.RestType,
+ expression: expr
+ };
+ }
+ params.push(expr);
+ if (token !== Token.RPAREN) {
+ expect(Token.COMMA);
+ }
+ }
+ return params;
+ }
+
+ // FunctionType := 'function' FunctionSignatureType
+ //
+ // FunctionSignatureType :=
+ // | TypeParameters '(' ')' ResultType
+ // | TypeParameters '(' ParametersType ')' ResultType
+ // | TypeParameters '(' 'this' ':' TypeName ')' ResultType
+ // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType
+ function parseFunctionType() {
+ var isNew, thisBinding, params, result, fnType;
+ assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\'');
+ consume(Token.NAME);
+
+ // Google Closure Compiler is not implementing TypeParameters.
+ // So we do not. if we don't get '(', we see it as error.
+ expect(Token.LPAREN);
+
+ isNew = false;
+ params = [];
+ thisBinding = null;
+ if (token !== Token.RPAREN) {
+ // ParametersType or 'this'
+ if (token === Token.NAME &&
+ (value === 'this' || value === 'new')) {
+ // 'this' or 'new'
+ // 'new' is Closure Compiler extension
+ isNew = value === 'new';
+ consume(Token.NAME);
+ expect(Token.COLON);
+ thisBinding = parseTypeName();
+ if (token === Token.COMMA) {
+ consume(Token.COMMA);
+ params = parseParametersType();
+ }
+ } else {
+ params = parseParametersType();
+ }
+ }
+
+ expect(Token.RPAREN);
+
+ result = null;
+ if (token === Token.COLON) {
+ result = parseResultType();
+ }
+
+ fnType = {
+ type: Syntax.FunctionType,
+ params: params,
+ result: result
+ };
+ if (thisBinding) {
+ // avoid adding null 'new' and 'this' properties
+ fnType['this'] = thisBinding;
+ if (isNew) {
+ fnType['new'] = true;
+ }
+ }
+ return fnType;
+ }
+
+ // BasicTypeExpression :=
+ // '*'
+ // | 'null'
+ // | 'undefined'
+ // | TypeName
+ // | FunctionType
+ // | UnionType
+ // | RecordType
+ // | ArrayType
+ function parseBasicTypeExpression() {
+ var context;
+ switch (token) {
+ case Token.STAR:
+ consume(Token.STAR);
+ return {
+ type: Syntax.AllLiteral
+ };
+
+ case Token.LPAREN:
+ return parseUnionType();
+
+ case Token.LBRACK:
+ return parseArrayType();
+
+ case Token.LBRACE:
+ return parseRecordType();
+
+ case Token.NAME:
+ if (value === 'null') {
+ consume(Token.NAME);
+ return {
+ type: Syntax.NullLiteral
+ };
+ }
+
+ if (value === 'undefined') {
+ consume(Token.NAME);
+ return {
+ type: Syntax.UndefinedLiteral
+ };
+ }
+
+ context = Context.save();
+ if (value === 'function') {
+ try {
+ return parseFunctionType();
+ } catch (e) {
+ context.restore();
+ }
+ }
+
+ return parseTypeName();
+
+ default:
+ throwError('unexpected token');
+ }
+ }
+
+ // TypeExpression :=
+ // BasicTypeExpression
+ // | '?' BasicTypeExpression
+ // | '!' BasicTypeExpression
+ // | BasicTypeExpression '?'
+ // | BasicTypeExpression '!'
+ // | '?'
+ // | BasicTypeExpression '[]'
+ function parseTypeExpression() {
+ var expr;
+
+ if (token === Token.QUESTION) {
+ consume(Token.QUESTION);
+ if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE ||
+ token === Token.RPAREN || token === Token.PIPE || token === Token.EOF ||
+ token === Token.RBRACK) {
+ return {
+ type: Syntax.NullableLiteral
+ };
+ }
+ return {
+ type: Syntax.NullableType,
+ expression: parseBasicTypeExpression(),
+ prefix: true
+ };
+ }
+
+ if (token === Token.BANG) {
+ consume(Token.BANG);
+ return {
+ type: Syntax.NonNullableType,
+ expression: parseBasicTypeExpression(),
+ prefix: true
+ };
+ }
+
+ expr = parseBasicTypeExpression();
+ if (token === Token.BANG) {
+ consume(Token.BANG);
+ return {
+ type: Syntax.NonNullableType,
+ expression: expr,
+ prefix: false
+ };
+ }
+
+ if (token === Token.QUESTION) {
+ consume(Token.QUESTION);
+ return {
+ type: Syntax.NullableType,
+ expression: expr,
+ prefix: false
+ };
+ }
+
+ if (token === Token.LBRACK) {
+ consume(Token.LBRACK);
+ consume(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])');
+ return {
+ type: Syntax.TypeApplication,
+ expression: {
+ type: Syntax.NameExpression,
+ name: 'Array'
+ },
+ applications: [expr]
+ };
+ }
+
+ return expr;
+ }
+
+ // TopLevelTypeExpression :=
+ // TypeExpression
+ // | TypeUnionList
+ //
+ // This rule is Google Closure Compiler extension, not ES4
+ // like,
+ // { number | string }
+ // If strict to ES4, we should write it as
+ // { (number|string) }
+ function parseTop() {
+ var expr, elements;
+
+ expr = parseTypeExpression();
+ if (token !== Token.PIPE) {
+ return expr;
+ }
+
+ elements = [ expr ];
+ consume(Token.PIPE);
+ while (true) {
+ elements.push(parseTypeExpression());
+ if (token !== Token.PIPE) {
+ break;
+ }
+ consume(Token.PIPE);
+ }
+
+ return {
+ type: Syntax.UnionType,
+ elements: elements
+ };
+ }
+
+ function parseTopParamType() {
+ var expr;
+
+ if (token === Token.REST) {
+ consume(Token.REST);
+ return {
+ type: Syntax.RestType,
+ expression: parseTop()
+ };
+ }
+
+ expr = parseTop();
+ if (token === Token.EQUAL) {
+ consume(Token.EQUAL);
+ return {
+ type: Syntax.OptionalType,
+ expression: expr
+ };
+ }
+
+ return expr;
+ }
+
+ function parseType(src, opt) {
+ var expr;
+
+ source = src;
+ length = source.length;
+ index = 0;
+ previous = 0;
+
+ next();
+ expr = parseTop();
+
+ if (opt && opt.midstream) {
+ return {
+ expression: expr,
+ index: previous
+ };
+ }
+
+ if (token !== Token.EOF) {
+ throwError('not reach to EOF');
+ }
+
+ return expr;
+ }
+
+ function parseParamType(src, opt) {
+ var expr;
+
+ source = src;
+ length = source.length;
+ index = 0;
+ previous = 0;
+
+ next();
+ expr = parseTopParamType();
+
+ if (opt && opt.midstream) {
+ return {
+ expression: expr,
+ index: previous
+ };
+ }
+
+ if (token !== Token.EOF) {
+ throwError('not reach to EOF');
+ }
+
+ return expr;
+ }
+
+ function stringifyImpl(node, compact, topLevel) {
+ var result, i, iz;
+
+ switch (node.type) {
+ case Syntax.NullableLiteral:
+ result = '?';
+ break;
+
+ case Syntax.AllLiteral:
+ result = '*';
+ break;
+
+ case Syntax.NullLiteral:
+ result = 'null';
+ break;
+
+ case Syntax.UndefinedLiteral:
+ result = 'undefined';
+ break;
+
+ case Syntax.VoidLiteral:
+ result = 'void';
+ break;
+
+ case Syntax.UnionType:
+ if (!topLevel) {
+ result = '(';
+ } else {
+ result = '';
+ }
+
+ for (i = 0, iz = node.elements.length; i < iz; ++i) {
+ result += stringifyImpl(node.elements[i], compact);
+ if ((i + 1) !== iz) {
+ result += '|';
+ }
+ }
+
+ if (!topLevel) {
+ result += ')';
+ }
+ break;
+
+ case Syntax.ArrayType:
+ result = '[';
+ for (i = 0, iz = node.elements.length; i < iz; ++i) {
+ result += stringifyImpl(node.elements[i], compact);
+ if ((i + 1) !== iz) {
+ result += compact ? ',' : ', ';
+ }
+ }
+ result += ']';
+ break;
+
+ case Syntax.RecordType:
+ result = '{';
+ for (i = 0, iz = node.fields.length; i < iz; ++i) {
+ result += stringifyImpl(node.fields[i], compact);
+ if ((i + 1) !== iz) {
+ result += compact ? ',' : ', ';
+ }
+ }
+ result += '}';
+ break;
+
+ case Syntax.FieldType:
+ if (node.value) {
+ result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact);
+ } else {
+ result = node.key;
+ }
+ break;
+
+ case Syntax.FunctionType:
+ result = compact ? 'function(' : 'function (';
+
+ if (node['this']) {
+ if (node['new']) {
+ result += (compact ? 'new:' : 'new: ');
+ } else {
+ result += (compact ? 'this:' : 'this: ');
+ }
+
+ result += stringifyImpl(node['this'], compact);
+
+ if (node.params.length !== 0) {
+ result += compact ? ',' : ', ';
+ }
+ }
+
+ for (i = 0, iz = node.params.length; i < iz; ++i) {
+ result += stringifyImpl(node.params[i], compact);
+ if ((i + 1) !== iz) {
+ result += compact ? ',' : ', ';
+ }
+ }
+
+ result += ')';
+
+ if (node.result) {
+ result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact);
+ }
+ break;
+
+ case Syntax.ParameterType:
+ result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact);
+ break;
+
+ case Syntax.RestType:
+ result = '...';
+ if (node.expression) {
+ result += stringifyImpl(node.expression, compact);
+ }
+ break;
+
+ case Syntax.NonNullableType:
+ if (node.prefix) {
+ result = '!' + stringifyImpl(node.expression, compact);
+ } else {
+ result = stringifyImpl(node.expression, compact) + '!';
+ }
+ break;
+
+ case Syntax.OptionalType:
+ result = stringifyImpl(node.expression, compact) + '=';
+ break;
+
+ case Syntax.NullableType:
+ if (node.prefix) {
+ result = '?' + stringifyImpl(node.expression, compact);
+ } else {
+ result = stringifyImpl(node.expression, compact) + '?';
+ }
+ break;
+
+ case Syntax.NameExpression:
+ result = node.name;
+ break;
+
+ case Syntax.TypeApplication:
+ result = stringifyImpl(node.expression, compact) + '.<';
+ for (i = 0, iz = node.applications.length; i < iz; ++i) {
+ result += stringifyImpl(node.applications[i], compact);
+ if ((i + 1) !== iz) {
+ result += compact ? ',' : ', ';
+ }
+ }
+ result += '>';
+ break;
+
+ default:
+ throwError('Unknown type ' + node.type);
+ }
+
+ return result;
+ }
+
+ function stringify(node, options) {
+ if (options == null) {
+ options = {};
+ }
+ return stringifyImpl(node, options.compact, options.topLevel);
+ }
+
+ exports.parseType = parseType;
+ exports.parseParamType = parseParamType;
+ exports.stringify = stringify;
+ exports.Syntax = Syntax;
+ }(typed = {}));
+
+ // JSDoc Tag Parser
+
+ (function (exports) {
+ var Rules,
+ index,
+ lineNumber,
+ length,
+ source,
+ recoverable,
+ sloppy,
+ strict;
+
+ function advance() {
+ var ch = source.charCodeAt(index);
+ index += 1;
+ if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(index) === 0x0A /* '\n' */)) {
+ lineNumber += 1;
+ }
+ return String.fromCharCode(ch);
+ }
+
+ function scanTitle() {
+ var title = '';
+ // waste '@'
+ advance();
+
+ while (index < length && isASCIIAlphanumeric(source.charCodeAt(index))) {
+ title += advance();
+ }
+
+ return title;
+ }
+
+ function seekContent() {
+ var ch, waiting, last = index;
+
+ waiting = false;
+ while (last < length) {
+ ch = source.charCodeAt(last);
+ if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(last + 1) === 0x0A /* '\n' */)) {
+ lineNumber += 1;
+ waiting = true;
+ } else if (waiting) {
+ if (ch === 0x40 /* '@' */) {
+ break;
+ }
+ if (!esutils.code.isWhiteSpace(ch)) {
+ waiting = false;
+ }
+ }
+ last += 1;
+ }
+ return last;
+ }
+
+ // type expression may have nest brace, such as,
+ // { { ok: string } }
+ //
+ // therefore, scanning type expression with balancing braces.
+ function parseType(title, last) {
+ var ch, brace, type, direct = false;
+
+
+ // search '{'
+ while (index < last) {
+ ch = source.charCodeAt(index);
+ if (esutils.code.isWhiteSpace(ch)) {
+ advance();
+ } else if (ch === 0x7B /* '{' */) {
+ advance();
+ break;
+ } else {
+ // this is direct pattern
+ direct = true;
+ break;
+ }
+ }
+
+
+ if (direct) {
+ return null;
+ }
+
+ // type expression { is found
+ brace = 1;
+ type = '';
+ while (index < last) {
+ ch = source.charCodeAt(index);
+ if (esutils.code.isLineTerminator(ch)) {
+ advance();
+ } else {
+ if (ch === 0x7D /* '}' */) {
+ brace -= 1;
+ if (brace === 0) {
+ advance();
+ break;
+ }
+ } else if (ch === 0x7B /* '{' */) {
+ brace += 1;
+ }
+ type += advance();
+ }
+ }
+
+ if (brace !== 0) {
+ // braces is not balanced
+ return throwError('Braces are not balanced');
+ }
+
+ if (isParamTitle(title)) {
+ return typed.parseParamType(type);
+ }
+ return typed.parseType(type);
+ }
+
+ function scanIdentifier(last) {
+ var identifier;
+ if (!esutils.code.isIdentifierStart(source.charCodeAt(index))) {
+ return null;
+ }
+ identifier = advance();
+ while (index < last && esutils.code.isIdentifierPart(source.charCodeAt(index))) {
+ identifier += advance();
+ }
+ return identifier;
+ }
+
+ function skipWhiteSpace(last) {
+ while (index < last && (esutils.code.isWhiteSpace(source.charCodeAt(index)) || esutils.code.isLineTerminator(source.charCodeAt(index)))) {
+ advance();
+ }
+ }
+
+ function parseName(last, allowBrackets, allowNestedParams) {
+ var name = '', useBrackets;
+
+ skipWhiteSpace(last);
+
+ if (index >= last) {
+ return null;
+ }
+
+ if (allowBrackets && source.charCodeAt(index) === 0x5B /* '[' */) {
+ useBrackets = true;
+ name = advance();
+ }
+
+ if (!esutils.code.isIdentifierStart(source.charCodeAt(index))) {
+ return null;
+ }
+
+ name += scanIdentifier(last);
+
+ if (allowNestedParams) {
+ while (source.charCodeAt(index) === 0x2E /* '.' */ ||
+ source.charCodeAt(index) === 0x23 /* '#' */ ||
+ source.charCodeAt(index) === 0x7E /* '~' */) {
+ name += advance();
+ name += scanIdentifier(last);
+ }
+ }
+
+ if (useBrackets) {
+ // do we have a default value for this?
+ if (source.charCodeAt(index) === 0x3D /* '=' */) {
+
+ // consume the '='' symbol
+ name += advance();
+ // scan in the default value
+ while (index < last && source.charCodeAt(index) !== 0x5D /* ']' */) {
+ name += advance();
+ }
+ }
+
+ if (index >= last || source.charCodeAt(index) !== 0x5D /* ']' */) {
+ // we never found a closing ']'
+ return null;
+ }
+
+ // collect the last ']'
+ name += advance();
+ }
+
+ return name;
+ }
+
+ function skipToTag() {
+ while (index < length && source.charCodeAt(index) !== 0x40 /* '@' */) {
+ advance();
+ }
+ if (index >= length) {
+ return false;
+ }
+ assert(source.charCodeAt(index) === 0x40 /* '@' */);
+ return true;
+ }
+
+ function TagParser(options, title) {
+ this._options = options;
+ this._title = title;
+ this._tag = {
+ title: title,
+ description: null
+ };
+ if (this._options.lineNumbers) {
+ this._tag.lineNumber = lineNumber;
+ }
+ this._last = 0;
+ // space to save special information for title parsers.
+ this._extra = { };
+ }
+
+ // addError(err, ...)
+ TagParser.prototype.addError = function addError(errorText) {
+ var args = Array.prototype.slice.call(arguments, 1),
+ msg = errorText.replace(
+ /%(\d)/g,
+ function (whole, index) {
+ assert(index < args.length, 'Message reference must be in range');
+ return args[index];
+ }
+ );
+
+ if (!this._tag.errors) {
+ this._tag.errors = [];
+ }
+ if (strict) {
+ throwError(msg);
+ }
+ this._tag.errors.push(msg);
+ return recoverable;
+ };
+
+ TagParser.prototype.parseType = function () {
+ // type required titles
+ if (isTypeParameterRequired(this._title)) {
+ try {
+ this._tag.type = parseType(this._title, this._last);
+ if (!this._tag.type) {
+ if (!isParamTitle(this._title)) {
+ if (!this.addError('Missing or invalid tag type')) {
+ return false;
+ }
+ }
+ }
+ } catch (error) {
+ this._tag.type = null;
+ if (!this.addError(error.message)) {
+ return false;
+ }
+ }
+ } else if (isAllowedType(this._title)) {
+ // optional types
+ try {
+ this._tag.type = parseType(this._title, this._last);
+ } catch (e) {
+ //For optional types, lets drop the thrown error when we hit the end of the file
+ }
+ }
+ return true;
+ };
+
+ TagParser.prototype._parseNamePath = function (optional) {
+ var name;
+ name = parseName(this._last, sloppy && isParamTitle(this._title), true);
+ if (!name) {
+ if (!optional) {
+ if (!this.addError('Missing or invalid tag name')) {
+ return false;
+ }
+ }
+ }
+ this._tag.name = name;
+ return true;
+ };
+
+ TagParser.prototype.parseNamePath = function () {
+ return this._parseNamePath(false);
+ };
+
+ TagParser.prototype.parseNamePathOptional = function () {
+ return this._parseNamePath(true);
+ };
+
+
+ TagParser.prototype.parseName = function () {
+ var assign, name;
+
+ // param, property requires name
+ if (isAllowedName(this._title)) {
+ this._tag.name = parseName(this._last, sloppy && isParamTitle(this._title), isAllowedNested(this._title));
+ if (!this._tag.name) {
+ if (!isNameParameterRequired(this._title)) {
+ return true;
+ }
+
+ // it's possible the name has already been parsed but interpreted as a type
+ // it's also possible this is a sloppy declaration, in which case it will be
+ // fixed at the end
+ if (isParamTitle(this._title) && this._tag.type && this._tag.type.name) {
+ this._extra.name = this._tag.type;
+ this._tag.name = this._tag.type.name;
+ this._tag.type = null;
+ } else {
+ if (!this.addError('Missing or invalid tag name')) {
+ return false;
+ }
+ }
+ } else {
+ name = this._tag.name;
+ if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') {
+ // extract the default value if there is one
+ // example: @param {string} [somebody=John Doe] description
+ assign = name.substring(1, name.length - 1).split('=');
+ if (assign[1]) {
+ this._tag['default'] = assign[1];
+ }
+ this._tag.name = assign[0];
+
+ // convert to an optional type
+ if (this._tag.type && this._tag.type.type !== 'OptionalType') {
+ this._tag.type = {
+ type: 'OptionalType',
+ expression: this._tag.type
+ };
+ }
+ }
+ }
+ }
+
+ return true;
+ };
+
+ TagParser.prototype.parseDescription = function parseDescription() {
+ var description = trim(sliceSource(source, index, this._last));
+ if (description) {
+ if ((/^-\s+/).test(description)) {
+ description = description.substring(2);
+ }
+ this._tag.description = description;
+ }
+ return true;
+ };
+
+ TagParser.prototype.parseKind = function parseKind() {
+ var kind, kinds;
+ kinds = {
+ 'class': true,
+ 'constant': true,
+ 'event': true,
+ 'external': true,
+ 'file': true,
+ 'function': true,
+ 'member': true,
+ 'mixin': true,
+ 'module': true,
+ 'namespace': true,
+ 'typedef': true
+ };
+ kind = trim(sliceSource(source, index, this._last));
+ this._tag.kind = kind;
+ if (!hasOwnProperty(kinds, kind)) {
+ if (!this.addError('Invalid kind name \'%0\'', kind)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ TagParser.prototype.parseAccess = function parseAccess() {
+ var access;
+ access = trim(sliceSource(source, index, this._last));
+ this._tag.access = access;
+ if (access !== 'private' && access !== 'protected' && access !== 'public') {
+ if (!this.addError('Invalid access name \'%0\'', access)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ TagParser.prototype.parseVariation = function parseVariation() {
+ var variation, text;
+ text = trim(sliceSource(source, index, this._last));
+ variation = parseFloat(text, 10);
+ this._tag.variation = variation;
+ if (isNaN(variation)) {
+ if (!this.addError('Invalid variation \'%0\'', text)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ TagParser.prototype.ensureEnd = function () {
+ var shouldBeEmpty = trim(sliceSource(source, index, this._last));
+ if (shouldBeEmpty) {
+ if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ TagParser.prototype.epilogue = function epilogue() {
+ var description;
+
+ description = this._tag.description;
+ // un-fix potentially sloppy declaration
+ if (isParamTitle(this._title) && !this._tag.type && description && description.charAt(0) === '[') {
+ this._tag.type = this._extra.name;
+ this._tag.name = undefined;
+
+ if (!sloppy) {
+ if (!this.addError('Missing or invalid tag name')) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ };
+
+ Rules = {
+ // http://usejsdoc.org/tags-access.html
+ 'access': ['parseAccess'],
+ // http://usejsdoc.org/tags-alias.html
+ 'alias': ['parseNamePath', 'ensureEnd'],
+ // http://usejsdoc.org/tags-augments.html
+ 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-constructor.html
+ 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // Synonym: http://usejsdoc.org/tags-constructor.html
+ 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // Synonym: http://usejsdoc.org/tags-extends.html
+ 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-deprecated.html
+ 'deprecated': ['parseDescription'],
+ // http://usejsdoc.org/tags-global.html
+ 'global': ['ensureEnd'],
+ // http://usejsdoc.org/tags-inner.html
+ 'inner': ['ensureEnd'],
+ // http://usejsdoc.org/tags-instance.html
+ 'instance': ['ensureEnd'],
+ // http://usejsdoc.org/tags-kind.html
+ 'kind': ['parseKind'],
+ // http://usejsdoc.org/tags-mixes.html
+ 'mixes': ['parseNamePath', 'ensureEnd'],
+ // http://usejsdoc.org/tags-mixin.html
+ 'mixin': ['parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-member.html
+ 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-method.html
+ 'method': ['parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-module.html
+ 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // Synonym: http://usejsdoc.org/tags-method.html
+ 'func': ['parseNamePathOptional', 'ensureEnd'],
+ // Synonym: http://usejsdoc.org/tags-method.html
+ 'function': ['parseNamePathOptional', 'ensureEnd'],
+ // Synonym: http://usejsdoc.org/tags-member.html
+ 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-name.html
+ 'name': ['parseNamePath', 'ensureEnd'],
+ // http://usejsdoc.org/tags-namespace.html
+ 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'],
+ // http://usejsdoc.org/tags-private.html
+ 'private': ['parseType', 'parseDescription'],
+ // http://usejsdoc.org/tags-protected.html
+ 'protected': ['parseType', 'parseDescription'],
+ // http://usejsdoc.org/tags-public.html
+ 'public': ['parseType', 'parseDescription'],
+ // http://usejsdoc.org/tags-readonly.html
+ 'readonly': ['ensureEnd'],
+ // http://usejsdoc.org/tags-requires.html
+ 'requires': ['parseNamePath', 'ensureEnd'],
+ // http://usejsdoc.org/tags-since.html
+ 'since': ['parseDescription'],
+ // http://usejsdoc.org/tags-static.html
+ 'static': ['ensureEnd'],
+ // http://usejsdoc.org/tags-summary.html
+ 'summary': ['parseDescription'],
+ // http://usejsdoc.org/tags-this.html
+ 'this': ['parseNamePath', 'ensureEnd'],
+ // http://usejsdoc.org/tags-todo.html
+ 'todo': ['parseDescription'],
+ // http://usejsdoc.org/tags-variation.html
+ 'variation': ['parseVariation'],
+ // http://usejsdoc.org/tags-version.html
+ 'version': ['parseDescription']
+ };
+
+ TagParser.prototype.parse = function parse() {
+ var i, iz, sequences, method;
+
+ // empty title
+ if (!this._title) {
+ if (!this.addError('Missing or invalid title')) {
+ return null;
+ }
+ }
+
+ // Seek to content last index.
+ this._last = seekContent(this._title);
+
+ if (hasOwnProperty(Rules, this._title)) {
+ sequences = Rules[this._title];
+ } else {
+ // default sequences
+ sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue'];
+ }
+
+ for (i = 0, iz = sequences.length; i < iz; ++i) {
+ method = sequences[i];
+ if (!this[method]()) {
+ return null;
+ }
+ }
+
+ // Seek global index to end of this tag.
+ index = this._last;
+ return this._tag;
+ };
+
+ function parseTag(options) {
+ var title, parser;
+
+ // skip to tag
+ if (!skipToTag()) {
+ return null;
+ }
+
+ // scan title
+ title = scanTitle();
+
+ // construct tag parser
+ parser = new TagParser(options, title);
+ return parser.parse();
+ }
+
+ //
+ // Parse JSDoc
+ //
+
+ function scanJSDocDescription() {
+ var description = '', ch, atAllowed;
+
+ atAllowed = true;
+ while (index < length) {
+ ch = source.charCodeAt(index);
+
+ if (atAllowed && ch === 0x40 /* '@' */) {
+ break;
+ }
+
+ if (esutils.code.isLineTerminator(ch)) {
+ atAllowed = true;
+ } else if (atAllowed && !esutils.code.isWhiteSpace(ch)) {
+ atAllowed = false;
+ }
+
+ description += advance();
+ }
+ return trim(description);
+ }
+
+ function parse(comment, options) {
+ var tags = [], tag, description, interestingTags, i, iz;
+
+ if (options === undefined) {
+ options = {};
+ }
+
+ if (typeof options.unwrap === 'boolean' && options.unwrap) {
+ source = unwrapComment(comment);
+ } else {
+ source = comment;
+ }
+
+ // array of relevant tags
+ if (options.tags) {
+ if (isArray(options.tags)) {
+ interestingTags = { };
+ for (i = 0, iz = options.tags.length; i < iz; i++) {
+ if (typeof options.tags[i] === 'string') {
+ interestingTags[options.tags[i]] = true;
+ } else {
+ throwError('Invalid "tags" parameter: ' + options.tags);
+ }
+ }
+ } else {
+ throwError('Invalid "tags" parameter: ' + options.tags);
+ }
+ }
+
+ length = source.length;
+ index = 0;
+ lineNumber = 0;
+ recoverable = options.recoverable;
+ sloppy = options.sloppy;
+ strict = options.strict;
+
+ description = scanJSDocDescription();
+
+ while (true) {
+ tag = parseTag(options);
+ if (!tag) {
+ break;
+ }
+ if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) {
+ tags.push(tag);
+ }
+ }
+
+ return {
+ description: description,
+ tags: tags
+ };
+ }
+ exports.parse = parse;
+ }(jsdoc = {}));
+
+ exports.version = VERSION;
+ exports.parse = jsdoc.parse;
+ exports.parseType = typed.parseType;
+ exports.parseParamType = typed.parseParamType;
+ exports.unwrapComment = unwrapComment;
+ exports.Syntax = shallowCopy(typed.Syntax);
+ exports.Error = DoctrineError;
+ exports.type = {
+ Syntax: exports.Syntax,
+ parseType: typed.parseType,
+ parseParamType: typed.parseParamType,
+ stringify: typed.stringify
+ };
+}());
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{"./package.json":10,"esutils":9}],6:[function(require,module,exports){
+/*
+ Copyright (C) 2013 Yusuke Suzuki
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+(function () {
+ 'use strict';
+
+ function isExpression(node) {
+ if (node == null) { return false; }
+ switch (node.type) {
+ case 'ArrayExpression':
+ case 'AssignmentExpression':
+ case 'BinaryExpression':
+ case 'CallExpression':
+ case 'ConditionalExpression':
+ case 'FunctionExpression':
+ case 'Identifier':
+ case 'Literal':
+ case 'LogicalExpression':
+ case 'MemberExpression':
+ case 'NewExpression':
+ case 'ObjectExpression':
+ case 'SequenceExpression':
+ case 'ThisExpression':
+ case 'UnaryExpression':
+ case 'UpdateExpression':
+ return true;
+ }
+ return false;
+ }
+
+ function isIterationStatement(node) {
+ if (node == null) { return false; }
+ switch (node.type) {
+ case 'DoWhileStatement':
+ case 'ForInStatement':
+ case 'ForStatement':
+ case 'WhileStatement':
+ return true;
+ }
+ return false;
+ }
+
+ function isStatement(node) {
+ if (node == null) { return false; }
+ switch (node.type) {
+ case 'BlockStatement':
+ case 'BreakStatement':
+ case 'ContinueStatement':
+ case 'DebuggerStatement':
+ case 'DoWhileStatement':
+ case 'EmptyStatement':
+ case 'ExpressionStatement':
+ case 'ForInStatement':
+ case 'ForStatement':
+ case 'IfStatement':
+ case 'LabeledStatement':
+ case 'ReturnStatement':
+ case 'SwitchStatement':
+ case 'ThrowStatement':
+ case 'TryStatement':
+ case 'VariableDeclaration':
+ case 'WhileStatement':
+ case 'WithStatement':
+ return true;
+ }
+ return false;
+ }
+
+ function isSourceElement(node) {
+ return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
+ }
+
+ function trailingStatement(node) {
+ switch (node.type) {
+ case 'IfStatement':
+ if (node.alternate != null) {
+ return node.alternate;
+ }
+ return node.consequent;
+
+ case 'LabeledStatement':
+ case 'ForStatement':
+ case 'ForInStatement':
+ case 'WhileStatement':
+ case 'WithStatement':
+ return node.body;
+ }
+ return null;
+ }
+
+ function isProblematicIfStatement(node) {
+ var current;
+
+ if (node.type !== 'IfStatement') {
+ return false;
+ }
+ if (node.alternate == null) {
+ return false;
+ }
+ current = node.consequent;
+ do {
+ if (current.type === 'IfStatement') {
+ if (current.alternate == null) {
+ return true;
+ }
+ }
+ current = trailingStatement(current);
+ } while (current);
+
+ return false;
+ }
+
+ module.exports = {
+ isExpression: isExpression,
+ isStatement: isStatement,
+ isIterationStatement: isIterationStatement,
+ isSourceElement: isSourceElement,
+ isProblematicIfStatement: isProblematicIfStatement,
+
+ trailingStatement: trailingStatement
+ };
+}());
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{}],7:[function(require,module,exports){
+/*
+ Copyright (C) 2013-2014 Yusuke Suzuki
+ Copyright (C) 2014 Ivan Nikulin
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+(function () {
+ 'use strict';
+
+ var Regex, NON_ASCII_WHITESPACES;
+
+ // See `tools/generate-identifier-regex.js`.
+ Regex = {
+ NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'),
+ NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]')
+ };
+
+ function isDecimalDigit(ch) {
+ return (ch >= 48 && ch <= 57); // 0..9
+ }
+
+ function isHexDigit(ch) {
+ return isDecimalDigit(ch) || // 0..9
+ (97 <= ch && ch <= 102) || // a..f
+ (65 <= ch && ch <= 70); // A..F
+ }
+
+ function isOctalDigit(ch) {
+ return (ch >= 48 && ch <= 55); // 0..7
+ }
+
+ // 7.2 White Space
+
+ NON_ASCII_WHITESPACES = [
+ 0x1680, 0x180E,
+ 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
+ 0x202F, 0x205F,
+ 0x3000,
+ 0xFEFF
+ ];
+
+ function isWhiteSpace(ch) {
+ return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
+ (ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0);
+ }
+
+ // 7.3 Line Terminators
+
+ function isLineTerminator(ch) {
+ return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
+ }
+
+ // 7.6 Identifier Names and Identifiers
+
+ function isIdentifierStart(ch) {
+ return (ch >= 97 && ch <= 122) || // a..z
+ (ch >= 65 && ch <= 90) || // A..Z
+ (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
+ (ch === 92) || // \ (backslash)
+ ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
+ }
+
+ function isIdentifierPart(ch) {
+ return (ch >= 97 && ch <= 122) || // a..z
+ (ch >= 65 && ch <= 90) || // A..Z
+ (ch >= 48 && ch <= 57) || // 0..9
+ (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
+ (ch === 92) || // \ (backslash)
+ ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
+ }
+
+ module.exports = {
+ isDecimalDigit: isDecimalDigit,
+ isHexDigit: isHexDigit,
+ isOctalDigit: isOctalDigit,
+ isWhiteSpace: isWhiteSpace,
+ isLineTerminator: isLineTerminator,
+ isIdentifierStart: isIdentifierStart,
+ isIdentifierPart: isIdentifierPart
+ };
+}());
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{}],8:[function(require,module,exports){
+/*
+ Copyright (C) 2013 Yusuke Suzuki
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+(function () {
+ 'use strict';
+
+ var code = require('./code');
+
+ function isStrictModeReservedWordES6(id) {
+ switch (id) {
+ case 'implements':
+ case 'interface':
+ case 'package':
+ case 'private':
+ case 'protected':
+ case 'public':
+ case 'static':
+ case 'let':
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ function isKeywordES5(id, strict) {
+ // yield should not be treated as keyword under non-strict mode.
+ if (!strict && id === 'yield') {
+ return false;
+ }
+ return isKeywordES6(id, strict);
+ }
+
+ function isKeywordES6(id, strict) {
+ if (strict && isStrictModeReservedWordES6(id)) {
+ return true;
+ }
+
+ switch (id.length) {
+ case 2:
+ return (id === 'if') || (id === 'in') || (id === 'do');
+ case 3:
+ return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
+ case 4:
+ return (id === 'this') || (id === 'else') || (id === 'case') ||
+ (id === 'void') || (id === 'with') || (id === 'enum');
+ case 5:
+ return (id === 'while') || (id === 'break') || (id === 'catch') ||
+ (id === 'throw') || (id === 'const') || (id === 'yield') ||
+ (id === 'class') || (id === 'super');
+ case 6:
+ return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
+ (id === 'switch') || (id === 'export') || (id === 'import');
+ case 7:
+ return (id === 'default') || (id === 'finally') || (id === 'extends');
+ case 8:
+ return (id === 'function') || (id === 'continue') || (id === 'debugger');
+ case 10:
+ return (id === 'instanceof');
+ default:
+ return false;
+ }
+ }
+
+ function isReservedWordES5(id, strict) {
+ return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
+ }
+
+ function isReservedWordES6(id, strict) {
+ return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
+ }
+
+ function isRestrictedWord(id) {
+ return id === 'eval' || id === 'arguments';
+ }
+
+ function isIdentifierName(id) {
+ var i, iz, ch;
+
+ if (id.length === 0) {
+ return false;
+ }
+
+ ch = id.charCodeAt(0);
+ if (!code.isIdentifierStart(ch) || ch === 92) { // \ (backslash)
+ return false;
+ }
+
+ for (i = 1, iz = id.length; i < iz; ++i) {
+ ch = id.charCodeAt(i);
+ if (!code.isIdentifierPart(ch) || ch === 92) { // \ (backslash)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ function isIdentifierES5(id, strict) {
+ return isIdentifierName(id) && !isReservedWordES5(id, strict);
+ }
+
+ function isIdentifierES6(id, strict) {
+ return isIdentifierName(id) && !isReservedWordES6(id, strict);
+ }
+
+ module.exports = {
+ isKeywordES5: isKeywordES5,
+ isKeywordES6: isKeywordES6,
+ isReservedWordES5: isReservedWordES5,
+ isReservedWordES6: isReservedWordES6,
+ isRestrictedWord: isRestrictedWord,
+ isIdentifierName: isIdentifierName,
+ isIdentifierES5: isIdentifierES5,
+ isIdentifierES6: isIdentifierES6
+ };
+}());
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{"./code":7}],9:[function(require,module,exports){
+/*
+ Copyright (C) 2013 Yusuke Suzuki
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+
+(function () {
+ 'use strict';
+
+ exports.ast = require('./ast');
+ exports.code = require('./code');
+ exports.keyword = require('./keyword');
+}());
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{"./ast":6,"./code":7,"./keyword":8}],10:[function(require,module,exports){
+module.exports={
+ "name": "doctrine",
+ "description": "JSDoc parser",
+ "homepage": "http://github.com/Constellation/doctrine.html",
+ "main": "doctrine.js",
+ "version": "0.6.2",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "maintainers": [
+ {
+ "name": "Yusuke Suzuki",
+ "email": "utatane.tea@gmail.com",
+ "url": "http://github.com/Constellation"
+ }
+ ],
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/Constellation/doctrine.git"
+ },
+ "devDependencies": {
+ "gulp": "^3.8.10",
+ "gulp-eslint": "^0.1.8",
+ "gulp-istanbul": "^0.3.1",
+ "gulp-jshint": "^1.9.0",
+ "gulp-mocha": "^1.1.1",
+ "jshint-stylish": "^1.0.0",
+ "should": "^4.1.0"
+ },
+ "licenses": [
+ {
+ "type": "BSD",
+ "url": "http://github.com/Constellation/doctrine/raw/master/LICENSE.BSD"
+ }
+ ],
+ "scripts": {
+ "test": "gulp",
+ "unit-test": "gulp test",
+ "lint": "gulp lint"
+ },
+ "dependencies": {
+ "esutils": "^1.1.4"
+ },
+ "readme": "doctrine ([doctrine](http://github.com/Constellation/doctrine)) is JSDoc parser. [![Build Status](https://secure.travis-ci.org/Constellation/doctrine.png)](http://travis-ci.org/Constellation/doctrine)\n\nIt is now used by content assist system of [Eclipse Orion](http://www.eclipse.org/orion/) ([detail](http://planetorion.org/news/2012/10/orion-1-0-release/))\n\nDoctrine can be used in a web browser:\n\n \n\nor in a Node.js application via the package manager:\n\n npm install doctrine\n\nsimple example:\n\n doctrine.parse(\n [\n \"/**\",\n \" * This function comment is parsed by doctrine\",\n \" * @param {{ok:String}} userName\",\n \"*/\"\n ].join('\\n'), { unwrap: true });\n\nand gets following information\n\n {\n \"description\": \"This function comment is parsed by doctrine\",\n \"tags\": [\n {\n \"title\": \"param\",\n \"description\": null,\n \"type\": {\n \"type\": \"RecordType\",\n \"fields\": [\n {\n \"type\": \"FieldType\",\n \"key\": \"ok\",\n \"value\": {\n \"type\": \"NameExpression\",\n \"name\": \"String\"\n }\n }\n ]\n },\n \"name\": \"userName\"\n }\n ]\n }\n\nsee [demo page](http://constellation.github.com/doctrine/demo/index.html) more detail.\n\n### Options\n\n#### doctrine.parse\nWe can pass options to `doctrine.parse(comment, options)`.\n```js\n{\n unwrap: boolean, // default: false\n tags: [ string ] | null, // default: null\n recoverable: boolean, // default: false\n sloppy: boolean, // default: false\n lineNumbers: boolean // default: false\n}\n```\n\n##### unwrap\n\nWhen `unwrap` is `true`, doctrine attempt to unwrap comment specific string from a provided comment text. (removes `/**`, `*/` and `*`)\nFor example, `unwrap` transforms\n```\n/**\n * @param use\n */\n```\nto\n```\n@param use\n```\nIf a provided comment has these comment specific strings, you need to specify this `unwrap` option to `true`.\n\n##### tags\n\nWhen `tags` array is specified, doctrine only produce tags that is specified in this array.\nFor example, if you specify `[ 'param' ]`, doctrine only produces `param` tags.\nIf null is specified, doctrine produces all tags that doctrine can recognize.\n\n##### recoverable\n\nWhen `recoverable` is `true`, doctrine becomes `recoverable` - When failing to parse jsdoc comment, doctrine recovers its state and attempt to continue parsing.\n\n##### sloppy\n\nWhen `sloppy` is `true`,\n```\n@param String [foo]\n```\n's `[foo]` is interpreted as a optional parameter, not interpreted as a name of this `@param`.\n\n##### lineNumbers\n\nWhen `lineNumbers` is `true`, parsed tags will include a `lineNumber` property indicating the line (relative to the start of the comment block) where each tag is located in the source. So, given the following comment:\n```\n/**\n * @param {String} foo\n * @return {number}\n */\n```\nThe `@param` tag will have `lineNumber: 1`, and the `@return` tag will have `lineNumber: 2`.\n\n\n### License\n\n#### doctrine\n\nCopyright (C) 2012 [Yusuke Suzuki](http://github.com/Constellation)\n (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#### esprima\n\nsome of functions is derived from esprima\n\nCopyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about)\n (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n#### closure-compiler\n\nsome of extensions is derived from closure-compiler\n\nApache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n",
+ "readmeFilename": "README.md",
+ "bugs": {
+ "url": "https://github.com/Constellation/doctrine/issues"
+ },
+ "_id": "doctrine@0.6.2",
+ "_shasum": "a7f3ddbf8ce79d1cd230388ee21035e2fd4ce394",
+ "_from": "doctrine@^0.6.2",
+ "_resolved": "https://registry.npmjs.org/doctrine/-/doctrine-0.6.2.tgz"
+}
+
+},{}],11:[function(require,module,exports){
+'use strict';
+
+var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
+
+module.exports = function (str) {
+ if (typeof str !== 'string') {
+ throw new TypeError('Expected a string');
+ }
+
+ return str.replace(matchOperatorsRe, '\\$&');
+};
+
+},{}],12:[function(require,module,exports){
+/*
+ Copyright (C) 2012-2013 Yusuke Suzuki
+ Copyright (C) 2013 Alex Seville
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * Escope (escope) is an ECMAScript
+ * scope analyzer extracted from the esmangle project.
+ *
+ * escope finds lexical scopes in a source program, i.e. areas of that
+ * program where different occurrences of the same identifier refer to the same
+ * variable. With each scope the contained variables are collected, and each
+ * identifier reference in code is linked to its corresponding variable (if
+ * possible).
+ *
+ * escope works on a syntax tree of the parsed source code which has
+ * to adhere to the
+ * Mozilla Parser API. E.g. esprima is a parser
+ * that produces such syntax trees.
+ *
+ * The main interface is the {@link analyze} function.
+ * @module
+ */
+
+/*jslint bitwise:true */
+/*global exports:true, define:true, require:true*/
+(function (factory, global) {
+ 'use strict';
+
+ function namespace(str, obj) {
+ var i, iz, names, name;
+ names = str.split('.');
+ for (i = 0, iz = names.length; i < iz; ++i) {
+ name = names[i];
+ if (obj.hasOwnProperty(name)) {
+ obj = obj[name];
+ } else {
+ obj = (obj[name] = {});
+ }
+ }
+ return obj;
+ }
+
+ // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
+ // and plain browser loading,
+ if (typeof define === 'function' && define.amd) {
+ define('escope', ['exports', 'estraverse'], function (exports, estraverse) {
+ factory(exports, global, estraverse);
+ });
+ } else if (typeof exports !== 'undefined') {
+ factory(exports, global, require('estraverse'));
+ } else {
+ factory(namespace('escope', global), global, global.estraverse);
+ }
+}(function (exports, global, estraverse) {
+ 'use strict';
+
+ var Syntax,
+ Map,
+ currentScope,
+ globalScope,
+ scopes,
+ options;
+
+ Syntax = estraverse.Syntax;
+
+ if (typeof global.Map !== 'undefined') {
+ // ES6 Map
+ Map = global.Map;
+ } else {
+ Map = function Map() {
+ this.__data = {};
+ };
+
+ Map.prototype.get = function MapGet(key) {
+ key = '$' + key;
+ if (this.__data.hasOwnProperty(key)) {
+ return this.__data[key];
+ }
+ return undefined;
+ };
+
+ Map.prototype.has = function MapHas(key) {
+ key = '$' + key;
+ return this.__data.hasOwnProperty(key);
+ };
+
+ Map.prototype.set = function MapSet(key, val) {
+ key = '$' + key;
+ this.__data[key] = val;
+ };
+
+ Map.prototype['delete'] = function MapDelete(key) {
+ key = '$' + key;
+ return delete this.__data[key];
+ };
+ }
+
+ function assert(cond, text) {
+ if (!cond) {
+ throw new Error(text);
+ }
+ }
+
+ function defaultOptions() {
+ return {
+ optimistic: false,
+ directive: false
+ };
+ }
+
+ function updateDeeply(target, override) {
+ var key, val;
+
+ function isHashObject(target) {
+ return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
+ }
+
+ for (key in override) {
+ if (override.hasOwnProperty(key)) {
+ val = override[key];
+ if (isHashObject(val)) {
+ if (isHashObject(target[key])) {
+ updateDeeply(target[key], val);
+ } else {
+ target[key] = updateDeeply({}, val);
+ }
+ } else {
+ target[key] = val;
+ }
+ }
+ }
+ return target;
+ }
+
+ /**
+ * A Reference represents a single occurrence of an identifier in code.
+ * @class Reference
+ */
+ function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal) {
+ /**
+ * Identifier syntax node.
+ * @member {esprima#Identifier} Reference#identifier
+ */
+ this.identifier = ident;
+ /**
+ * Reference to the enclosing Scope.
+ * @member {Scope} Reference#from
+ */
+ this.from = scope;
+ /**
+ * Whether the reference comes from a dynamic scope (such as 'eval',
+ * 'with', etc.), and may be trapped by dynamic scopes.
+ * @member {boolean} Reference#tainted
+ */
+ this.tainted = false;
+ /**
+ * The variable this reference is resolved with.
+ * @member {Variable} Reference#resolved
+ */
+ this.resolved = null;
+ /**
+ * The read-write mode of the reference. (Value is one of {@link
+ * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).
+ * @member {number} Reference#flag
+ * @private
+ */
+ this.flag = flag;
+ if (this.isWrite()) {
+ /**
+ * If reference is writeable, this is the tree being written to it.
+ * @member {esprima#Node} Reference#writeExpr
+ */
+ this.writeExpr = writeExpr;
+ }
+ /**
+ * Whether the Reference might refer to a global variable.
+ * @member {boolean} Reference#__maybeImplicitGlobal
+ * @private
+ */
+ this.__maybeImplicitGlobal = maybeImplicitGlobal;
+ }
+
+ /**
+ * @constant Reference.READ
+ * @private
+ */
+ Reference.READ = 0x1;
+ /**
+ * @constant Reference.WRITE
+ * @private
+ */
+ Reference.WRITE = 0x2;
+ /**
+ * @constant Reference.RW
+ * @private
+ */
+ Reference.RW = 0x3;
+
+ /**
+ * Whether the reference is static.
+ * @method Reference#isStatic
+ * @return {boolean}
+ */
+ Reference.prototype.isStatic = function isStatic() {
+ return !this.tainted && this.resolved && this.resolved.scope.isStatic();
+ };
+
+ /**
+ * Whether the reference is writeable.
+ * @method Reference#isWrite
+ * @return {boolean}
+ */
+ Reference.prototype.isWrite = function isWrite() {
+ return this.flag & Reference.WRITE;
+ };
+
+ /**
+ * Whether the reference is readable.
+ * @method Reference#isRead
+ * @return {boolean}
+ */
+ Reference.prototype.isRead = function isRead() {
+ return this.flag & Reference.READ;
+ };
+
+ /**
+ * Whether the reference is read-only.
+ * @method Reference#isReadOnly
+ * @return {boolean}
+ */
+ Reference.prototype.isReadOnly = function isReadOnly() {
+ return this.flag === Reference.READ;
+ };
+
+ /**
+ * Whether the reference is write-only.
+ * @method Reference#isWriteOnly
+ * @return {boolean}
+ */
+ Reference.prototype.isWriteOnly = function isWriteOnly() {
+ return this.flag === Reference.WRITE;
+ };
+
+ /**
+ * Whether the reference is read-write.
+ * @method Reference#isReadWrite
+ * @return {boolean}
+ */
+ Reference.prototype.isReadWrite = function isReadWrite() {
+ return this.flag === Reference.RW;
+ };
+
+ /**
+ * A Variable represents a locally scoped identifier. These include arguments to
+ * functions.
+ * @class Variable
+ */
+ function Variable(name, scope) {
+ /**
+ * The variable name, as given in the source code.
+ * @member {String} Variable#name
+ */
+ this.name = name;
+ /**
+ * List of defining occurrences of this variable (like in 'var ...'
+ * statements or as parameter), as AST nodes.
+ * @member {esprima.Identifier[]} Variable#identifiers
+ */
+ this.identifiers = [];
+ /**
+ * List of {@link Reference|references} of this variable (excluding parameter entries)
+ * in its defining scope and all nested scopes. For defining
+ * occurrences only see {@link Variable#defs}.
+ * @member {Reference[]} Variable#references
+ */
+ this.references = [];
+
+ /**
+ * List of defining occurrences of this variable (like in 'var ...'
+ * statements or as parameter), as custom objects.
+ * @typedef {Object} DefEntry
+ * @property {String} DefEntry.type - the type of the occurrence (e.g.
+ * "Parameter", "Variable", ...)
+ * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence
+ * @property {esprima.Node} DefEntry.node - the enclosing node of the
+ * identifier
+ * @property {esprima.Node} [DefEntry.parent] - the enclosing statement
+ * node of the identifier
+ * @member {DefEntry[]} Variable#defs
+ */
+ this.defs = [];
+
+ this.tainted = false;
+ /**
+ * Whether this is a stack variable.
+ * @member {boolean} Variable#stack
+ */
+ this.stack = true;
+ /**
+ * Reference to the enclosing Scope.
+ * @member {Scope} Variable#scope
+ */
+ this.scope = scope;
+ }
+
+ Variable.CatchClause = 'CatchClause';
+ Variable.Parameter = 'Parameter';
+ Variable.FunctionName = 'FunctionName';
+ Variable.Variable = 'Variable';
+ Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable';
+
+ function isStrictScope(scope, block) {
+ var body, i, iz, stmt, expr;
+
+ // When upper scope is exists and strict, inner scope is also strict.
+ if (scope.upper && scope.upper.isStrict) {
+ return true;
+ }
+
+ if (scope.type === 'function') {
+ body = block.body;
+ } else if (scope.type === 'global') {
+ body = block;
+ } else {
+ return false;
+ }
+
+ if (options.directive) {
+ for (i = 0, iz = body.body.length; i < iz; ++i) {
+ stmt = body.body[i];
+ if (stmt.type !== 'DirectiveStatement') {
+ break;
+ }
+ if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') {
+ return true;
+ }
+ }
+ } else {
+ for (i = 0, iz = body.body.length; i < iz; ++i) {
+ stmt = body.body[i];
+ if (stmt.type !== Syntax.ExpressionStatement) {
+ break;
+ }
+ expr = stmt.expression;
+ if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') {
+ break;
+ }
+ if (expr.raw != null) {
+ if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') {
+ return true;
+ }
+ } else {
+ if (expr.value === 'use strict') {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @class Scope
+ */
+ function Scope(block, opt) {
+ var variable, body;
+
+ /**
+ * One of 'catch', 'with', 'function' or 'global'.
+ * @member {String} Scope#type
+ */
+ this.type =
+ (block.type === Syntax.CatchClause) ? 'catch' :
+ (block.type === Syntax.WithStatement) ? 'with' :
+ (block.type === Syntax.Program) ? 'global' : 'function';
+ /**
+ * The scoped {@link Variable}s of this scope, as { Variable.name
+ * : Variable }.
+ * @member {Map} Scope#set
+ */
+ this.set = new Map();
+ /**
+ * The tainted variables of this scope, as { Variable.name :
+ * boolean }.
+ * @member {Map} Scope#taints */
+ this.taints = new Map();
+ /**
+ * Generally, through the lexical scoping of JS you can always know
+ * which variable an identifier in the source code refers to. There are
+ * a few exceptions to this rule. With 'global' and 'with' scopes you
+ * can only decide at runtime which variable a reference refers to.
+ * Moreover, if 'eval()' is used in a scope, it might introduce new
+ * bindings in this or its prarent scopes.
+ * All those scopes are considered 'dynamic'.
+ * @member {boolean} Scope#dynamic
+ */
+ this.dynamic = this.type === 'global' || this.type === 'with';
+ /**
+ * A reference to the scope-defining syntax node.
+ * @member {esprima.Node} Scope#block
+ */
+ this.block = block;
+ /**
+ * The {@link Reference|references} that are not resolved with this scope.
+ * @member {Reference[]} Scope#through
+ */
+ this.through = [];
+ /**
+ * The scoped {@link Variable}s of this scope. In the case of a
+ * 'function' scope this includes the automatic argument arguments as
+ * its first element, as well as all further formal arguments.
+ * @member {Variable[]} Scope#variables
+ */
+ this.variables = [];
+ /**
+ * Any variable {@link Reference|reference} found in this scope. This
+ * includes occurrences of local variables as well as variables from
+ * parent scopes (including the global scope). For local variables
+ * this also includes defining occurrences (like in a 'var' statement).
+ * In a 'function' scope this does not include the occurrences of the
+ * formal parameter in the parameter list.
+ * @member {Reference[]} Scope#references
+ */
+ this.references = [];
+ /**
+ * List of {@link Reference}s that are left to be resolved (i.e. which
+ * need to be linked to the variable they refer to). Used internally to
+ * resolve bindings during scope analysis. On a finalized scope
+ * analysis, all sopes have left value null.
+ * @member {Reference[]} Scope#left
+ */
+ this.left = [];
+ /**
+ * For 'global' and 'function' scopes, this is a self-reference. For
+ * other scope types this is the variableScope value of the
+ * parent scope.
+ * @member {Scope} Scope#variableScope
+ */
+ this.variableScope =
+ (this.type === 'global' || this.type === 'function') ? this : currentScope.variableScope;
+ /**
+ * Whether this scope is created by a FunctionExpression.
+ * @member {boolean} Scope#functionExpressionScope
+ */
+ this.functionExpressionScope = false;
+ /**
+ * Whether this is a scope that contains an 'eval()' invocation.
+ * @member {boolean} Scope#directCallToEvalScope
+ */
+ this.directCallToEvalScope = false;
+ /**
+ * @member {boolean} Scope#thisFound
+ */
+ this.thisFound = false;
+ body = this.type === 'function' ? block.body : block;
+ if (opt.naming) {
+ this.__define(block.id, {
+ type: Variable.FunctionName,
+ name: block.id,
+ node: block
+ });
+ this.functionExpressionScope = true;
+ } else {
+ if (this.type === 'function') {
+ variable = new Variable('arguments', this);
+ this.taints.set('arguments', true);
+ this.set.set('arguments', variable);
+ this.variables.push(variable);
+ }
+
+ if (block.type === Syntax.FunctionExpression && block.id) {
+ new Scope(block, { naming: true });
+ }
+ }
+
+ /**
+ * Reference to the parent {@link Scope|scope}.
+ * @member {Scope} Scope#upper
+ */
+ this.upper = currentScope;
+ /**
+ * Whether 'use strict' is in effect in this scope.
+ * @member {boolean} Scope#isStrict
+ */
+ this.isStrict = isStrictScope(this, block);
+
+ /**
+ * List of nested {@link Scope}s.
+ * @member {Scope[]} Scope#childScopes
+ */
+ this.childScopes = [];
+ if (currentScope) {
+ currentScope.childScopes.push(this);
+ }
+
+
+ // RAII
+ currentScope = this;
+ if (this.type === 'global') {
+ globalScope = this;
+ globalScope.implicit = {
+ set: new Map(),
+ variables: []
+ };
+ }
+ scopes.push(this);
+ }
+
+ Scope.prototype.__close = function __close() {
+ var i, iz, ref, current, node, implicit;
+
+ // Because if this is global environment, upper is null
+ if (!this.dynamic || options.optimistic) {
+ // static resolve
+ for (i = 0, iz = this.left.length; i < iz; ++i) {
+ ref = this.left[i];
+ if (!this.__resolve(ref)) {
+ this.__delegateToUpperScope(ref);
+ }
+ }
+ } else {
+ // this is "global" / "with" / "function with eval" environment
+ if (this.type === 'with') {
+ for (i = 0, iz = this.left.length; i < iz; ++i) {
+ ref = this.left[i];
+ ref.tainted = true;
+ this.__delegateToUpperScope(ref);
+ }
+ } else {
+ for (i = 0, iz = this.left.length; i < iz; ++i) {
+ // notify all names are through to global
+ ref = this.left[i];
+ current = this;
+ do {
+ current.through.push(ref);
+ current = current.upper;
+ } while (current);
+ }
+ }
+ }
+
+ if (this.type === 'global') {
+ implicit = [];
+ for (i = 0, iz = this.left.length; i < iz; ++i) {
+ ref = this.left[i];
+ if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
+ implicit.push(ref.__maybeImplicitGlobal);
+ }
+ }
+
+ // create an implicit global variable from assignment expression
+ for (i = 0, iz = implicit.length; i < iz; ++i) {
+ node = implicit[i];
+ this.__defineImplicit(node.left, {
+ type: Variable.ImplicitGlobalVariable,
+ name: node.left,
+ node: node
+ });
+ }
+ }
+
+ this.left = null;
+ currentScope = this.upper;
+ };
+
+ Scope.prototype.__resolve = function __resolve(ref) {
+ var variable, name;
+ name = ref.identifier.name;
+ if (this.set.has(name)) {
+ variable = this.set.get(name);
+ variable.references.push(ref);
+ variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
+ if (ref.tainted) {
+ variable.tainted = true;
+ this.taints.set(variable.name, true);
+ }
+ ref.resolved = variable;
+ return true;
+ }
+ return false;
+ };
+
+ Scope.prototype.__delegateToUpperScope = function __delegateToUpperScope(ref) {
+ if (this.upper) {
+ this.upper.left.push(ref);
+ }
+ this.through.push(ref);
+ };
+
+ Scope.prototype.__defineImplicit = function __defineImplicit(node, info) {
+ var name, variable;
+ if (node && node.type === Syntax.Identifier) {
+ name = node.name;
+ if (!this.implicit.set.has(name)) {
+ variable = new Variable(name, this);
+ variable.identifiers.push(node);
+ variable.defs.push(info);
+ this.implicit.set.set(name, variable);
+ this.implicit.variables.push(variable);
+ } else {
+ variable = this.implicit.set.get(name);
+ variable.identifiers.push(node);
+ variable.defs.push(info);
+ }
+ }
+ };
+
+ Scope.prototype.__define = function __define(node, info) {
+ var name, variable;
+ if (node && node.type === Syntax.Identifier) {
+ name = node.name;
+ if (!this.set.has(name)) {
+ variable = new Variable(name, this);
+ variable.identifiers.push(node);
+ variable.defs.push(info);
+ this.set.set(name, variable);
+ this.variables.push(variable);
+ } else {
+ variable = this.set.get(name);
+ variable.identifiers.push(node);
+ variable.defs.push(info);
+ }
+ }
+ };
+
+ Scope.prototype.__referencing = function __referencing(node, assign, writeExpr, maybeImplicitGlobal) {
+ var ref;
+ // because Array element may be null
+ if (node && node.type === Syntax.Identifier) {
+ ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal);
+ this.references.push(ref);
+ this.left.push(ref);
+ }
+ };
+
+ Scope.prototype.__detectEval = function __detectEval() {
+ var current;
+ current = this;
+ this.directCallToEvalScope = true;
+ do {
+ current.dynamic = true;
+ current = current.upper;
+ } while (current);
+ };
+
+ Scope.prototype.__detectThis = function __detectThis() {
+ this.thisFound = true;
+ };
+
+ Scope.prototype.__isClosed = function isClosed() {
+ return this.left === null;
+ };
+
+ // API Scope#resolve(name)
+ // returns resolved reference
+ Scope.prototype.resolve = function resolve(ident) {
+ var ref, i, iz;
+ assert(this.__isClosed(), 'scope should be closed');
+ assert(ident.type === Syntax.Identifier, 'target should be identifier');
+ for (i = 0, iz = this.references.length; i < iz; ++i) {
+ ref = this.references[i];
+ if (ref.identifier === ident) {
+ return ref;
+ }
+ }
+ return null;
+ };
+
+ // API Scope#isStatic
+ // returns this scope is static
+ Scope.prototype.isStatic = function isStatic() {
+ return !this.dynamic;
+ };
+
+ // API Scope#isArgumentsMaterialized
+ // return this scope has materialized arguments
+ Scope.prototype.isArgumentsMaterialized = function isArgumentsMaterialized() {
+ // TODO(Constellation)
+ // We can more aggressive on this condition like this.
+ //
+ // function t() {
+ // // arguments of t is always hidden.
+ // function arguments() {
+ // }
+ // }
+ var variable;
+
+ // This is not function scope
+ if (this.type !== 'function') {
+ return true;
+ }
+
+ if (!this.isStatic()) {
+ return true;
+ }
+
+ variable = this.set.get('arguments');
+ assert(variable, 'always have arguments variable');
+ return variable.tainted || variable.references.length !== 0;
+ };
+
+ // API Scope#isThisMaterialized
+ // return this scope has materialized `this` reference
+ Scope.prototype.isThisMaterialized = function isThisMaterialized() {
+ // This is not function scope
+ if (this.type !== 'function') {
+ return true;
+ }
+ if (!this.isStatic()) {
+ return true;
+ }
+ return this.thisFound;
+ };
+
+ Scope.mangledName = '__$escope$__';
+
+ Scope.prototype.attach = function attach() {
+ if (!this.functionExpressionScope) {
+ this.block[Scope.mangledName] = this;
+ }
+ };
+
+ Scope.prototype.detach = function detach() {
+ if (!this.functionExpressionScope) {
+ delete this.block[Scope.mangledName];
+ }
+ };
+
+ Scope.prototype.isUsedName = function (name) {
+ if (this.set.has(name)) {
+ return true;
+ }
+ for (var i = 0, iz = this.through.length; i < iz; ++i) {
+ if (this.through[i].identifier.name === name) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ /**
+ * @class ScopeManager
+ */
+ function ScopeManager(scopes) {
+ this.scopes = scopes;
+ this.attached = false;
+ }
+
+ // Returns appropliate scope for this node
+ ScopeManager.prototype.__get = function __get(node) {
+ var i, iz, scope;
+ if (this.attached) {
+ return node[Scope.mangledName] || null;
+ }
+ if (Scope.isScopeRequired(node)) {
+ for (i = 0, iz = this.scopes.length; i < iz; ++i) {
+ scope = this.scopes[i];
+ if (!scope.functionExpressionScope) {
+ if (scope.block === node) {
+ return scope;
+ }
+ }
+ }
+ }
+ return null;
+ };
+
+ ScopeManager.prototype.acquire = function acquire(node) {
+ return this.__get(node);
+ };
+
+ ScopeManager.prototype.release = function release(node) {
+ var scope = this.__get(node);
+ if (scope) {
+ scope = scope.upper;
+ while (scope) {
+ if (!scope.functionExpressionScope) {
+ return scope;
+ }
+ scope = scope.upper;
+ }
+ }
+ return null;
+ };
+
+ ScopeManager.prototype.attach = function attach() {
+ var i, iz;
+ for (i = 0, iz = this.scopes.length; i < iz; ++i) {
+ this.scopes[i].attach();
+ }
+ this.attached = true;
+ };
+
+ ScopeManager.prototype.detach = function detach() {
+ var i, iz;
+ for (i = 0, iz = this.scopes.length; i < iz; ++i) {
+ this.scopes[i].detach();
+ }
+ this.attached = false;
+ };
+
+ Scope.isScopeRequired = function isScopeRequired(node) {
+ return Scope.isVariableScopeRequired(node) || node.type === Syntax.WithStatement || node.type === Syntax.CatchClause;
+ };
+
+ Scope.isVariableScopeRequired = function isVariableScopeRequired(node) {
+ return node.type === Syntax.Program || node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration;
+ };
+
+ /**
+ * Main interface function. Takes an Esprima syntax tree and returns the
+ * analyzed scopes.
+ * @function analyze
+ * @param {esprima.Tree} tree
+ * @param {Object} providedOptions - Options that tailor the scope analysis
+ * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag
+ * @param {boolean} [providedOptions.directive=false]- the directive flag
+ * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls
+ * @return {ScopeManager}
+ */
+ function analyze(tree, providedOptions) {
+ var resultScopes;
+
+ options = updateDeeply(defaultOptions(), providedOptions);
+ resultScopes = scopes = [];
+ currentScope = null;
+ globalScope = null;
+
+ // attach scope and collect / resolve names
+ estraverse.traverse(tree, {
+ enter: function enter(node) {
+ var i, iz, decl;
+ if (Scope.isScopeRequired(node)) {
+ new Scope(node, {});
+ }
+
+ switch (node.type) {
+ case Syntax.AssignmentExpression:
+ if (node.operator === '=') {
+ currentScope.__referencing(node.left, Reference.WRITE, node.right, (!currentScope.isStrict && node.left.name != null) && node);
+ } else {
+ currentScope.__referencing(node.left, Reference.RW, node.right);
+ }
+ currentScope.__referencing(node.right);
+ break;
+
+ case Syntax.ArrayExpression:
+ for (i = 0, iz = node.elements.length; i < iz; ++i) {
+ currentScope.__referencing(node.elements[i]);
+ }
+ break;
+
+ case Syntax.BlockStatement:
+ break;
+
+ case Syntax.BinaryExpression:
+ currentScope.__referencing(node.left);
+ currentScope.__referencing(node.right);
+ break;
+
+ case Syntax.BreakStatement:
+ break;
+
+ case Syntax.CallExpression:
+ currentScope.__referencing(node.callee);
+ for (i = 0, iz = node['arguments'].length; i < iz; ++i) {
+ currentScope.__referencing(node['arguments'][i]);
+ }
+
+ // check this is direct call to eval
+ if (!options.ignoreEval && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') {
+ currentScope.variableScope.__detectEval();
+ }
+ break;
+
+ case Syntax.CatchClause:
+ currentScope.__define(node.param, {
+ type: Variable.CatchClause,
+ name: node.param,
+ node: node
+ });
+ break;
+
+ case Syntax.ConditionalExpression:
+ currentScope.__referencing(node.test);
+ currentScope.__referencing(node.consequent);
+ currentScope.__referencing(node.alternate);
+ break;
+
+ case Syntax.ContinueStatement:
+ break;
+
+ case Syntax.DirectiveStatement:
+ break;
+
+ case Syntax.DoWhileStatement:
+ currentScope.__referencing(node.test);
+ break;
+
+ case Syntax.DebuggerStatement:
+ break;
+
+ case Syntax.EmptyStatement:
+ break;
+
+ case Syntax.ExpressionStatement:
+ currentScope.__referencing(node.expression);
+ break;
+
+ case Syntax.ForStatement:
+ currentScope.__referencing(node.init);
+ currentScope.__referencing(node.test);
+ currentScope.__referencing(node.update);
+ break;
+
+ case Syntax.ForInStatement:
+ if (node.left.type === Syntax.VariableDeclaration) {
+ currentScope.__referencing(node.left.declarations[0].id, Reference.WRITE, null, false);
+ } else {
+ currentScope.__referencing(node.left, Reference.WRITE, null, (!currentScope.isStrict && node.left.name != null) && node);
+ }
+ currentScope.__referencing(node.right);
+ break;
+
+ case Syntax.FunctionDeclaration:
+ // FunctionDeclaration name is defined in upper scope
+ currentScope.upper.__define(node.id, {
+ type: Variable.FunctionName,
+ name: node.id,
+ node: node
+ });
+ for (i = 0, iz = node.params.length; i < iz; ++i) {
+ currentScope.__define(node.params[i], {
+ type: Variable.Parameter,
+ name: node.params[i],
+ node: node,
+ index: i
+ });
+ }
+ break;
+
+ case Syntax.FunctionExpression:
+ // id is defined in upper scope
+ for (i = 0, iz = node.params.length; i < iz; ++i) {
+ currentScope.__define(node.params[i], {
+ type: Variable.Parameter,
+ name: node.params[i],
+ node: node,
+ index: i
+ });
+ }
+ break;
+
+ case Syntax.Identifier:
+ break;
+
+ case Syntax.IfStatement:
+ currentScope.__referencing(node.test);
+ break;
+
+ case Syntax.Literal:
+ break;
+
+ case Syntax.LabeledStatement:
+ break;
+
+ case Syntax.LogicalExpression:
+ currentScope.__referencing(node.left);
+ currentScope.__referencing(node.right);
+ break;
+
+ case Syntax.MemberExpression:
+ currentScope.__referencing(node.object);
+ if (node.computed) {
+ currentScope.__referencing(node.property);
+ }
+ break;
+
+ case Syntax.NewExpression:
+ currentScope.__referencing(node.callee);
+ for (i = 0, iz = node['arguments'].length; i < iz; ++i) {
+ currentScope.__referencing(node['arguments'][i]);
+ }
+ break;
+
+ case Syntax.ObjectExpression:
+ break;
+
+ case Syntax.Program:
+ break;
+
+ case Syntax.Property:
+ currentScope.__referencing(node.value);
+ break;
+
+ case Syntax.ReturnStatement:
+ currentScope.__referencing(node.argument);
+ break;
+
+ case Syntax.SequenceExpression:
+ for (i = 0, iz = node.expressions.length; i < iz; ++i) {
+ currentScope.__referencing(node.expressions[i]);
+ }
+ break;
+
+ case Syntax.SwitchStatement:
+ currentScope.__referencing(node.discriminant);
+ break;
+
+ case Syntax.SwitchCase:
+ currentScope.__referencing(node.test);
+ break;
+
+ case Syntax.ThisExpression:
+ currentScope.variableScope.__detectThis();
+ break;
+
+ case Syntax.ThrowStatement:
+ currentScope.__referencing(node.argument);
+ break;
+
+ case Syntax.TryStatement:
+ break;
+
+ case Syntax.UnaryExpression:
+ currentScope.__referencing(node.argument);
+ break;
+
+ case Syntax.UpdateExpression:
+ currentScope.__referencing(node.argument, Reference.RW, null);
+ break;
+
+ case Syntax.VariableDeclaration:
+ for (i = 0, iz = node.declarations.length; i < iz; ++i) {
+ decl = node.declarations[i];
+ currentScope.variableScope.__define(decl.id, {
+ type: Variable.Variable,
+ name: decl.id,
+ node: decl,
+ index: i,
+ parent: node
+ });
+ if (decl.init) {
+ // initializer is found
+ currentScope.__referencing(decl.id, Reference.WRITE, decl.init, false);
+ currentScope.__referencing(decl.init);
+ }
+ }
+ break;
+
+ case Syntax.VariableDeclarator:
+ break;
+
+ case Syntax.WhileStatement:
+ currentScope.__referencing(node.test);
+ break;
+
+ case Syntax.WithStatement:
+ // WithStatement object is referenced at upper scope
+ currentScope.upper.__referencing(node.object);
+ break;
+ }
+ },
+
+ leave: function leave(node) {
+ while (currentScope && node === currentScope.block) {
+ currentScope.__close();
+ }
+ }
+ });
+
+ assert(currentScope === null);
+ globalScope = null;
+ scopes = null;
+ options = null;
+
+ return new ScopeManager(resultScopes);
+ }
+
+ /** @name module:escope.version */
+ exports.version = '1.0.1';
+ /** @name module:escope.Reference */
+ exports.Reference = Reference;
+ /** @name module:escope.Variable */
+ exports.Variable = Variable;
+ /** @name module:escope.Scope */
+ exports.Scope = Scope;
+ /** @name module:escope.ScopeManager */
+ exports.ScopeManager = ScopeManager;
+ /** @name module:escope.analyze */
+ exports.analyze = analyze;
+}, this));
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{"estraverse":22}],13:[function(require,module,exports){
+/*
+Copyright (C) 2013 Ariya Hidayat
+Copyright (C) 2013 Thaddee Tyl
+Copyright (C) 2013 Mathias Bynens
+Copyright (C) 2012 Ariya Hidayat
+Copyright (C) 2012 Mathias Bynens
+Copyright (C) 2012 Joost-Wim Boekesteijn
+Copyright (C) 2012 Kris Kowal
+Copyright (C) 2012 Yusuke Suzuki
+Copyright (C) 2012 Arpad Borsos
+Copyright (C) 2011 Ariya Hidayat
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/*eslint no-undefined:0, no-use-before-define: 0*/
+
+"use strict";
+
+var syntax = require("./lib/syntax"),
+ tokenInfo = require("./lib/token-info"),
+ astNodeTypes = require("./lib/ast-node-types"),
+ astNodeFactory = require("./lib/ast-node-factory"),
+ defaultFeatures = require("./lib/features"),
+ Messages = require("./lib/messages"),
+ XHTMLEntities = require("./lib/xhtml-entities");
+
+var Token = tokenInfo.Token,
+ TokenName = tokenInfo.TokenName,
+ FnExprTokens = tokenInfo.FnExprTokens,
+ Regex = syntax.Regex,
+ PropertyKind,
+ source,
+ strict,
+ index,
+ lineNumber,
+ lineStart,
+ length,
+ lookahead,
+ state,
+ extra;
+
+PropertyKind = {
+ Data: 1,
+ Get: 2,
+ Set: 4
+};
+
+
+// Ensure the condition is true, otherwise throw an error.
+// This is only to have a better contract semantic, i.e. another safety net
+// to catch a logic error. The condition shall be fulfilled in normal case.
+// Do NOT use this to enforce a certain condition on any user input.
+
+function assert(condition, message) {
+ /* istanbul ignore if */
+ if (!condition) {
+ throw new Error("ASSERT: " + message);
+ }
+}
+
+// 7.4 Comments
+
+function addComment(type, value, start, end, loc) {
+ var comment;
+
+ assert(typeof start === "number", "Comment must have valid position");
+
+ // Because the way the actual token is scanned, often the comments
+ // (if any) are skipped twice during the lexical analysis.
+ // Thus, we need to skip adding a comment if the comment array already
+ // handled it.
+ if (state.lastCommentStart >= start) {
+ return;
+ }
+ state.lastCommentStart = start;
+
+ comment = {
+ type: type,
+ value: value
+ };
+ if (extra.range) {
+ comment.range = [start, end];
+ }
+ if (extra.loc) {
+ comment.loc = loc;
+ }
+ extra.comments.push(comment);
+ if (extra.attachComment) {
+ extra.leadingComments.push(comment);
+ extra.trailingComments.push(comment);
+ }
+}
+
+function skipSingleLineComment(offset) {
+ var start, loc, ch, comment;
+
+ start = index - offset;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart - offset
+ }
+ };
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ ++index;
+ if (syntax.isLineTerminator(ch)) {
+ if (extra.comments) {
+ comment = source.slice(start + offset, index - 1);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart - 1
+ };
+ addComment("Line", comment, start, index - 1, loc);
+ }
+ if (ch === 13 && source.charCodeAt(index) === 10) {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ return;
+ }
+ }
+
+ if (extra.comments) {
+ comment = source.slice(start + offset, index);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ addComment("Line", comment, start, index, loc);
+ }
+}
+
+function skipMultiLineComment() {
+ var start, loc, ch, comment;
+
+ if (extra.comments) {
+ start = index - 2;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart - 2
+ }
+ };
+ }
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (syntax.isLineTerminator(ch)) {
+ if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
+ ++index;
+ }
+ ++lineNumber;
+ ++index;
+ lineStart = index;
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ } else if (ch === 0x2A) {
+ // Block comment ends with "*/".
+ if (source.charCodeAt(index + 1) === 0x2F) {
+ ++index;
+ ++index;
+ if (extra.comments) {
+ comment = source.slice(start + 2, index - 2);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ addComment("Block", comment, start, index, loc);
+ }
+ return;
+ }
+ ++index;
+ } else {
+ ++index;
+ }
+ }
+
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+}
+
+function skipComment() {
+ var ch, start;
+
+ start = (index === 0);
+ while (index < length) {
+ ch = source.charCodeAt(index);
+
+ if (syntax.isWhiteSpace(ch)) {
+ ++index;
+ } else if (syntax.isLineTerminator(ch)) {
+ ++index;
+ if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ start = true;
+ } else if (ch === 0x2F) { // U+002F is "/"
+ ch = source.charCodeAt(index + 1);
+ if (ch === 0x2F) {
+ ++index;
+ ++index;
+ skipSingleLineComment(2);
+ start = true;
+ } else if (ch === 0x2A) { // U+002A is "*"
+ ++index;
+ ++index;
+ skipMultiLineComment();
+ } else {
+ break;
+ }
+ } else if (start && ch === 0x2D) { // U+002D is "-"
+ // U+003E is ">"
+ if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
+ // "-->" is a single-line comment
+ index += 3;
+ skipSingleLineComment(3);
+ } else {
+ break;
+ }
+ } else if (ch === 0x3C) { // U+003C is "<"
+ if (source.slice(index + 1, index + 4) === "!--") {
+ ++index; // `<`
+ ++index; // `!`
+ ++index; // `-`
+ ++index; // `-`
+ skipSingleLineComment(4);
+ } else {
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+}
+
+function scanHexEscape(prefix) {
+ var i, len, ch, code = 0;
+
+ len = (prefix === "u") ? 4 : 2;
+ for (i = 0; i < len; ++i) {
+ if (index < length && syntax.isHexDigit(source[index])) {
+ ch = source[index++];
+ code = code * 16 + "0123456789abcdef".indexOf(ch.toLowerCase());
+ } else {
+ return "";
+ }
+ }
+ return String.fromCharCode(code);
+}
+
+function getEscapedIdentifier() {
+ var ch, id;
+
+ ch = source.charCodeAt(index++);
+ id = String.fromCharCode(ch);
+
+ // "\u" (U+005C, U+0075) denotes an escaped character.
+ if (ch === 0x5C) {
+ if (source.charCodeAt(index) !== 0x75) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ ++index;
+ ch = scanHexEscape("u");
+ if (!ch || ch === "\\" || !syntax.isIdentifierStart(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ id = ch;
+ }
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!syntax.isIdentifierPart(ch)) {
+ break;
+ }
+ ++index;
+ id += String.fromCharCode(ch);
+
+ // "\u" (U+005C, U+0075) denotes an escaped character.
+ if (ch === 0x5C) {
+ id = id.substr(0, id.length - 1);
+ if (source.charCodeAt(index) !== 0x75) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ ++index;
+ ch = scanHexEscape("u");
+ if (!ch || ch === "\\" || !syntax.isIdentifierPart(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ id += ch;
+ }
+ }
+
+ return id;
+}
+
+function getIdentifier() {
+ var start, ch;
+
+ start = index++;
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (ch === 0x5C) {
+ // Blackslash (U+005C) marks Unicode escape sequence.
+ index = start;
+ return getEscapedIdentifier();
+ }
+ if (syntax.isIdentifierPart(ch)) {
+ ++index;
+ } else {
+ break;
+ }
+ }
+
+ return source.slice(start, index);
+}
+
+function scanIdentifier() {
+ var start, id, type;
+
+ start = index;
+
+ // Backslash (U+005C) starts an escaped character.
+ id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();
+
+ // There is no keyword or literal with only one character.
+ // Thus, it must be an identifier.
+ if (id.length === 1) {
+ type = Token.Identifier;
+ } else if (syntax.isKeyword(id, strict, extra.ecmaFeatures)) {
+ type = Token.Keyword;
+ } else if (id === "null") {
+ type = Token.NullLiteral;
+ } else if (id === "true" || id === "false") {
+ type = Token.BooleanLiteral;
+ } else {
+ type = Token.Identifier;
+ }
+
+ return {
+ type: type,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+
+// 7.7 Punctuators
+
+function scanPunctuator() {
+ var start = index,
+ code = source.charCodeAt(index),
+ code2,
+ ch1 = source[index],
+ ch2,
+ ch3,
+ ch4;
+
+ switch (code) {
+ // Check for most common single-character punctuators.
+ case 40: // ( open bracket
+ case 41: // ) close bracket
+ case 59: // ; semicolon
+ case 44: // , comma
+ case 123: // { open curly brace
+ case 125: // } close curly brace
+ case 91: // [
+ case 93: // ]
+ case 58: // :
+ case 63: // ?
+ case 126: // ~
+ ++index;
+ if (extra.tokenize) {
+ if (code === 40) {
+ extra.openParenToken = extra.tokens.length;
+ } else if (code === 123) {
+ extra.openCurlyToken = extra.tokens.length;
+ }
+ }
+ return {
+ type: Token.Punctuator,
+ value: String.fromCharCode(code),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+
+ default:
+ code2 = source.charCodeAt(index + 1);
+
+ // "=" (char #61) marks an assignment or comparison operator.
+ if (code2 === 61) {
+ switch (code) {
+ case 37: // %
+ case 38: // &
+ case 42: // *:
+ case 43: // +
+ case 45: // -
+ case 47: // /
+ case 60: // <
+ case 62: // >
+ case 94: // ^
+ case 124: // |
+ index += 2;
+ return {
+ type: Token.Punctuator,
+ value: String.fromCharCode(code) + String.fromCharCode(code2),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+
+ case 33: // !
+ case 61: // =
+ index += 2;
+
+ // !== and ===
+ if (source.charCodeAt(index) === 61) {
+ ++index;
+ }
+ return {
+ type: Token.Punctuator,
+ value: source.slice(start, index),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ default:
+ break;
+ }
+ }
+ break;
+ }
+
+ // Peek more characters.
+
+ ch2 = source[index + 1];
+ ch3 = source[index + 2];
+ ch4 = source[index + 3];
+
+ // 4-character punctuator: >>>=
+
+ if (ch1 === ">" && ch2 === ">" && ch3 === ">") {
+ if (ch4 === "=") {
+ index += 4;
+ return {
+ type: Token.Punctuator,
+ value: ">>>=",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ // 3-character punctuators: === !== >>> <<= >>=
+
+ if (ch1 === ">" && ch2 === ">" && ch3 === ">") {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: ">>>",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === "<" && ch2 === "<" && ch3 === "=") {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: "<<=",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === ">" && ch2 === ">" && ch3 === "=") {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: ">>=",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // The ... operator only valid in JSX mode for now
+ if (extra.ecmaFeatures.jsx && state.inJSXSpreadAttribute) {
+ if (ch1 === "." && ch2 === "." && ch3 === ".") {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: "...",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ // Other 2-character punctuators: ++ -- << >> && ||
+ if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) {
+ index += 2;
+ return {
+ type: Token.Punctuator,
+ value: ch1 + ch2,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // the => for arrow functions
+ if (extra.ecmaFeatures.arrowFunctions) {
+ if (ch1 === "=" && ch2 === ">") {
+ index += 2;
+ return {
+ type: Token.Punctuator,
+ value: "=>",
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ if ("<>=!+-*%&|^/".indexOf(ch1) >= 0) {
+ ++index;
+ return {
+ type: Token.Punctuator,
+ value: ch1,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === ".") {
+ ++index;
+ return {
+ type: Token.Punctuator,
+ value: ch1,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+}
+
+// 7.8.3 Numeric Literals
+
+function scanHexLiteral(start) {
+ var number = "";
+
+ while (index < length) {
+ if (!syntax.isHexDigit(source[index])) {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (number.length === 0) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ if (syntax.isIdentifierStart(source.charCodeAt(index))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt("0x" + number, 16),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function scanBinaryLiteral(start) {
+ var ch, number = "";
+
+ while (index < length) {
+ ch = source[index];
+ if (ch !== "0" && ch !== "1") {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (number.length === 0) {
+ // only 0b or 0B
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+
+ if (index < length) {
+ ch = source.charCodeAt(index);
+ /* istanbul ignore else */
+ if (syntax.isIdentifierStart(ch) || syntax.isDecimalDigit(ch)) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt(number, 2),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function scanOctalLiteral(prefix, start) {
+ var number, octal;
+
+ if (syntax.isOctalDigit(prefix)) {
+ octal = true;
+ number = "0" + source[index++];
+ } else {
+ octal = false;
+ ++index;
+ number = "";
+ }
+
+
+ while (index < length) {
+ if (!syntax.isOctalDigit(source[index])) {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (!octal && number.length === 0) {
+ // only 0o or 0O
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ if (syntax.isIdentifierStart(source.charCodeAt(index)) || syntax.isDecimalDigit(source.charCodeAt(index))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt(number, 8),
+ octal: true,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function scanNumericLiteral() {
+ var number, start, ch;
+
+ ch = source[index];
+ assert(syntax.isDecimalDigit(ch.charCodeAt(0)) || (ch === "."),
+ "Numeric literal must start with a decimal digit or a decimal point");
+
+ start = index;
+ number = "";
+ if (ch !== ".") {
+ number = source[index++];
+ ch = source[index];
+
+ // Hex number starts with "0x".
+ // Octal number starts with "0".
+ if (number === "0") {
+ if (ch === "x" || ch === "X") {
+ ++index;
+ return scanHexLiteral(start);
+ }
+
+ // Binary number in ES6 starts with '0b'
+ if (extra.ecmaFeatures.binaryLiterals) {
+ if (ch === "b" || ch === "B") {
+ ++index;
+ return scanBinaryLiteral(start);
+ }
+ }
+
+ if ((extra.ecmaFeatures.octalLiterals && (ch === "o" || ch === "O")) || syntax.isOctalDigit(ch)) {
+ return scanOctalLiteral(ch, start);
+ }
+
+ // decimal number starts with "0" such as "09" is illegal.
+ if (ch && syntax.isDecimalDigit(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ }
+
+ while (syntax.isDecimalDigit(source.charCodeAt(index))) {
+ number += source[index++];
+ }
+ ch = source[index];
+ }
+
+ if (ch === ".") {
+ number += source[index++];
+ while (syntax.isDecimalDigit(source.charCodeAt(index))) {
+ number += source[index++];
+ }
+ ch = source[index];
+ }
+
+ if (ch === "e" || ch === "E") {
+ number += source[index++];
+
+ ch = source[index];
+ if (ch === "+" || ch === "-") {
+ number += source[index++];
+ }
+ if (syntax.isDecimalDigit(source.charCodeAt(index))) {
+ while (syntax.isDecimalDigit(source.charCodeAt(index))) {
+ number += source[index++];
+ }
+ } else {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ }
+
+ if (syntax.isIdentifierStart(source.charCodeAt(index))) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseFloat(number),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+// 7.8.4 String Literals
+
+function scanStringLiteral() {
+ var str = "", quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;
+ startLineNumber = lineNumber;
+ startLineStart = lineStart;
+
+ quote = source[index];
+ assert((quote === "'" || quote === "\""),
+ "String literal must starts with a quote");
+
+ start = index;
+ ++index;
+
+ while (index < length) {
+ ch = source[index++];
+
+ if (ch === quote) {
+ quote = "";
+ break;
+ } else if (ch === "\\") {
+ ch = source[index++];
+ if (!ch || !syntax.isLineTerminator(ch.charCodeAt(0))) {
+ switch (ch) {
+ case "u":
+ case "x":
+ restore = index;
+ unescaped = scanHexEscape(ch);
+ if (unescaped) {
+ str += unescaped;
+ } else {
+ index = restore;
+ str += ch;
+ }
+ break;
+ case "n":
+ str += "\n";
+ break;
+ case "r":
+ str += "\r";
+ break;
+ case "t":
+ str += "\t";
+ break;
+ case "b":
+ str += "\b";
+ break;
+ case "f":
+ str += "\f";
+ break;
+ case "v":
+ str += "\x0B";
+ break;
+
+ default:
+ if (syntax.isOctalDigit(ch)) {
+ code = "01234567".indexOf(ch);
+
+ // \0 is not octal escape sequence
+ if (code !== 0) {
+ octal = true;
+ }
+
+ if (index < length && syntax.isOctalDigit(source[index])) {
+ octal = true;
+ code = code * 8 + "01234567".indexOf(source[index++]);
+
+ // 3 digits are only allowed when string starts
+ // with 0, 1, 2, 3
+ if ("0123".indexOf(ch) >= 0 &&
+ index < length &&
+ syntax.isOctalDigit(source[index])) {
+ code = code * 8 + "01234567".indexOf(source[index++]);
+ }
+ }
+ str += String.fromCharCode(code);
+ } else {
+ str += ch;
+ }
+ break;
+ }
+ } else {
+ ++lineNumber;
+ if (ch === "\r" && source[index] === "\n") {
+ ++index;
+ }
+ lineStart = index;
+ }
+ } else if (syntax.isLineTerminator(ch.charCodeAt(0))) {
+ break;
+ } else {
+ str += ch;
+ }
+ }
+
+ if (quote !== "") {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ return {
+ type: Token.StringLiteral,
+ value: str,
+ octal: octal,
+ startLineNumber: startLineNumber,
+ startLineStart: startLineStart,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function testRegExp(pattern, flags) {
+ var tmp = pattern,
+ validFlags = "gmsi";
+
+ if (extra.ecmaFeatures.regexYFlag) {
+ validFlags += "y";
+ }
+
+ if (extra.ecmaFeatures.regexUFlag) {
+ validFlags += "u";
+ }
+
+ if (!RegExp("^[" + validFlags + "]*$").test(flags)) {
+ throwError({}, Messages.InvalidRegExpFlag);
+ }
+
+
+ if (flags.indexOf("u") >= 0) {
+ // Replace each astral symbol and every Unicode code point
+ // escape sequence with a single ASCII symbol to avoid throwing on
+ // regular expressions that are only valid in combination with the
+ // `/u` flag.
+ // Note: replacing with the ASCII symbol `x` might cause false
+ // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
+ // perfectly valid pattern that is equivalent to `[a-b]`, but it
+ // would be replaced by `[x-b]` which throws an error.
+ tmp = tmp
+ .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
+ if (parseInt($1, 16) <= 0x10FFFF) {
+ return "x";
+ }
+ throwError({}, Messages.InvalidRegExp);
+ })
+ .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
+ }
+
+ // First, detect invalid regular expressions.
+ try {
+ RegExp(tmp);
+ } catch (e) {
+ throwError({}, Messages.InvalidRegExp);
+ }
+
+ // Return a regular expression object for this pattern-flag pair, or
+ // `null` in case the current environment doesn't support the flags it
+ // uses.
+ try {
+ return new RegExp(pattern, flags);
+ } catch (exception) {
+ return null;
+ }
+}
+
+function scanRegExpBody() {
+ var ch, str, classMarker, terminated, body;
+
+ ch = source[index];
+ assert(ch === "/", "Regular expression literal must start with a slash");
+ str = source[index++];
+
+ classMarker = false;
+ terminated = false;
+ while (index < length) {
+ ch = source[index++];
+ str += ch;
+ if (ch === "\\") {
+ ch = source[index++];
+ // ECMA-262 7.8.5
+ if (syntax.isLineTerminator(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+ str += ch;
+ } else if (syntax.isLineTerminator(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnterminatedRegExp);
+ } else if (classMarker) {
+ if (ch === "]") {
+ classMarker = false;
+ }
+ } else {
+ if (ch === "/") {
+ terminated = true;
+ break;
+ } else if (ch === "[") {
+ classMarker = true;
+ }
+ }
+ }
+
+ if (!terminated) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+
+ // Exclude leading and trailing slash.
+ body = str.substr(1, str.length - 2);
+ return {
+ value: body,
+ literal: str
+ };
+}
+
+function scanRegExpFlags() {
+ var ch, str, flags, restore;
+
+ str = "";
+ flags = "";
+ while (index < length) {
+ ch = source[index];
+ if (!syntax.isIdentifierPart(ch.charCodeAt(0))) {
+ break;
+ }
+
+ ++index;
+ if (ch === "\\" && index < length) {
+ ch = source[index];
+ if (ch === "u") {
+ ++index;
+ restore = index;
+ ch = scanHexEscape("u");
+ if (ch) {
+ flags += ch;
+ for (str += "\\u"; restore < index; ++restore) {
+ str += source[restore];
+ }
+ } else {
+ index = restore;
+ flags += "u";
+ str += "\\u";
+ }
+ throwErrorTolerant({}, Messages.UnexpectedToken, "ILLEGAL");
+ } else {
+ str += "\\";
+ throwErrorTolerant({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+ } else {
+ flags += ch;
+ str += ch;
+ }
+ }
+
+ return {
+ value: flags,
+ literal: str
+ };
+}
+
+function scanRegExp() {
+ var start, body, flags, value;
+
+ lookahead = null;
+ skipComment();
+ start = index;
+
+ body = scanRegExpBody();
+ flags = scanRegExpFlags();
+ value = testRegExp(body.value, flags.value);
+
+ if (extra.tokenize) {
+ return {
+ type: Token.RegularExpression,
+ value: value,
+ regex: {
+ pattern: body.value,
+ flags: flags.value
+ },
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ return {
+ literal: body.literal + flags.literal,
+ value: value,
+ regex: {
+ pattern: body.value,
+ flags: flags.value
+ },
+ range: [start, index]
+ };
+}
+
+function collectRegex() {
+ var pos, loc, regex, token;
+
+ skipComment();
+
+ pos = index;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+
+ regex = scanRegExp();
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+
+ /* istanbul ignore next */
+ if (!extra.tokenize) {
+ // Pop the previous token, which is likely "/" or "/="
+ if (extra.tokens.length > 0) {
+ token = extra.tokens[extra.tokens.length - 1];
+ if (token.range[0] === pos && token.type === "Punctuator") {
+ if (token.value === "/" || token.value === "/=") {
+ extra.tokens.pop();
+ }
+ }
+ }
+
+ extra.tokens.push({
+ type: "RegularExpression",
+ value: regex.literal,
+ regex: regex.regex,
+ range: [pos, index],
+ loc: loc
+ });
+ }
+
+ return regex;
+}
+
+function isIdentifierName(token) {
+ return token.type === Token.Identifier ||
+ token.type === Token.Keyword ||
+ token.type === Token.BooleanLiteral ||
+ token.type === Token.NullLiteral;
+}
+
+function advanceSlash() {
+ var prevToken,
+ checkToken;
+ // Using the following algorithm:
+ // https://github.com/mozilla/sweet.js/wiki/design
+ prevToken = extra.tokens[extra.tokens.length - 1];
+ if (!prevToken) {
+ // Nothing before that: it cannot be a division.
+ return collectRegex();
+ }
+ if (prevToken.type === "Punctuator") {
+ if (prevToken.value === "]") {
+ return scanPunctuator();
+ }
+ if (prevToken.value === ")") {
+ checkToken = extra.tokens[extra.openParenToken - 1];
+ if (checkToken &&
+ checkToken.type === "Keyword" &&
+ (checkToken.value === "if" ||
+ checkToken.value === "while" ||
+ checkToken.value === "for" ||
+ checkToken.value === "with")) {
+ return collectRegex();
+ }
+ return scanPunctuator();
+ }
+ if (prevToken.value === "}") {
+ // Dividing a function by anything makes little sense,
+ // but we have to check for that.
+ if (extra.tokens[extra.openCurlyToken - 3] &&
+ extra.tokens[extra.openCurlyToken - 3].type === "Keyword") {
+ // Anonymous function.
+ checkToken = extra.tokens[extra.openCurlyToken - 4];
+ if (!checkToken) {
+ return scanPunctuator();
+ }
+ } else if (extra.tokens[extra.openCurlyToken - 4] &&
+ extra.tokens[extra.openCurlyToken - 4].type === "Keyword") {
+ // Named function.
+ checkToken = extra.tokens[extra.openCurlyToken - 5];
+ if (!checkToken) {
+ return collectRegex();
+ }
+ } else {
+ return scanPunctuator();
+ }
+ // checkToken determines whether the function is
+ // a declaration or an expression.
+ if (FnExprTokens.indexOf(checkToken.value) >= 0) {
+ // It is an expression.
+ return scanPunctuator();
+ }
+ // It is a declaration.
+ return collectRegex();
+ }
+ return collectRegex();
+ }
+ if (prevToken.type === "Keyword") {
+ return collectRegex();
+ }
+ return scanPunctuator();
+}
+
+function advance() {
+ var ch,
+ allowJSX = extra.ecmaFeatures.jsx;
+
+ /*
+ * If JSX isn't allowed or JSX is allowed and we're not inside an JSX child,
+ * then skip any comments.
+ */
+ if (!allowJSX || !state.inJSXChild) {
+ skipComment();
+ }
+
+ if (index >= length) {
+ return {
+ type: Token.EOF,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [index, index]
+ };
+ }
+
+ // if inside an JSX child, then abort regular tokenization
+ if (allowJSX && state.inJSXChild) {
+ return advanceJSXChild();
+ }
+
+ ch = source.charCodeAt(index);
+
+ // Very common: ( and ) and ;
+ if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
+ return scanPunctuator();
+ }
+
+ // String literal starts with single quote (U+0027) or double quote (U+0022).
+ if (ch === 0x27 || ch === 0x22) {
+ if (allowJSX && state.inJSXTag) {
+ return scanJSXStringLiteral();
+ }
+
+ return scanStringLiteral();
+ }
+
+ if (allowJSX && state.inJSXTag && syntax.isJSXIdentifierStart(ch)) {
+ return scanJSXIdentifier();
+ }
+
+ // TODO: template string support here
+
+ if (syntax.isIdentifierStart(ch)) {
+ return scanIdentifier();
+ }
+
+
+
+ // Dot (.) U+002E can also start a floating-point number, hence the need
+ // to check the next character.
+ if (ch === 0x2E) {
+ if (syntax.isDecimalDigit(source.charCodeAt(index + 1))) {
+ return scanNumericLiteral();
+ }
+ return scanPunctuator();
+ }
+
+ if (syntax.isDecimalDigit(ch)) {
+ return scanNumericLiteral();
+ }
+
+ // Slash (/) U+002F can also start a regex.
+ if (extra.tokenize && ch === 0x2F) {
+ return advanceSlash();
+ }
+
+ return scanPunctuator();
+}
+
+function collectToken() {
+ var loc, token, range, value, entry,
+ allowJSX = extra.ecmaFeatures.jsx;
+
+ /* istanbul ignore else */
+ if (!allowJSX || !state.inJSXChild) {
+ skipComment();
+ }
+
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+
+ token = advance();
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+
+ if (token.type !== Token.EOF) {
+ range = [token.range[0], token.range[1]];
+ value = source.slice(token.range[0], token.range[1]);
+ entry = {
+ type: TokenName[token.type],
+ value: value,
+ range: range,
+ loc: loc
+ };
+ if (token.regex) {
+ entry.regex = {
+ pattern: token.regex.pattern,
+ flags: token.regex.flags
+ };
+ }
+ extra.tokens.push(entry);
+ }
+
+ return token;
+}
+
+function lex() {
+ var token;
+
+ token = lookahead;
+ index = token.range[1];
+ lineNumber = token.lineNumber;
+ lineStart = token.lineStart;
+
+ lookahead = (typeof extra.tokens !== "undefined") ? collectToken() : advance();
+
+ index = token.range[1];
+ lineNumber = token.lineNumber;
+ lineStart = token.lineStart;
+
+ return token;
+}
+
+function peek() {
+ var pos, line, start;
+
+ pos = index;
+ line = lineNumber;
+ start = lineStart;
+ lookahead = (typeof extra.tokens !== "undefined") ? collectToken() : advance();
+ index = pos;
+ lineNumber = line;
+ lineStart = start;
+}
+
+function lookahead2() {
+ var adv, pos, line, start, result;
+
+ // If we are collecting the tokens, don't grab the next one yet.
+ /* istanbul ignore next */
+ adv = (typeof extra.advance === "function") ? extra.advance : advance;
+
+ pos = index;
+ line = lineNumber;
+ start = lineStart;
+
+ // Scan for the next immediate token.
+ /* istanbul ignore if */
+ if (lookahead === null) {
+ lookahead = adv();
+ }
+ index = lookahead.range[1];
+ lineNumber = lookahead.lineNumber;
+ lineStart = lookahead.lineStart;
+
+ // Grab the token right after.
+ result = adv();
+ index = pos;
+ lineNumber = line;
+ lineStart = start;
+
+ return result;
+}
+
+
+//------------------------------------------------------------------------------
+// JSX
+//------------------------------------------------------------------------------
+
+function getQualifiedJSXName(object) {
+ if (object.type === astNodeTypes.JSXIdentifier) {
+ return object.name;
+ }
+ if (object.type === astNodeTypes.JSXNamespacedName) {
+ return object.namespace.name + ":" + object.name.name;
+ }
+ /* istanbul ignore else */
+ if (object.type === astNodeTypes.JSXMemberExpression) {
+ return (
+ getQualifiedJSXName(object.object) + "." +
+ getQualifiedJSXName(object.property)
+ );
+ }
+ /* istanbul ignore next */
+ throwUnexpected(object);
+}
+
+function scanJSXIdentifier() {
+ var ch, start, value = "";
+
+ start = index;
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (!syntax.isJSXIdentifierPart(ch)) {
+ break;
+ }
+ value += source[index++];
+ }
+
+ return {
+ type: Token.JSXIdentifier,
+ value: value,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function scanJSXEntity() {
+ var ch, str = "", start = index, count = 0, code;
+ ch = source[index];
+ assert(ch === "&", "Entity must start with an ampersand");
+ index++;
+ while (index < length && count++ < 10) {
+ ch = source[index++];
+ if (ch === ";") {
+ break;
+ }
+ str += ch;
+ }
+
+ // Well-formed entity (ending was found).
+ if (ch === ";") {
+ // Numeric entity.
+ if (str[0] === "#") {
+ if (str[1] === "x") {
+ code = +("0" + str.substr(1));
+ } else {
+ // Removing leading zeros in order to avoid treating as octal in old browsers.
+ code = +str.substr(1).replace(Regex.LeadingZeros, "");
+ }
+
+ if (!isNaN(code)) {
+ return String.fromCharCode(code);
+ }
+ /* istanbul ignore else */
+ } else if (XHTMLEntities[str]) {
+ return XHTMLEntities[str];
+ }
+ }
+
+ // Treat non-entity sequences as regular text.
+ index = start + 1;
+ return "&";
+}
+
+function scanJSXText(stopChars) {
+ var ch, str = "", start;
+ start = index;
+ while (index < length) {
+ ch = source[index];
+ if (stopChars.indexOf(ch) !== -1) {
+ break;
+ }
+ if (ch === "&") {
+ str += scanJSXEntity();
+ } else {
+ index++;
+ if (ch === "\r" && source[index] === "\n") {
+ str += ch;
+ ch = source[index];
+ index++;
+ }
+ if (syntax.isLineTerminator(ch.charCodeAt(0))) {
+ ++lineNumber;
+ lineStart = index;
+ }
+ str += ch;
+ }
+ }
+ return {
+ type: Token.JSXText,
+ value: str,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+}
+
+function scanJSXStringLiteral() {
+ var innerToken, quote, start;
+
+ quote = source[index];
+ assert((quote === "\"" || quote === "'"),
+ "String literal must starts with a quote");
+
+ start = index;
+ ++index;
+
+ innerToken = scanJSXText([quote]);
+
+ if (quote !== source[index]) {
+ throwError({}, Messages.UnexpectedToken, "ILLEGAL");
+ }
+
+ ++index;
+
+ innerToken.range = [start, index];
+
+ return innerToken;
+}
+
+/*
+ * Between JSX opening and closing tags (e.g. HERE), anything that
+ * is not another JSX tag and is not an expression wrapped by {} is text.
+ */
+function advanceJSXChild() {
+ var ch = source.charCodeAt(index);
+
+ // { (123) and < (60)
+ if (ch !== 123 && ch !== 60) {
+ return scanJSXText(["<", "{"]);
+ }
+
+ return scanPunctuator();
+}
+
+function parseJSXIdentifier() {
+ var token, marker = markerCreate();
+
+ if (lookahead.type !== Token.JSXIdentifier) {
+ throwUnexpected(lookahead);
+ }
+
+ token = lex();
+ return markerApply(marker, astNodeFactory.createJSXIdentifier(token.value));
+}
+
+function parseJSXNamespacedName() {
+ var namespace, name, marker = markerCreate();
+
+ namespace = parseJSXIdentifier();
+ expect(":");
+ name = parseJSXIdentifier();
+
+ return markerApply(marker, astNodeFactory.createJSXNamespacedName(namespace, name));
+}
+
+function parseJSXMemberExpression() {
+ var marker = markerCreate(),
+ expr = parseJSXIdentifier();
+
+ while (match(".")) {
+ lex();
+ expr = markerApply(marker, astNodeFactory.createJSXMemberExpression(expr, parseJSXIdentifier()));
+ }
+
+ return expr;
+}
+
+function parseJSXElementName() {
+ if (lookahead2().value === ":") {
+ return parseJSXNamespacedName();
+ }
+ if (lookahead2().value === ".") {
+ return parseJSXMemberExpression();
+ }
+
+ return parseJSXIdentifier();
+}
+
+function parseJSXAttributeName() {
+ if (lookahead2().value === ":") {
+ return parseJSXNamespacedName();
+ }
+
+ return parseJSXIdentifier();
+}
+
+function parseJSXAttributeValue() {
+ var value, marker;
+ if (match("{")) {
+ value = parseJSXExpressionContainer();
+ if (value.expression.type === astNodeTypes.JSXEmptyExpression) {
+ throwError(
+ value,
+ "JSX attributes must only be assigned a non-empty " +
+ "expression"
+ );
+ }
+ } else if (match("<")) {
+ value = parseJSXElement();
+ } else if (lookahead.type === Token.JSXText) {
+ marker = markerCreate();
+ value = markerApply(marker, astNodeFactory.createLiteralFromSource(lex(), source));
+ } else {
+ throwError({}, Messages.InvalidJSXAttributeValue);
+ }
+ return value;
+}
+
+function parseJSXEmptyExpression() {
+ var marker = markerCreatePreserveWhitespace();
+ while (source.charAt(index) !== "}") {
+ index++;
+ }
+ return markerApply(marker, astNodeFactory.createJSXEmptyExpression());
+}
+
+function parseJSXExpressionContainer() {
+ var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
+
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = false;
+
+ expect("{");
+
+ if (match("}")) {
+ expression = parseJSXEmptyExpression();
+ } else {
+ expression = parseExpression();
+ }
+
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
+
+ expect("}");
+
+ return markerApply(marker, astNodeFactory.createJSXExpressionContainer(expression));
+}
+
+function parseJSXSpreadAttribute() {
+ var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
+
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = false;
+ state.inJSXSpreadAttribute = true;
+
+ expect("{");
+ expect("...");
+
+ state.inJSXSpreadAttribute = false;
+
+ expression = parseAssignmentExpression();
+
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
+
+ expect("}");
+
+ return markerApply(marker, astNodeFactory.createJSXSpreadAttribute(expression));
+}
+
+function parseJSXAttribute() {
+ var name, marker;
+
+ if (match("{")) {
+ return parseJSXSpreadAttribute();
+ }
+
+ marker = markerCreate();
+
+ name = parseJSXAttributeName();
+
+ // HTML empty attribute
+ if (match("=")) {
+ lex();
+ return markerApply(marker, astNodeFactory.createJSXAttribute(name, parseJSXAttributeValue()));
+ }
+
+ return markerApply(marker, astNodeFactory.createJSXAttribute(name));
+}
+
+function parseJSXChild() {
+ var token, marker;
+ if (match("{")) {
+ token = parseJSXExpressionContainer();
+ } else if (lookahead.type === Token.JSXText) {
+ marker = markerCreatePreserveWhitespace();
+ token = markerApply(marker, astNodeFactory.createLiteralFromSource(lex(), source));
+ } else {
+ token = parseJSXElement();
+ }
+ return token;
+}
+
+function parseJSXClosingElement() {
+ var name, origInJSXChild, origInJSXTag, marker = markerCreate();
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = true;
+ expect("<");
+ expect("/");
+ name = parseJSXElementName();
+ // Because advance() (called by lex() called by expect()) expects there
+ // to be a valid token after >, it needs to know whether to look for a
+ // standard JS token or an JSX text node
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
+ expect(">");
+ return markerApply(marker, astNodeFactory.createJSXClosingElement(name));
+}
+
+function parseJSXOpeningElement() {
+ var name, attributes = [], selfClosing = false, origInJSXChild,
+ origInJSXTag, marker = markerCreate();
+
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = true;
+
+ expect("<");
+
+ name = parseJSXElementName();
+
+ while (index < length &&
+ lookahead.value !== "/" &&
+ lookahead.value !== ">") {
+ attributes.push(parseJSXAttribute());
+ }
+
+ state.inJSXTag = origInJSXTag;
+
+ if (lookahead.value === "/") {
+ expect("/");
+ // Because advance() (called by lex() called by expect()) expects
+ // there to be a valid token after >, it needs to know whether to
+ // look for a standard JS token or an JSX text node
+ state.inJSXChild = origInJSXChild;
+ expect(">");
+ selfClosing = true;
+ } else {
+ state.inJSXChild = true;
+ expect(">");
+ }
+ return markerApply(marker, astNodeFactory.createJSXOpeningElement(name, attributes, selfClosing));
+}
+
+function parseJSXElement() {
+ var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
+
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ openingElement = parseJSXOpeningElement();
+
+ if (!openingElement.selfClosing) {
+ while (index < length) {
+ state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because should not be considered in the child
+ if (lookahead.value === "<" && lookahead2().value === "/") {
+ break;
+ }
+ state.inJSXChild = true;
+ children.push(parseJSXChild());
+ }
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
+ closingElement = parseJSXClosingElement();
+ if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
+ throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
+ }
+ }
+
+ /*
+ * When (erroneously) writing two adjacent tags like
+ *
+ * var x =
one
two
;
+ *
+ * the default error message is a bit incomprehensible. Since it"s
+ * rarely (never?) useful to write a less-than sign after an JSX
+ * element, we disallow it here in the parser in order to provide a
+ * better error message. (In the rare case that the less-than operator
+ * was intended, the left tag can be wrapped in parentheses.)
+ */
+ if (!origInJSXChild && match("<")) {
+ throwError(lookahead, Messages.AdjacentJSXElements);
+ }
+
+ return markerApply(marker, astNodeFactory.createJSXElement(openingElement, closingElement, children));
+}
+
+//------------------------------------------------------------------------------
+// Location markers
+//------------------------------------------------------------------------------
+
+/**
+ * Applies location information to the given node by using the given marker.
+ * The marker indicates the point at which the node is said to have to begun
+ * in the source code.
+ * @param {Object} marker The market to use for the node.
+ * @param {ASTNode} node The AST node to apply location information to.
+ * @returns {ASTNode} The node that was passed in.
+ * @private
+ */
+function markerApply(marker, node) {
+
+ // add range information to the node if present
+ if (extra.range) {
+ node.range = [marker.offset, index];
+ }
+
+ // add location information the node if present
+ if (extra.loc) {
+ node.loc = {
+ start: {
+ line: marker.line,
+ column: marker.col
+ },
+ end: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+ // Attach extra.source information to the location, if present
+ if (extra.source) {
+ node.loc.source = extra.source;
+ }
+ }
+
+ // attach leading and trailing comments if requested
+ if (extra.attachComment) {
+ processComment(node);
+ }
+
+ return node;
+}
+
+/**
+ * Creates a location marker in the source code. Location markers are used for
+ * tracking where tokens and nodes appear in the source code.
+ * @returns {Object} A marker object or undefined if the parser doesn't have
+ * any location information.
+ * @private
+ */
+function markerCreate() {
+
+ if (!extra.loc && !extra.range) {
+ return undefined;
+ }
+
+ skipComment();
+
+ return {
+ offset: index,
+ line: lineNumber,
+ col: index - lineStart
+ };
+}
+
+/**
+ * Creates a location marker in the source code. Location markers are used for
+ * tracking where tokens and nodes appear in the source code. This method
+ * doesn't skip comments or extra whitespace which is important for JSX.
+ * @returns {Object} A marker object or undefined if the parser doesn't have
+ * any location information.
+ * @private
+ */
+function markerCreatePreserveWhitespace() {
+
+ if (!extra.loc && !extra.range) {
+ return undefined;
+ }
+
+ return {
+ offset: index,
+ line: lineNumber,
+ col: index - lineStart
+ };
+}
+
+
+//------------------------------------------------------------------------------
+// Syntax Tree Delegate
+//------------------------------------------------------------------------------
+
+
+function processComment(node) {
+ var lastChild,
+ trailingComments,
+ i;
+
+ if (node.type === astNodeTypes.Program) {
+ if (node.body.length > 0) {
+ return;
+ }
+ }
+
+ if (extra.trailingComments.length > 0) {
+
+ /*
+ * If the first comment in trailingComments comes after the
+ * current node, then we're good - all comments in the array will
+ * come after the node and so it's safe to add then as official
+ * trailingComments.
+ */
+ if (extra.trailingComments[0].range[0] >= node.range[1]) {
+ trailingComments = extra.trailingComments;
+ extra.trailingComments = [];
+ } else {
+
+ /*
+ * Otherwise, if the first comment doesn't come after the
+ * current node, that means we have a mix of leading and trailing
+ * comments in the array and that leadingComments contains the
+ * same items as trailingComments. Reset trailingComments to
+ * zero items and we'll handle this by evaluating leadingComments
+ * later.
+ */
+ extra.trailingComments.length = 0;
+ }
+ } else {
+ if (extra.bottomRightStack.length > 0 &&
+ extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
+ extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
+ trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
+ delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
+ }
+ }
+
+ // Eating the stack.
+ while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
+ lastChild = extra.bottomRightStack.pop();
+ }
+
+ if (lastChild) {
+ if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
+ node.leadingComments = lastChild.leadingComments;
+ delete lastChild.leadingComments;
+ }
+ } else if (extra.leadingComments.length > 0) {
+
+ if (extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
+ node.leadingComments = extra.leadingComments;
+ extra.leadingComments = [];
+ } else {
+
+ // https://github.com/eslint/espree/issues/2
+
+ /*
+ * In special cases, such as return (without a value) and
+ * debugger, all comments will end up as leadingComments and
+ * will otherwise be eliminated. This extra step runs when the
+ * bottomRightStack is empty and there are comments left
+ * in leadingComments.
+ *
+ * This loop figures out the stopping point between the actual
+ * leading and trailing comments by finding the location of the
+ * first comment that comes after the given node.
+ */
+ for (i = 0; i < extra.leadingComments.length; i++) {
+ if (extra.leadingComments[i].range[1] > node.range[0]) {
+ break;
+ }
+ }
+
+ /*
+ * Split the array based on the location of the first comment
+ * that comes after the node. Keep in mind that this could
+ * result in an empty array, and if so, the array must be
+ * deleted.
+ */
+ node.leadingComments = extra.leadingComments.slice(0, i);
+ if (node.leadingComments.length === 0) {
+ delete node.leadingComments;
+ }
+
+ /*
+ * Similarly, trailing comments are attached later. The variable
+ * must be reset to null if there are no trailing comments.
+ */
+ trailingComments = extra.leadingComments.slice(i);
+ if (trailingComments.length === 0) {
+ trailingComments = null;
+ }
+ }
+ }
+
+ if (trailingComments) {
+ node.trailingComments = trailingComments;
+ }
+
+ extra.bottomRightStack.push(node);
+}
+
+// Return true if there is a line terminator before the next token.
+
+function peekLineTerminator() {
+ var pos, line, start, found;
+
+ pos = index;
+ line = lineNumber;
+ start = lineStart;
+ skipComment();
+ found = lineNumber !== line;
+ index = pos;
+ lineNumber = line;
+ lineStart = start;
+
+ return found;
+}
+
+// Throw an exception
+
+function throwError(token, messageFormat) {
+ var error,
+ args = Array.prototype.slice.call(arguments, 2),
+ msg = messageFormat.replace(
+ /%(\d)/g,
+ function (whole, index) {
+ assert(index < args.length, "Message reference must be in range");
+ return args[index];
+ }
+ );
+
+ if (typeof token.lineNumber === "number") {
+ error = new Error("Line " + token.lineNumber + ": " + msg);
+ error.index = token.range[0];
+ error.lineNumber = token.lineNumber;
+ error.column = token.range[0] - lineStart + 1;
+ } else {
+ error = new Error("Line " + lineNumber + ": " + msg);
+ error.index = index;
+ error.lineNumber = lineNumber;
+ error.column = index - lineStart + 1;
+ }
+
+ error.description = msg;
+ throw error;
+}
+
+function throwErrorTolerant() {
+ try {
+ throwError.apply(null, arguments);
+ } catch (e) {
+ if (extra.errors) {
+ extra.errors.push(e);
+ } else {
+ throw e;
+ }
+ }
+}
+
+
+// Throw an exception because of the token.
+
+function throwUnexpected(token) {
+ if (token.type === Token.EOF) {
+ throwError(token, Messages.UnexpectedEOS);
+ }
+
+ if (token.type === Token.NumericLiteral) {
+ throwError(token, Messages.UnexpectedNumber);
+ }
+
+ if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
+ throwError(token, Messages.UnexpectedString);
+ }
+
+ if (token.type === Token.Identifier) {
+ throwError(token, Messages.UnexpectedIdentifier);
+ }
+
+ if (token.type === Token.Keyword) {
+ if (syntax.isFutureReservedWord(token.value)) {
+ throwError(token, Messages.UnexpectedReserved);
+ } else if (strict && syntax.isStrictModeReservedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictReservedWord);
+ return;
+ }
+ throwError(token, Messages.UnexpectedToken, token.value);
+ }
+
+ // BooleanLiteral, NullLiteral, or Punctuator.
+ throwError(token, Messages.UnexpectedToken, token.value);
+}
+
+// Expect the next token to match the specified punctuator.
+// If not, an exception will be thrown.
+
+function expect(value) {
+ var token = lex();
+ if (token.type !== Token.Punctuator || token.value !== value) {
+ throwUnexpected(token);
+ }
+}
+
+// Expect the next token to match the specified keyword.
+// If not, an exception will be thrown.
+
+function expectKeyword(keyword) {
+ var token = lex();
+ if (token.type !== Token.Keyword || token.value !== keyword) {
+ throwUnexpected(token);
+ }
+}
+
+// Return true if the next token matches the specified punctuator.
+
+function match(value) {
+ return lookahead.type === Token.Punctuator && lookahead.value === value;
+}
+
+// Return true if the next token matches the specified keyword
+
+function matchKeyword(keyword) {
+ return lookahead.type === Token.Keyword && lookahead.value === keyword;
+}
+
+// Return true if the next token matches the specified contextual keyword
+// (where an identifier is sometimes a keyword depending on the context)
+
+function matchContextualKeyword(keyword) {
+ return lookahead.type === Token.Identifier && lookahead.value === keyword;
+}
+
+// Return true if the next token is an assignment operator
+
+function matchAssign() {
+ var op;
+
+ if (lookahead.type !== Token.Punctuator) {
+ return false;
+ }
+ op = lookahead.value;
+ return op === "=" ||
+ op === "*=" ||
+ op === "/=" ||
+ op === "%=" ||
+ op === "+=" ||
+ op === "-=" ||
+ op === "<<=" ||
+ op === ">>=" ||
+ op === ">>>=" ||
+ op === "&=" ||
+ op === "^=" ||
+ op === "|=";
+}
+
+function consumeSemicolon() {
+ var line;
+
+ // Catch the very common case first: immediately a semicolon (U+003B).
+ if (source.charCodeAt(index) === 0x3B || match(";")) {
+ lex();
+ return;
+ }
+
+ line = lineNumber;
+ skipComment();
+ if (lineNumber !== line) {
+ return;
+ }
+
+ if (lookahead.type !== Token.EOF && !match("}")) {
+ throwUnexpected(lookahead);
+ }
+}
+
+// Return true if provided expression is LeftHandSideExpression
+
+function isLeftHandSide(expr) {
+ return expr.type === astNodeTypes.Identifier || expr.type === astNodeTypes.MemberExpression;
+}
+
+// 11.1.4 Array Initialiser
+
+function parseArrayInitialiser() {
+ var elements = [],
+ marker = markerCreate();
+
+ expect("[");
+
+ while (!match("]")) {
+ if (match(",")) {
+ lex();
+ elements.push(null);
+ } else {
+ elements.push(parseAssignmentExpression());
+
+ if (!match("]")) {
+ expect(",");
+ }
+ }
+ }
+
+ lex();
+
+ return markerApply(marker, astNodeFactory.createArrayExpression(elements));
+}
+
+// 11.1.5 Object Initialiser
+
+function parsePropertyFunction(options) {
+ var previousStrict = strict,
+ previousYieldAllowed = state.yieldAllowed,
+ params = options.params || [],
+ defaults = options.defaults || [],
+ body,
+ marker = markerCreate();
+
+ state.yieldAllowed = options.generator;
+
+ /*
+ * Esprima uses parseConciseBody() here, which is incorrect. Object literal
+ * methods must have braces.
+ */
+ body = parseFunctionSourceElements();
+
+ if (options.name && strict && syntax.isRestrictedWord(params[0].name)) {
+ throwErrorTolerant(options.name, Messages.StrictParamName);
+ }
+
+ strict = previousStrict;
+ state.yieldAllowed = previousYieldAllowed;
+
+ return markerApply(marker, astNodeFactory.createFunctionExpression(
+ null,
+ params,
+ defaults,
+ body,
+ options.rest || null,
+ options.generator,
+ body.type !== astNodeTypes.BlockStatement
+ ));
+}
+
+function parsePropertyMethodFunction(options) {
+ var previousStrict = strict,
+ tmp,
+ method;
+
+ strict = true;
+
+ tmp = parseParams();
+
+ if (tmp.stricted) {
+ throwErrorTolerant(tmp.stricted, tmp.message);
+ }
+
+ method = parsePropertyFunction({
+ params: tmp.params,
+ defaults: tmp.defaults,
+ rest: tmp.rest,
+ generator: options ? options.generator : false
+ });
+
+ strict = previousStrict;
+
+ return method;
+}
+
+function parseObjectPropertyKey() {
+ var marker = markerCreate(),
+ token = lex(),
+ propertyKey,
+ result;
+
+ // Note: This function is called only from parseObjectProperty(), where
+ // EOF and Punctuator tokens are already filtered out.
+
+ if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
+ if (strict && token.octal) {
+ throwErrorTolerant(token, Messages.StrictOctalLiteral);
+ }
+ return markerApply(marker, astNodeFactory.createLiteralFromSource(token, source));
+ }
+
+ if (extra.ecmaFeatures.objectLiteralComputedProperties &&
+ token.type === Token.Punctuator && token.value === "["
+ ) {
+ // For computed properties we should skip the [ and ], and
+ // capture in marker only the assignment expression itself.
+ marker = markerCreate();
+ propertyKey = parseAssignmentExpression();
+ result = markerApply(marker, propertyKey);
+ expect("]");
+ return result;
+ }
+
+ return markerApply(marker, astNodeFactory.createIdentifier(token.value));
+}
+
+function parseObjectProperty() {
+ var token, key, id, param, computed;
+ var allowComputed = extra.ecmaFeatures.objectLiteralComputedProperties,
+ allowMethod = extra.ecmaFeatures.objectLiteralShorthandMethods,
+ allowShorthand = extra.ecmaFeatures.objectLiteralShorthandProperties,
+ allowGenerators = extra.ecmaFeatures.generators,
+ marker = markerCreate();
+
+ token = lookahead;
+ computed = (token.value === "[" && token.type === Token.Punctuator);
+
+ if (token.type === Token.Identifier || (allowComputed && computed)) {
+
+ id = parseObjectPropertyKey();
+
+ /*
+ * Check for getters and setters. Be careful! "get" and "set" are legal
+ * method names. It's only a getter or setter if followed by a space.
+ */
+ if (token.value === "get" && !match(":") && !match("(")) {
+ computed = (lookahead.value === "[");
+ key = parseObjectPropertyKey();
+ expect("(");
+ expect(")");
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "get",
+ key,
+ parsePropertyFunction({ generator: false }),
+ false,
+ false,
+ computed
+ )
+ );
+ }
+
+ if (token.value === "set" && !match(":") && !match("(")) {
+ computed = (lookahead.value === "[");
+ key = parseObjectPropertyKey();
+ expect("(");
+ token = lookahead;
+ param = [ parseVariableIdentifier() ];
+ expect(")");
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "set",
+ key,
+ parsePropertyFunction({
+ params: param,
+ generator: false,
+ name: token
+ }),
+ false,
+ false,
+ computed
+ )
+ );
+ }
+
+ // normal property (key:value)
+ if (match(":")) {
+ lex();
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ id,
+ parseAssignmentExpression(),
+ false,
+ false,
+ computed
+ )
+ );
+ }
+
+ // method shorthand (key(){...})
+ if (allowMethod && match("(")) {
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ id,
+ parsePropertyMethodFunction({ generator: false }),
+ true,
+ false,
+ computed
+ )
+ );
+ }
+
+ /*
+ * Only other possibility is that this is a shorthand property. Computed
+ * properties cannot use shorthand notation, so that's a syntax error.
+ * If shorthand properties aren't allow, then this is an automatic
+ * syntax error.
+ */
+ if (computed || !allowShorthand) {
+ throwUnexpected(lookahead);
+ }
+
+ // shorthand property
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ id,
+ id,
+ false,
+ true,
+ false
+ )
+ );
+ }
+
+ // only possibility in this branch is a generator
+ if (token.type === Token.EOF || token.type === Token.Punctuator) {
+ if (!allowGenerators || !match("*")) {
+ throwUnexpected(token);
+ }
+ lex();
+
+ computed = (lookahead.type === Token.Punctuator && lookahead.value === "[");
+
+ id = parseObjectPropertyKey();
+
+ if (!match("(")) {
+ throwUnexpected(lex());
+ }
+
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ id,
+ parsePropertyMethodFunction({ generator: true }),
+ true,
+ false,
+ computed
+ )
+ );
+
+ } else {
+
+ /*
+ * If we've made it here, then that means the property name is represented
+ * by a string (i.e, { "foo": 2}). The only options here are normal
+ * property with a colon or a method.
+ */
+ key = parseObjectPropertyKey();
+
+ // check for property value
+ if (match(":")) {
+ lex();
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ key,
+ parseAssignmentExpression(),
+ false,
+ false,
+ false
+ )
+ );
+ }
+
+ // check for method
+ if (allowMethod && match("(")) {
+ return markerApply(
+ marker,
+ astNodeFactory.createProperty(
+ "init",
+ key,
+ parsePropertyMethodFunction(),
+ true,
+ false,
+ false
+ )
+ );
+ }
+
+ // no other options, this is bad
+ throwUnexpected(lex());
+ }
+}
+
+function parseObjectInitialiser() {
+ var marker = markerCreate(),
+ allowDuplicates = extra.ecmaFeatures.objectLiteralDuplicateProperties,
+ properties = [],
+ property,
+ name,
+ key,
+ kind,
+ kindMap = {},
+ toString = String;
+
+ expect("{");
+
+ while (!match("}")) {
+ property = parseObjectProperty();
+
+ if (!property.computed) {
+
+ if (property.key.type === astNodeTypes.Identifier) {
+ name = property.key.name;
+ } else {
+ name = toString(property.key.value);
+ }
+
+ if (property.kind === "init") {
+ kind = PropertyKind.Data;
+ } else if (property.kind === "get") {
+ kind = PropertyKind.Get;
+ } else {
+ kind = PropertyKind.Set;
+ }
+
+ key = "$" + name;
+ if (Object.prototype.hasOwnProperty.call(kindMap, key)) {
+ if (kindMap[key] === PropertyKind.Data) {
+ if (kind === PropertyKind.Data && name === "__proto__" && allowDuplicates) {
+ // Duplicate '__proto__' literal properties are forbidden in ES 6
+ throwErrorTolerant({}, Messages.DuplicatePrototypeProperty);
+ } else if (kind === PropertyKind.Data && strict && !allowDuplicates) {
+ // Duplicate literal properties are only forbidden in ES 5 strict mode
+ throwErrorTolerant({}, Messages.StrictDuplicateProperty);
+ } else if (kind !== PropertyKind.Data) {
+ throwErrorTolerant({}, Messages.AccessorDataProperty);
+ }
+ } else {
+ if (kind === PropertyKind.Data) {
+ throwErrorTolerant({}, Messages.AccessorDataProperty);
+ } else if (kindMap[key] & kind) {
+ throwErrorTolerant({}, Messages.AccessorGetSet);
+ }
+ }
+ kindMap[key] |= kind;
+ } else {
+ kindMap[key] = kind;
+ }
+ }
+
+ properties.push(property);
+
+ if (!match("}")) {
+ expect(",");
+ }
+ }
+
+ expect("}");
+
+ return markerApply(marker, astNodeFactory.createObjectExpression(properties));
+}
+
+// 11.1.6 The Grouping Operator
+
+function parseGroupExpression() {
+ var expr;
+
+ expect("(");
+
+ expr = parseExpression();
+
+ expect(")");
+
+ return expr;
+}
+
+
+// 11.1 Primary Expressions
+
+function parsePrimaryExpression() {
+ var type, token, expr,
+ marker,
+ allowJSX = extra.ecmaFeatures.jsx;
+
+ if (match("(")) {
+ return parseGroupExpression();
+ }
+
+ if (match("[")) {
+ return parseArrayInitialiser();
+ }
+
+ if (match("{")) {
+ return parseObjectInitialiser();
+ }
+
+ if (allowJSX && match("<")) {
+ return parseJSXElement();
+ }
+
+ type = lookahead.type;
+ marker = markerCreate();
+
+ if (type === Token.Identifier) {
+ expr = astNodeFactory.createIdentifier(lex().value);
+ } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
+ if (strict && lookahead.octal) {
+ throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
+ }
+ expr = astNodeFactory.createLiteralFromSource(lex(), source);
+ } else if (type === Token.Keyword) {
+ if (matchKeyword("function")) {
+ return parseFunctionExpression();
+ }
+ if (matchKeyword("this")) {
+ lex();
+ expr = astNodeFactory.createThisExpression();
+ } else {
+ throwUnexpected(lex());
+ }
+ } else if (type === Token.BooleanLiteral) {
+ token = lex();
+ token.value = (token.value === "true");
+ expr = astNodeFactory.createLiteralFromSource(token, source);
+ } else if (type === Token.NullLiteral) {
+ token = lex();
+ token.value = null;
+ expr = astNodeFactory.createLiteralFromSource(token, source);
+ } else if (match("/") || match("/=")) {
+ if (typeof extra.tokens !== "undefined") {
+ expr = astNodeFactory.createLiteralFromSource(collectRegex(), source);
+ } else {
+ expr = astNodeFactory.createLiteralFromSource(scanRegExp(), source);
+ }
+ peek();
+ } else {
+ throwUnexpected(lex());
+ }
+
+ return markerApply(marker, expr);
+}
+
+// 11.2 Left-Hand-Side Expressions
+
+function parseArguments() {
+ var args = [];
+
+ expect("(");
+
+ if (!match(")")) {
+ while (index < length) {
+ args.push(parseAssignmentExpression());
+ if (match(")")) {
+ break;
+ }
+ expect(",");
+ }
+ }
+
+ expect(")");
+
+ return args;
+}
+
+function parseNonComputedProperty() {
+ var token,
+ marker = markerCreate();
+
+ token = lex();
+
+ if (!isIdentifierName(token)) {
+ throwUnexpected(token);
+ }
+
+ return markerApply(marker, astNodeFactory.createIdentifier(token.value));
+}
+
+function parseNonComputedMember() {
+ expect(".");
+
+ return parseNonComputedProperty();
+}
+
+function parseComputedMember() {
+ var expr;
+
+ expect("[");
+
+ expr = parseExpression();
+
+ expect("]");
+
+ return expr;
+}
+
+function parseNewExpression() {
+ var callee, args,
+ marker = markerCreate();
+
+ expectKeyword("new");
+ callee = parseLeftHandSideExpression();
+ args = match("(") ? parseArguments() : [];
+
+ return markerApply(marker, astNodeFactory.createNewExpression(callee, args));
+}
+
+function parseLeftHandSideExpressionAllowCall() {
+ var previousAllowIn, expr, args, property,
+ marker = markerCreate();
+
+ previousAllowIn = state.allowIn;
+ state.allowIn = true;
+ expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression();
+ state.allowIn = previousAllowIn;
+
+ for (;;) {
+ if (match(".")) {
+ property = parseNonComputedMember();
+ expr = astNodeFactory.createMemberExpression(".", expr, property);
+ } else if (match("(")) {
+ args = parseArguments();
+ expr = astNodeFactory.createCallExpression(expr, args);
+ } else if (match("[")) {
+ property = parseComputedMember();
+ expr = astNodeFactory.createMemberExpression("[", expr, property);
+ } else {
+ break;
+ }
+ markerApply(marker, expr);
+ }
+
+ return expr;
+}
+
+function parseLeftHandSideExpression() {
+ var previousAllowIn, expr, property,
+ marker = markerCreate();
+
+ previousAllowIn = state.allowIn;
+ expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression();
+ state.allowIn = previousAllowIn;
+
+ while (match(".") || match("[")) {
+ if (match("[")) {
+ property = parseComputedMember();
+ expr = astNodeFactory.createMemberExpression("[", expr, property);
+ } else {
+ property = parseNonComputedMember();
+ expr = astNodeFactory.createMemberExpression(".", expr, property);
+ }
+ markerApply(marker, expr);
+ }
+
+ return expr;
+}
+
+// 11.3 Postfix Expressions
+
+function parsePostfixExpression() {
+ var expr, token,
+ marker = markerCreate();
+
+ expr = parseLeftHandSideExpressionAllowCall();
+
+ if (lookahead.type === Token.Punctuator) {
+ if ((match("++") || match("--")) && !peekLineTerminator()) {
+ // 11.3.1, 11.3.2
+ if (strict && expr.type === astNodeTypes.Identifier && syntax.isRestrictedWord(expr.name)) {
+ throwErrorTolerant({}, Messages.StrictLHSPostfix);
+ }
+
+ if (!isLeftHandSide(expr)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ token = lex();
+ expr = markerApply(marker, astNodeFactory.createPostfixExpression(token.value, expr));
+ }
+ }
+
+ return expr;
+}
+
+// 11.4 Unary Operators
+
+function parseUnaryExpression() {
+ var token, expr,
+ marker;
+
+ if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
+ expr = parsePostfixExpression();
+ } else if (match("++") || match("--")) {
+ marker = markerCreate();
+ token = lex();
+ expr = parseUnaryExpression();
+ // 11.4.4, 11.4.5
+ if (strict && expr.type === astNodeTypes.Identifier && syntax.isRestrictedWord(expr.name)) {
+ throwErrorTolerant({}, Messages.StrictLHSPrefix);
+ }
+
+ if (!isLeftHandSide(expr)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ expr = astNodeFactory.createUnaryExpression(token.value, expr);
+ expr = markerApply(marker, expr);
+ } else if (match("+") || match("-") || match("~") || match("!")) {
+ marker = markerCreate();
+ token = lex();
+ expr = parseUnaryExpression();
+ expr = astNodeFactory.createUnaryExpression(token.value, expr);
+ expr = markerApply(marker, expr);
+ } else if (matchKeyword("delete") || matchKeyword("void") || matchKeyword("typeof")) {
+ marker = markerCreate();
+ token = lex();
+ expr = parseUnaryExpression();
+ expr = astNodeFactory.createUnaryExpression(token.value, expr);
+ expr = markerApply(marker, expr);
+ if (strict && expr.operator === "delete" && expr.argument.type === astNodeTypes.Identifier) {
+ throwErrorTolerant({}, Messages.StrictDelete);
+ }
+ } else {
+ expr = parsePostfixExpression();
+ }
+
+ return expr;
+}
+
+function binaryPrecedence(token, allowIn) {
+ var prec = 0;
+
+ if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
+ return 0;
+ }
+
+ switch (token.value) {
+ case "||":
+ prec = 1;
+ break;
+
+ case "&&":
+ prec = 2;
+ break;
+
+ case "|":
+ prec = 3;
+ break;
+
+ case "^":
+ prec = 4;
+ break;
+
+ case "&":
+ prec = 5;
+ break;
+
+ case "==":
+ case "!=":
+ case "===":
+ case "!==":
+ prec = 6;
+ break;
+
+ case "<":
+ case ">":
+ case "<=":
+ case ">=":
+ case "instanceof":
+ prec = 7;
+ break;
+
+ case "in":
+ prec = allowIn ? 7 : 0;
+ break;
+
+ case "<<":
+ case ">>":
+ case ">>>":
+ prec = 8;
+ break;
+
+ case "+":
+ case "-":
+ prec = 9;
+ break;
+
+ case "*":
+ case "/":
+ case "%":
+ prec = 11;
+ break;
+
+ default:
+ break;
+ }
+
+ return prec;
+}
+
+// 11.5 Multiplicative Operators
+// 11.6 Additive Operators
+// 11.7 Bitwise Shift Operators
+// 11.8 Relational Operators
+// 11.9 Equality Operators
+// 11.10 Binary Bitwise Operators
+// 11.11 Binary Logical Operators
+function parseBinaryExpression() {
+ var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
+ marker, markers;
+
+ previousAllowIn = state.allowIn;
+ state.allowIn = true;
+
+ marker = markerCreate();
+ left = parseUnaryExpression();
+
+ token = lookahead;
+ prec = binaryPrecedence(token, previousAllowIn);
+ if (prec === 0) {
+ return left;
+ }
+ token.prec = prec;
+ lex();
+
+ markers = [marker, markerCreate()];
+ right = parseUnaryExpression();
+
+ stack = [left, token, right];
+
+ while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
+
+ // Reduce: make a binary expression from the three topmost entries.
+ while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
+ right = stack.pop();
+ operator = stack.pop().value;
+ left = stack.pop();
+ expr = astNodeFactory.createBinaryExpression(operator, left, right);
+ markers.pop();
+ marker = markers.pop();
+ markerApply(marker, expr);
+ stack.push(expr);
+ markers.push(marker);
+ }
+
+ // Shift.
+ token = lex();
+ token.prec = prec;
+ stack.push(token);
+ markers.push(markerCreate());
+ expr = parseUnaryExpression();
+ stack.push(expr);
+ }
+
+ state.allowIn = previousAllowIn;
+
+ // Final reduce to clean-up the stack.
+ i = stack.length - 1;
+ expr = stack[i];
+ markers.pop();
+ while (i > 1) {
+ expr = astNodeFactory.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
+ i -= 2;
+ marker = markers.pop();
+ markerApply(marker, expr);
+ }
+
+ return expr;
+}
+
+// 11.12 Conditional Operator
+
+function parseConditionalExpression() {
+ var expr, previousAllowIn, consequent, alternate,
+ marker = markerCreate();
+
+ expr = parseBinaryExpression();
+
+ if (match("?")) {
+ lex();
+ previousAllowIn = state.allowIn;
+ state.allowIn = true;
+ consequent = parseAssignmentExpression();
+ state.allowIn = previousAllowIn;
+ expect(":");
+ alternate = parseAssignmentExpression();
+
+ expr = astNodeFactory.createConditionalExpression(expr, consequent, alternate);
+ markerApply(marker, expr);
+ }
+
+ return expr;
+}
+
+// 11.13 Assignment Operators
+
+function parseAssignmentExpression() {
+ var token, left, right, node,
+ marker,
+ allowGenerators = extra.ecmaFeatures.generators;
+
+ // Note that 'yield' is treated as a keyword in strict mode, but a
+ // contextual keyword (identifier) in non-strict mode, so we need
+ // to use matchKeyword and matchContextualKeyword appropriately.
+ if (allowGenerators && ((state.yieldAllowed && matchContextualKeyword("yield")) || (strict && matchKeyword("yield")))) {
+ return parseYieldExpression();
+ }
+
+ marker = markerCreate();
+ token = lookahead;
+
+ node = left = parseConditionalExpression();
+
+ if (matchAssign()) {
+ // LeftHandSideExpression
+ if (!isLeftHandSide(left)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ // 11.13.1
+ if (strict && left.type === astNodeTypes.Identifier && syntax.isRestrictedWord(left.name)) {
+ throwErrorTolerant(token, Messages.StrictLHSAssignment);
+ }
+
+ token = lex();
+ right = parseAssignmentExpression();
+ node = markerApply(marker, astNodeFactory.createAssignmentExpression(token.value, left, right));
+ }
+
+ return node;
+}
+
+// 11.14 Comma Operator
+
+function parseExpression() {
+ var expr,
+ marker = markerCreate();
+
+ expr = parseAssignmentExpression();
+
+ if (match(",")) {
+ expr = astNodeFactory.createSequenceExpression([ expr ]);
+
+ while (index < length) {
+ if (!match(",")) {
+ break;
+ }
+ lex();
+ expr.expressions.push(parseAssignmentExpression());
+ }
+
+ markerApply(marker, expr);
+ }
+
+ return expr;
+}
+
+// 12.1 Block
+
+function parseStatementList() {
+ var list = [],
+ statement;
+
+ while (index < length) {
+ if (match("}")) {
+ break;
+ }
+ statement = parseSourceElement();
+ if (typeof statement === "undefined") {
+ break;
+ }
+ list.push(statement);
+ }
+
+ return list;
+}
+
+function parseBlock() {
+ var block,
+ marker = markerCreate();
+
+ expect("{");
+
+ block = parseStatementList();
+
+ expect("}");
+
+ return markerApply(marker, astNodeFactory.createBlockStatement(block));
+}
+
+// 12.2 Variable Statement
+
+function parseVariableIdentifier() {
+ var token,
+ marker = markerCreate();
+
+ token = lex();
+
+ if (token.type !== Token.Identifier) {
+ throwUnexpected(token);
+ }
+
+ return markerApply(marker, astNodeFactory.createIdentifier(token.value));
+}
+
+function parseVariableDeclaration(kind) {
+ var init = null, id,
+ marker = markerCreate();
+
+ id = parseVariableIdentifier();
+
+ // 12.2.1
+ if (strict && syntax.isRestrictedWord(id.name)) {
+ throwErrorTolerant({}, Messages.StrictVarName);
+ }
+
+ // TODO: Verify against feature flags
+ if (kind === "const") {
+ expect("=");
+ init = parseAssignmentExpression();
+ } else if (match("=")) {
+ lex();
+ init = parseAssignmentExpression();
+ }
+
+ return markerApply(marker, astNodeFactory.createVariableDeclarator(id, init));
+}
+
+function parseVariableDeclarationList(kind) {
+ var list = [];
+
+ do {
+ list.push(parseVariableDeclaration(kind));
+ if (!match(",")) {
+ break;
+ }
+ lex();
+ } while (index < length);
+
+ return list;
+}
+
+function parseVariableStatement() {
+ var declarations;
+
+ expectKeyword("var");
+
+ declarations = parseVariableDeclarationList();
+
+ consumeSemicolon();
+
+ return astNodeFactory.createVariableDeclaration(declarations, "var");
+}
+
+// kind may be `const` or `let`
+// Both are experimental and not in the specification yet.
+// see http://wiki.ecmascript.org/doku.php?id=harmony:const
+// and http://wiki.ecmascript.org/doku.php?id=harmony:let
+function parseConstLetDeclaration(kind) {
+ var declarations,
+ marker = markerCreate();
+
+ expectKeyword(kind);
+
+ declarations = parseVariableDeclarationList(kind);
+
+ consumeSemicolon();
+
+ return markerApply(marker, astNodeFactory.createVariableDeclaration(declarations, kind));
+}
+
+// 12.3 Empty Statement
+
+function parseEmptyStatement() {
+ expect(";");
+ return astNodeFactory.createEmptyStatement();
+}
+
+// 12.4 Expression Statement
+
+function parseExpressionStatement() {
+ var expr = parseExpression();
+ consumeSemicolon();
+ return astNodeFactory.createExpressionStatement(expr);
+}
+
+// 12.5 If statement
+
+function parseIfStatement() {
+ var test, consequent, alternate;
+
+ expectKeyword("if");
+
+ expect("(");
+
+ test = parseExpression();
+
+ expect(")");
+
+ consequent = parseStatement();
+
+ if (matchKeyword("else")) {
+ lex();
+ alternate = parseStatement();
+ } else {
+ alternate = null;
+ }
+
+ return astNodeFactory.createIfStatement(test, consequent, alternate);
+}
+
+// 12.6 Iteration Statements
+
+function parseDoWhileStatement() {
+ var body, test, oldInIteration;
+
+ expectKeyword("do");
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ body = parseStatement();
+
+ state.inIteration = oldInIteration;
+
+ expectKeyword("while");
+
+ expect("(");
+
+ test = parseExpression();
+
+ expect(")");
+
+ if (match(";")) {
+ lex();
+ }
+
+ return astNodeFactory.createDoWhileStatement(test, body);
+}
+
+function parseWhileStatement() {
+ var test, body, oldInIteration;
+
+ expectKeyword("while");
+
+ expect("(");
+
+ test = parseExpression();
+
+ expect(")");
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ body = parseStatement();
+
+ state.inIteration = oldInIteration;
+
+ return astNodeFactory.createWhileStatement(test, body);
+}
+
+function parseForVariableDeclaration() {
+ var token, declarations,
+ marker = markerCreate();
+
+ token = lex();
+ declarations = parseVariableDeclarationList();
+
+ return markerApply(marker, astNodeFactory.createVariableDeclaration(declarations, token.value));
+}
+
+function parseForStatement(opts) {
+ var init, test, update, left, right, body, operator, oldInIteration;
+ var allowForOf = extra.ecmaFeatures.forOf,
+ allowBlockBindings = extra.ecmaFeatures.blockBindings;
+
+ init = test = update = null;
+
+ expectKeyword("for");
+
+ expect("(");
+
+ if (match(";")) {
+ lex();
+ } else {
+
+ if (matchKeyword("var") ||
+ (allowBlockBindings && (matchKeyword("let") || matchKeyword("const")))
+ ) {
+ state.allowIn = false;
+ init = parseForVariableDeclaration();
+ state.allowIn = true;
+
+ if (init.declarations.length === 1) {
+ if (matchKeyword("in") || (allowForOf && matchContextualKeyword("of"))) {
+ operator = lookahead;
+
+ // TODO: is "var" check here really needed? wasn"t in 1.2.2
+ if (!((operator.value === "in" || init.kind !== "var") && init.declarations[0].init)) {
+ lex();
+ left = init;
+ right = parseExpression();
+ init = null;
+ }
+ }
+ }
+
+ } else {
+ state.allowIn = false;
+ init = parseExpression();
+ state.allowIn = true;
+
+ if (allowForOf && matchContextualKeyword("of")) {
+ operator = lex();
+ left = init;
+ right = parseExpression();
+ init = null;
+ } else if (matchKeyword("in")) {
+ // LeftHandSideExpression
+ if (!isLeftHandSide(init)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInForIn);
+ }
+
+ lex();
+ left = init;
+ right = parseExpression();
+ init = null;
+ }
+ }
+
+ if (typeof left === "undefined") {
+ expect(";");
+ }
+ }
+
+ if (typeof left === "undefined") {
+
+ if (!match(";")) {
+ test = parseExpression();
+ }
+ expect(";");
+
+ if (!match(")")) {
+ update = parseExpression();
+ }
+ }
+
+ expect(")");
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ if (!(opts !== undefined && opts.ignoreBody)) {
+ body = parseStatement();
+ }
+
+ state.inIteration = oldInIteration;
+
+ if (typeof left === "undefined") {
+ return astNodeFactory.createForStatement(init, test, update, body);
+ }
+
+ if (extra.ecmaFeatures.forOf && operator.value === "of") {
+ return astNodeFactory.createForOfStatement(left, right, body);
+ }
+
+ return astNodeFactory.createForInStatement(left, right, body);
+}
+
+// 12.7 The continue statement
+
+function parseContinueStatement() {
+ var label = null, key;
+
+ expectKeyword("continue");
+
+ // Optimize the most common form: "continue;".
+ if (source.charCodeAt(index) === 0x3B) {
+ lex();
+
+ if (!state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return astNodeFactory.createContinueStatement(null);
+ }
+
+ if (peekLineTerminator()) {
+ if (!state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return astNodeFactory.createContinueStatement(null);
+ }
+
+ if (lookahead.type === Token.Identifier) {
+ label = parseVariableIdentifier();
+
+ key = "$" + label.name;
+ if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ throwError({}, Messages.UnknownLabel, label.name);
+ }
+ }
+
+ consumeSemicolon();
+
+ if (label === null && !state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return astNodeFactory.createContinueStatement(label);
+}
+
+// 12.8 The break statement
+
+function parseBreakStatement() {
+ var label = null, key;
+
+ expectKeyword("break");
+
+ // Catch the very common case first: immediately a semicolon (U+003B).
+ if (source.charCodeAt(index) === 0x3B) {
+ lex();
+
+ if (!(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return astNodeFactory.createBreakStatement(null);
+ }
+
+ if (peekLineTerminator()) {
+ if (!(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return astNodeFactory.createBreakStatement(null);
+ }
+
+ if (lookahead.type === Token.Identifier) {
+ label = parseVariableIdentifier();
+
+ key = "$" + label.name;
+ if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ throwError({}, Messages.UnknownLabel, label.name);
+ }
+ }
+
+ consumeSemicolon();
+
+ if (label === null && !(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return astNodeFactory.createBreakStatement(label);
+}
+
+// 12.9 The return statement
+
+function parseReturnStatement() {
+ var argument = null;
+
+ expectKeyword("return");
+
+ if (!state.inFunctionBody) {
+ throwErrorTolerant({}, Messages.IllegalReturn);
+ }
+
+ // "return" followed by a space and an identifier is very common.
+ if (source.charCodeAt(index) === 0x20) {
+ if (syntax.isIdentifierStart(source.charCodeAt(index + 1))) {
+ argument = parseExpression();
+ consumeSemicolon();
+ return astNodeFactory.createReturnStatement(argument);
+ }
+ }
+
+ if (peekLineTerminator()) {
+ return astNodeFactory.createReturnStatement(null);
+ }
+
+ if (!match(";")) {
+ if (!match("}") && lookahead.type !== Token.EOF) {
+ argument = parseExpression();
+ }
+ }
+
+ consumeSemicolon();
+
+ return astNodeFactory.createReturnStatement(argument);
+}
+
+// 12.10 The with statement
+
+function parseWithStatement() {
+ var object, body;
+
+ if (strict) {
+ // TODO(ikarienator): Should we update the test cases instead?
+ skipComment();
+ throwErrorTolerant({}, Messages.StrictModeWith);
+ }
+
+ expectKeyword("with");
+
+ expect("(");
+
+ object = parseExpression();
+
+ expect(")");
+
+ body = parseStatement();
+
+ return astNodeFactory.createWithStatement(object, body);
+}
+
+// 12.10 The swith statement
+
+function parseSwitchCase() {
+ var test, consequent = [], statement,
+ marker = markerCreate();
+
+ if (matchKeyword("default")) {
+ lex();
+ test = null;
+ } else {
+ expectKeyword("case");
+ test = parseExpression();
+ }
+ expect(":");
+
+ while (index < length) {
+ if (match("}") || matchKeyword("default") || matchKeyword("case")) {
+ break;
+ }
+ statement = parseStatement();
+ consequent.push(statement);
+ }
+
+ return markerApply(marker, astNodeFactory.createSwitchCase(test, consequent));
+}
+
+function parseSwitchStatement() {
+ var discriminant, cases, clause, oldInSwitch, defaultFound;
+
+ expectKeyword("switch");
+
+ expect("(");
+
+ discriminant = parseExpression();
+
+ expect(")");
+
+ expect("{");
+
+ cases = [];
+
+ if (match("}")) {
+ lex();
+ return astNodeFactory.createSwitchStatement(discriminant, cases);
+ }
+
+ oldInSwitch = state.inSwitch;
+ state.inSwitch = true;
+ defaultFound = false;
+
+ while (index < length) {
+ if (match("}")) {
+ break;
+ }
+ clause = parseSwitchCase();
+ if (clause.test === null) {
+ if (defaultFound) {
+ throwError({}, Messages.MultipleDefaultsInSwitch);
+ }
+ defaultFound = true;
+ }
+ cases.push(clause);
+ }
+
+ state.inSwitch = oldInSwitch;
+
+ expect("}");
+
+ return astNodeFactory.createSwitchStatement(discriminant, cases);
+}
+
+// 12.13 The throw statement
+
+function parseThrowStatement() {
+ var argument;
+
+ expectKeyword("throw");
+
+ if (peekLineTerminator()) {
+ throwError({}, Messages.NewlineAfterThrow);
+ }
+
+ argument = parseExpression();
+
+ consumeSemicolon();
+
+ return astNodeFactory.createThrowStatement(argument);
+}
+
+// 12.14 The try statement
+
+function parseCatchClause() {
+ var param, body,
+ marker = markerCreate();
+
+ expectKeyword("catch");
+
+ expect("(");
+ if (match(")")) {
+ throwUnexpected(lookahead);
+ }
+
+ param = parseVariableIdentifier();
+ // 12.14.1
+ if (strict && syntax.isRestrictedWord(param.name)) {
+ throwErrorTolerant({}, Messages.StrictCatchVariable);
+ }
+
+ expect(")");
+ body = parseBlock();
+ return markerApply(marker, astNodeFactory.createCatchClause(param, body));
+}
+
+function parseTryStatement() {
+ var block, handlers = [], finalizer = null;
+
+ expectKeyword("try");
+
+ block = parseBlock();
+
+ if (matchKeyword("catch")) {
+ handlers.push(parseCatchClause());
+ }
+
+ if (matchKeyword("finally")) {
+ lex();
+ finalizer = parseBlock();
+ }
+
+ if (handlers.length === 0 && !finalizer) {
+ throwError({}, Messages.NoCatchOrFinally);
+ }
+
+ return astNodeFactory.createTryStatement(block, [], handlers, finalizer);
+}
+
+// 12.15 The debugger statement
+
+function parseDebuggerStatement() {
+ expectKeyword("debugger");
+
+ consumeSemicolon();
+
+ return astNodeFactory.createDebuggerStatement();
+}
+
+// 12 Statements
+
+function parseStatement() {
+ var type = lookahead.type,
+ expr,
+ labeledBody,
+ key,
+ marker;
+
+ if (type === Token.EOF) {
+ throwUnexpected(lookahead);
+ }
+
+ if (type === Token.Punctuator && lookahead.value === "{") {
+ return parseBlock();
+ }
+
+ marker = markerCreate();
+
+ if (type === Token.Punctuator) {
+ switch (lookahead.value) {
+ case ";":
+ return markerApply(marker, parseEmptyStatement());
+ case "(":
+ return markerApply(marker, parseExpressionStatement());
+ default:
+ break;
+ }
+ }
+
+ marker = markerCreate();
+
+ if (type === Token.Keyword) {
+ switch (lookahead.value) {
+ case "break":
+ return markerApply(marker, parseBreakStatement());
+ case "continue":
+ return markerApply(marker, parseContinueStatement());
+ case "debugger":
+ return markerApply(marker, parseDebuggerStatement());
+ case "do":
+ return markerApply(marker, parseDoWhileStatement());
+ case "for":
+ return markerApply(marker, parseForStatement());
+ case "function":
+ return markerApply(marker, parseFunctionDeclaration());
+ case "if":
+ return markerApply(marker, parseIfStatement());
+ case "return":
+ return markerApply(marker, parseReturnStatement());
+ case "switch":
+ return markerApply(marker, parseSwitchStatement());
+ case "throw":
+ return markerApply(marker, parseThrowStatement());
+ case "try":
+ return markerApply(marker, parseTryStatement());
+ case "var":
+ return markerApply(marker, parseVariableStatement());
+ case "while":
+ return markerApply(marker, parseWhileStatement());
+ case "with":
+ return markerApply(marker, parseWithStatement());
+ default:
+ break;
+ }
+ }
+
+ marker = markerCreate();
+ expr = parseExpression();
+
+ // 12.12 Labelled Statements
+ if ((expr.type === astNodeTypes.Identifier) && match(":")) {
+ lex();
+
+ key = "$" + expr.name;
+ if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ throwError({}, Messages.Redeclaration, "Label", expr.name);
+ }
+
+ state.labelSet[key] = true;
+ labeledBody = parseStatement();
+ delete state.labelSet[key];
+ return markerApply(marker, astNodeFactory.createLabeledStatement(expr, labeledBody));
+ }
+
+ consumeSemicolon();
+
+ return markerApply(marker, astNodeFactory.createExpressionStatement(expr));
+}
+
+// 13 Function Definition
+
+// function parseConciseBody() {
+// if (match("{")) {
+// return parseFunctionSourceElements();
+// }
+// return parseAssignmentExpression();
+// }
+
+function parseFunctionSourceElements() {
+ var sourceElement, sourceElements = [], token, directive, firstRestricted,
+ oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody,
+ marker = markerCreate();
+
+ expect("{");
+
+ while (index < length) {
+ if (lookahead.type !== Token.StringLiteral) {
+ break;
+ }
+ token = lookahead;
+
+ sourceElement = parseSourceElement();
+ sourceElements.push(sourceElement);
+ if (sourceElement.expression.type !== astNodeTypes.Literal) {
+ // this is not directive
+ break;
+ }
+ directive = source.slice(token.range[0] + 1, token.range[1] - 1);
+ if (directive === "use strict") {
+ strict = true;
+ if (firstRestricted) {
+ throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
+ }
+ } else {
+ if (!firstRestricted && token.octal) {
+ firstRestricted = token;
+ }
+ }
+ }
+
+ oldLabelSet = state.labelSet;
+ oldInIteration = state.inIteration;
+ oldInSwitch = state.inSwitch;
+ oldInFunctionBody = state.inFunctionBody;
+
+ state.labelSet = {};
+ state.inIteration = false;
+ state.inSwitch = false;
+ state.inFunctionBody = true;
+
+ while (index < length) {
+
+ if (match("}")) {
+ break;
+ }
+
+ sourceElement = parseSourceElement();
+
+ if (typeof sourceElement === "undefined") {
+ break;
+ }
+
+ sourceElements.push(sourceElement);
+ }
+
+ expect("}");
+
+ state.labelSet = oldLabelSet;
+ state.inIteration = oldInIteration;
+ state.inSwitch = oldInSwitch;
+ state.inFunctionBody = oldInFunctionBody;
+
+ return markerApply(marker, astNodeFactory.createBlockStatement(sourceElements));
+}
+
+function parseParams(firstRestricted) {
+ var param, params = [], token, stricted, paramSet, key, message;
+ expect("(");
+
+ if (!match(")")) {
+ paramSet = {};
+ while (index < length) {
+ token = lookahead;
+ param = parseVariableIdentifier();
+ key = "$" + token.value;
+ if (strict) {
+ if (syntax.isRestrictedWord(token.value)) {
+ stricted = token;
+ message = Messages.StrictParamName;
+ }
+ if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
+ stricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ } else if (!firstRestricted) {
+ if (syntax.isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictParamName;
+ } else if (syntax.isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
+ firstRestricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ }
+ params.push(param);
+ paramSet[key] = true;
+ if (match(")")) {
+ break;
+ }
+ expect(",");
+ }
+ }
+
+ expect(")");
+
+ return {
+ params: params,
+ stricted: stricted,
+ firstRestricted: firstRestricted,
+ message: message
+ };
+}
+
+function parseFunctionDeclaration() {
+ var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator,
+ marker = markerCreate(),
+ allowGenerators = extra.ecmaFeatures.generators;
+
+ expectKeyword("function");
+
+ generator = false;
+ if (allowGenerators && match("*")) {
+ lex();
+ generator = true;
+ }
+
+ token = lookahead;
+
+ id = parseVariableIdentifier();
+
+ if (strict) {
+ if (syntax.isRestrictedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictFunctionName);
+ }
+ } else {
+ if (syntax.isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictFunctionName;
+ } else if (syntax.isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ }
+ }
+
+ tmp = parseParams(firstRestricted);
+ firstRestricted = tmp.firstRestricted;
+ if (tmp.message) {
+ message = tmp.message;
+ }
+
+ previousStrict = strict;
+ previousYieldAllowed = state.yieldAllowed;
+ state.yieldAllowed = generator;
+
+ body = parseFunctionSourceElements();
+
+ if (strict && firstRestricted) {
+ throwError(firstRestricted, message);
+ }
+ if (strict && tmp.stricted) {
+ throwErrorTolerant(tmp.stricted, message);
+ }
+ strict = previousStrict;
+ state.yieldAllowed = previousYieldAllowed;
+
+ return markerApply(
+ marker,
+ astNodeFactory.createFunctionDeclaration(
+ id,
+ tmp.params,
+ tmp.defaults,
+ body,
+ tmp.rest,
+ generator,
+ false
+ )
+ );
+ }
+
+function parseFunctionExpression() {
+ var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator,
+ marker = markerCreate(),
+ allowGenerators = extra.ecmaFeatures.generators;
+
+ expectKeyword("function");
+
+ generator = false;
+
+ if (allowGenerators && match("*")) {
+ lex();
+ generator = true;
+ }
+
+ if (!match("(")) {
+ token = lookahead;
+ id = parseVariableIdentifier();
+ if (strict) {
+ if (syntax.isRestrictedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictFunctionName);
+ }
+ } else {
+ if (syntax.isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictFunctionName;
+ } else if (syntax.isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ }
+ }
+ }
+
+ tmp = parseParams(firstRestricted);
+ firstRestricted = tmp.firstRestricted;
+ if (tmp.message) {
+ message = tmp.message;
+ }
+
+ previousStrict = strict;
+ previousYieldAllowed = state.yieldAllowed;
+ state.yieldAllowed = generator;
+
+ body = parseFunctionSourceElements();
+
+ if (strict && firstRestricted) {
+ throwError(firstRestricted, message);
+ }
+ if (strict && tmp.stricted) {
+ throwErrorTolerant(tmp.stricted, message);
+ }
+ strict = previousStrict;
+ state.yieldAllowed = previousYieldAllowed;
+
+ return markerApply(
+ marker,
+ astNodeFactory.createFunctionExpression(
+ id,
+ tmp.params,
+ tmp.defaults,
+ body,
+ tmp.rest,
+ generator,
+ false
+ )
+ );
+}
+
+function parseYieldExpression() {
+ var yieldToken, delegateFlag, expr, marker = markerCreate();
+
+ yieldToken = lex();
+ assert(yieldToken.value === "yield", "Called parseYieldExpression with non-yield lookahead.");
+
+ if (!state.yieldAllowed) {
+ throwErrorTolerant({}, Messages.IllegalYield);
+ }
+
+ delegateFlag = false;
+ if (match("*")) {
+ lex();
+ delegateFlag = true;
+ }
+
+ expr = parseAssignmentExpression();
+
+ return markerApply(marker, astNodeFactory.createYieldExpression(expr, delegateFlag));
+}
+
+
+// 14 Program
+
+function parseSourceElement() {
+ if (lookahead.type === Token.Keyword) {
+ switch (lookahead.value) {
+ case "function":
+ return parseFunctionDeclaration();
+ case "const":
+ case "let":
+ if (extra.ecmaFeatures.blockBindings) {
+ return parseConstLetDeclaration(lookahead.value);
+ }
+ /* falls through */
+ default:
+ return parseStatement();
+ }
+ }
+
+ if (lookahead.type !== Token.EOF) {
+ return parseStatement();
+ }
+}
+
+function parseSourceElements() {
+ var sourceElement, sourceElements = [], token, directive, firstRestricted;
+
+ while (index < length) {
+ token = lookahead;
+ if (token.type !== Token.StringLiteral) {
+ break;
+ }
+
+ sourceElement = parseSourceElement();
+ sourceElements.push(sourceElement);
+ if (sourceElement.expression.type !== astNodeTypes.Literal) {
+ // this is not directive
+ break;
+ }
+ directive = source.slice(token.range[0] + 1, token.range[1] - 1);
+ if (directive === "use strict") {
+ strict = true;
+ if (firstRestricted) {
+ throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
+ }
+ } else {
+ if (!firstRestricted && token.octal) {
+ firstRestricted = token;
+ }
+ }
+ }
+
+ while (index < length) {
+ sourceElement = parseSourceElement();
+ /* istanbul ignore if */
+ if (typeof sourceElement === "undefined") {
+ break;
+ }
+ sourceElements.push(sourceElement);
+ }
+ return sourceElements;
+}
+
+function parseProgram() {
+ var body,
+ marker;
+
+ skipComment();
+ peek();
+ marker = markerCreate();
+ strict = false;
+
+ body = parseSourceElements();
+ return markerApply(marker, astNodeFactory.createProgram(body));
+}
+
+function filterTokenLocation() {
+ var i, entry, token, tokens = [];
+
+ for (i = 0; i < extra.tokens.length; ++i) {
+ entry = extra.tokens[i];
+ token = {
+ type: entry.type,
+ value: entry.value
+ };
+ if (entry.regex) {
+ token.regex = {
+ pattern: entry.regex.pattern,
+ flags: entry.regex.flags
+ };
+ }
+ if (extra.range) {
+ token.range = entry.range;
+ }
+ if (extra.loc) {
+ token.loc = entry.loc;
+ }
+ tokens.push(token);
+ }
+
+ extra.tokens = tokens;
+}
+
+//------------------------------------------------------------------------------
+// Tokenizer
+//------------------------------------------------------------------------------
+
+function tokenize(code, options) {
+ var toString,
+ tokens;
+
+ toString = String;
+ if (typeof code !== "string" && !(code instanceof String)) {
+ code = toString(code);
+ }
+
+ source = code;
+ index = 0;
+ lineNumber = (source.length > 0) ? 1 : 0;
+ lineStart = 0;
+ length = source.length;
+ lookahead = null;
+ state = {
+ allowIn: true,
+ labelSet: {},
+ inFunctionBody: false,
+ inIteration: false,
+ inSwitch: false,
+ lastCommentStart: -1,
+ yieldAllowed: false,
+ inJSXSpreadAttribute: false,
+ inJSXChild: false,
+ inJSXTag: false
+ };
+
+ extra = {
+ ecmaFeatures: defaultFeatures
+ };
+
+ // Options matching.
+ options = options || {};
+
+ // Of course we collect tokens here.
+ options.tokens = true;
+ extra.tokens = [];
+ extra.tokenize = true;
+ // The following two fields are necessary to compute the Regex tokens.
+ extra.openParenToken = -1;
+ extra.openCurlyToken = -1;
+
+ extra.range = (typeof options.range === "boolean") && options.range;
+ extra.loc = (typeof options.loc === "boolean") && options.loc;
+
+ if (typeof options.comment === "boolean" && options.comment) {
+ extra.comments = [];
+ }
+ if (typeof options.tolerant === "boolean" && options.tolerant) {
+ extra.errors = [];
+ }
+
+ // apply parsing flags
+ if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") {
+ extra.ecmaFeatures = options.ecmaFeatures;
+ }
+
+ try {
+ peek();
+ if (lookahead.type === Token.EOF) {
+ return extra.tokens;
+ }
+
+ lex();
+ while (lookahead.type !== Token.EOF) {
+ try {
+ lex();
+ } catch (lexError) {
+ if (extra.errors) {
+ extra.errors.push(lexError);
+ // We have to break on the first error
+ // to avoid infinite loops.
+ break;
+ } else {
+ throw lexError;
+ }
+ }
+ }
+
+ filterTokenLocation();
+ tokens = extra.tokens;
+
+ if (typeof extra.comments !== "undefined") {
+ tokens.comments = extra.comments;
+ }
+ if (typeof extra.errors !== "undefined") {
+ tokens.errors = extra.errors;
+ }
+ } catch (e) {
+ throw e;
+ } finally {
+ extra = {};
+ }
+ return tokens;
+}
+
+//------------------------------------------------------------------------------
+// Parser
+//------------------------------------------------------------------------------
+
+function parse(code, options) {
+ var program, toString;
+
+ toString = String;
+ if (typeof code !== "string" && !(code instanceof String)) {
+ code = toString(code);
+ }
+
+ source = code;
+ index = 0;
+ lineNumber = (source.length > 0) ? 1 : 0;
+ lineStart = 0;
+ length = source.length;
+ lookahead = null;
+ state = {
+ allowIn: true,
+ labelSet: {},
+ inFunctionBody: false,
+ inIteration: false,
+ inSwitch: false,
+ lastCommentStart: -1,
+ yieldAllowed: false,
+ inJSXSpreadAttribute: false,
+ inJSXChild: false,
+ inJSXTag: false
+ };
+
+ extra = {
+ ecmaFeatures: defaultFeatures
+ };
+
+ if (typeof options !== "undefined") {
+ extra.range = (typeof options.range === "boolean") && options.range;
+ extra.loc = (typeof options.loc === "boolean") && options.loc;
+ extra.attachComment = (typeof options.attachComment === "boolean") && options.attachComment;
+
+ // apply parsing flags
+ if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") {
+ extra.ecmaFeatures = options.ecmaFeatures;
+ }
+
+ if (extra.loc && options.source !== null && options.source !== undefined) {
+ extra.source = toString(options.source);
+ }
+
+ if (typeof options.tokens === "boolean" && options.tokens) {
+ extra.tokens = [];
+ }
+ if (typeof options.comment === "boolean" && options.comment) {
+ extra.comments = [];
+ }
+ if (typeof options.tolerant === "boolean" && options.tolerant) {
+ extra.errors = [];
+ }
+ if (extra.attachComment) {
+ extra.range = true;
+ extra.comments = [];
+ extra.bottomRightStack = [];
+ extra.trailingComments = [];
+ extra.leadingComments = [];
+ }
+ }
+
+ try {
+ program = parseProgram();
+ if (typeof extra.comments !== "undefined") {
+ program.comments = extra.comments;
+ }
+ if (typeof extra.tokens !== "undefined") {
+ filterTokenLocation();
+ program.tokens = extra.tokens;
+ }
+ if (typeof extra.errors !== "undefined") {
+ program.errors = extra.errors;
+ }
+ } catch (e) {
+ throw e;
+ } finally {
+ extra = {};
+ }
+
+ return program;
+}
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+exports.version = require("./package.json").version;
+
+exports.tokenize = tokenize;
+
+exports.parse = parse;
+
+// Deep copy.
+/* istanbul ignore next */
+exports.Syntax = (function () {
+ var name, types = {};
+
+ if (typeof Object.create === "function") {
+ types = Object.create(null);
+ }
+
+ for (name in astNodeTypes) {
+ if (astNodeTypes.hasOwnProperty(name)) {
+ types[name] = astNodeTypes[name];
+ }
+ }
+
+ if (typeof Object.freeze === "function") {
+ Object.freeze(types);
+ }
+
+ return types;
+}());
+
+},{"./lib/ast-node-factory":14,"./lib/ast-node-types":15,"./lib/features":16,"./lib/messages":17,"./lib/syntax":18,"./lib/token-info":19,"./lib/xhtml-entities":20,"./package.json":21}],14:[function(require,module,exports){
+/**
+ * @fileoverview A factory for creating AST nodes
+ * @author Fred K. Schott
+ * @copyright 2014 Fred K. Schott. All rights reserved.
+ * @copyright 2011-2013 Ariya Hidayat
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var astNodeTypes = require("./ast-node-types");
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+
+ /**
+ * Create an Array Expression ASTNode out of an array of elements
+ * @param {ASTNode[]} elements An array of ASTNode elements
+ * @returns {ASTNode} An ASTNode representing the entire array expression
+ */
+ createArrayExpression: function (elements) {
+ return {
+ type: astNodeTypes.ArrayExpression,
+ elements: elements
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an assignment expression
+ * @param {ASTNode} operator The assignment operator
+ * @param {ASTNode} left The left operand
+ * @param {ASTNode} right The right operand
+ * @returns {ASTNode} An ASTNode representing the entire assignment expression
+ */
+ createAssignmentExpression: function (operator, left, right) {
+ return {
+ type: astNodeTypes.AssignmentExpression,
+ operator: operator,
+ left: left,
+ right: right
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a binary expression
+ * @param {ASTNode} operator The assignment operator
+ * @param {ASTNode} left The left operand
+ * @param {ASTNode} right The right operand
+ * @returns {ASTNode} An ASTNode representing the entire binary expression
+ */
+ createBinaryExpression: function (operator, left, right) {
+ var type = (operator === "||" || operator === "&&") ? astNodeTypes.LogicalExpression :
+ astNodeTypes.BinaryExpression;
+ return {
+ type: type,
+ operator: operator,
+ left: left,
+ right: right
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a block statement
+ * @param {ASTNode} body The block statement body
+ * @returns {ASTNode} An ASTNode representing the entire block statement
+ */
+ createBlockStatement: function (body) {
+ return {
+ type: astNodeTypes.BlockStatement,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a break statement
+ * @param {ASTNode} label The break statement label
+ * @returns {ASTNode} An ASTNode representing the break statement
+ */
+ createBreakStatement: function (label) {
+ return {
+ type: astNodeTypes.BreakStatement,
+ label: label
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a call expression
+ * @param {ASTNode} callee The function being called
+ * @param {ASTNode[]} args An array of ASTNodes representing the function call arguments
+ * @returns {ASTNode} An ASTNode representing the entire call expression
+ */
+ createCallExpression: function (callee, args) {
+ return {
+ type: astNodeTypes.CallExpression,
+ callee: callee,
+ "arguments": args
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a catch clause/block
+ * @param {ASTNode} param Any catch clause exeption/conditional parameter information
+ * @param {ASTNode} body The catch block body
+ * @returns {ASTNode} An ASTNode representing the entire catch clause
+ */
+ createCatchClause: function (param, body) {
+ return {
+ type: astNodeTypes.CatchClause,
+ param: param,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a conditional expression
+ * @param {ASTNode} test The conditional to evaluate
+ * @param {ASTNode} consequent The code to be run if the test returns true
+ * @param {ASTNode} alternate The code to be run if the test returns false
+ * @returns {ASTNode} An ASTNode representing the entire conditional expression
+ */
+ createConditionalExpression: function (test, consequent, alternate) {
+ return {
+ type: astNodeTypes.ConditionalExpression,
+ test: test,
+ consequent: consequent,
+ alternate: alternate
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a continue statement
+ * @param {?ASTNode} label The optional continue label (null if not set)
+ * @returns {ASTNode} An ASTNode representing the continue statement
+ */
+ createContinueStatement: function (label) {
+ return {
+ type: astNodeTypes.ContinueStatement,
+ label: label
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a debugger statement
+ * @returns {ASTNode} An ASTNode representing the debugger statement
+ */
+ createDebuggerStatement: function () {
+ return {
+ type: astNodeTypes.DebuggerStatement
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an empty statement
+ * @returns {ASTNode} An ASTNode representing an empty statement
+ */
+ createEmptyStatement: function () {
+ return {
+ type: astNodeTypes.EmptyStatement
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an expression statement
+ * @param {ASTNode} expression The expression
+ * @returns {ASTNode} An ASTNode representing an expression statement
+ */
+ createExpressionStatement: function (expression) {
+ return {
+ type: astNodeTypes.ExpressionStatement,
+ expression: expression
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a while statement
+ * @param {ASTNode} test The while conditional
+ * @param {ASTNode} body The while loop body
+ * @returns {ASTNode} An ASTNode representing a while statement
+ */
+ createWhileStatement: function (test, body) {
+ return {
+ type: astNodeTypes.WhileStatement,
+ test: test,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a do..while statement
+ * @param {ASTNode} test The do..while conditional
+ * @param {ASTNode} body The do..while loop body
+ * @returns {ASTNode} An ASTNode representing a do..while statement
+ */
+ createDoWhileStatement: function (test, body) {
+ return {
+ type: astNodeTypes.DoWhileStatement,
+ body: body,
+ test: test
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a for statement
+ * @param {ASTNode} init The initialization expression
+ * @param {ASTNode} test The conditional test expression
+ * @param {ASTNode} update The update expression
+ * @param {ASTNode} body The statement body
+ * @returns {ASTNode} An ASTNode representing a for statement
+ */
+ createForStatement: function (init, test, update, body) {
+ return {
+ type: astNodeTypes.ForStatement,
+ init: init,
+ test: test,
+ update: update,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a for..in statement
+ * @param {ASTNode} left The left-side variable for the property name
+ * @param {ASTNode} right The right-side object
+ * @param {ASTNode} body The statement body
+ * @returns {ASTNode} An ASTNode representing a for..in statement
+ */
+ createForInStatement: function (left, right, body) {
+ return {
+ type: astNodeTypes.ForInStatement,
+ left: left,
+ right: right,
+ body: body,
+ each: false
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a for..of statement
+ * @param {ASTNode} left The left-side variable for the property value
+ * @param {ASTNode} right The right-side object
+ * @param {ASTNode} body The statement body
+ * @returns {ASTNode} An ASTNode representing a for..of statement
+ */
+ createForOfStatement: function (left, right, body) {
+ return {
+ type: astNodeTypes.ForOfStatement,
+ left: left,
+ right: right,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a function declaration
+ * @param {ASTNode} id The function name
+ * @param {ASTNode} params The function arguments
+ * @param {ASTNode} defaults Any default arguments (ES6-only feature)
+ * @param {ASTNode} body The function body
+ * @param {ASTNode} rest The node representing a rest argument.
+ * @param {boolean} generator True if the function is a generator, false if not.
+ * @param {boolean} expression True if the function is created via an expression.
+ * Always false for declarations, but kept here to be in sync with
+ * FunctionExpression objects.
+ * @returns {ASTNode} An ASTNode representing a function declaration
+ */
+ createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression) {
+ return {
+ type: astNodeTypes.FunctionDeclaration,
+ id: id,
+ params: params,
+ defaults: defaults || [],
+ body: body,
+ rest: rest || null,
+ generator: !!generator,
+ expression: !!expression
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a function expression
+ * @param {ASTNode} id The function name
+ * @param {ASTNode} params The function arguments
+ * @param {ASTNode} defaults Any default arguments (ES6-only feature)
+ * @param {ASTNode} body The function body
+ * @param {ASTNode} rest The node representing a rest argument.
+ * @param {boolean} generator True if the function is a generator, false if not.
+ * @param {boolean} expression True if the function is created via an expression.
+ * @returns {ASTNode} An ASTNode representing a function declaration
+ */
+ createFunctionExpression: function (id, params, defaults, body, rest, generator, expression) {
+ return {
+ type: astNodeTypes.FunctionExpression,
+ id: id,
+ params: params,
+ defaults: defaults || [],
+ body: body,
+ rest: rest || null,
+ generator: !!generator,
+ expression: !!expression
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an identifier
+ * @param {ASTNode} name The identifier name
+ * @returns {ASTNode} An ASTNode representing an identifier
+ */
+ createIdentifier: function (name) {
+ return {
+ type: astNodeTypes.Identifier,
+ name: name
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an if statement
+ * @param {ASTNode} test The if conditional expression
+ * @param {ASTNode} consequent The consequent if statement to run
+ * @param {ASTNode} alternate the "else" alternate statement
+ * @returns {ASTNode} An ASTNode representing an if statement
+ */
+ createIfStatement: function (test, consequent, alternate) {
+ return {
+ type: astNodeTypes.IfStatement,
+ test: test,
+ consequent: consequent,
+ alternate: alternate
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a labeled statement
+ * @param {ASTNode} label The statement label
+ * @param {ASTNode} body The labeled statement body
+ * @returns {ASTNode} An ASTNode representing a labeled statement
+ */
+ createLabeledStatement: function (label, body) {
+ return {
+ type: astNodeTypes.LabeledStatement,
+ label: label,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode literal from the source code
+ * @param {ASTNode} token The ASTNode token
+ * @param {string} source The source code to get the literal from
+ * @returns {ASTNode} An ASTNode representing the new literal
+ */
+ createLiteralFromSource: function (token, source) {
+ var node = {
+ type: astNodeTypes.Literal,
+ value: token.value,
+ raw: source.slice(token.range[0], token.range[1])
+ };
+
+ // regular expressions have regex properties
+ if (token.regex) {
+ node.regex = token.regex;
+ }
+
+ return node;
+ },
+
+ /**
+ * Create an ASTNode representation of a member expression
+ * @param {string} accessor The member access method (bracket or period)
+ * @param {ASTNode} object The object being referenced
+ * @param {ASTNode} property The object-property being referenced
+ * @returns {ASTNode} An ASTNode representing a member expression
+ */
+ createMemberExpression: function (accessor, object, property) {
+ return {
+ type: astNodeTypes.MemberExpression,
+ computed: accessor === "[",
+ object: object,
+ property: property
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a new expression
+ * @param {ASTNode} callee The constructor for the new object type
+ * @param {ASTNode} args The arguments passed to the constructor
+ * @returns {ASTNode} An ASTNode representing a new expression
+ */
+ createNewExpression: function (callee, args) {
+ return {
+ type: astNodeTypes.NewExpression,
+ callee: callee,
+ "arguments": args
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a new object expression
+ * @param {ASTNode[]} properties An array of ASTNodes that represent all object
+ * properties and associated values
+ * @returns {ASTNode} An ASTNode representing a new object expression
+ */
+ createObjectExpression: function (properties) {
+ return {
+ type: astNodeTypes.ObjectExpression,
+ properties: properties
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a postfix expression
+ * @param {string} operator The postfix operator ("++", "--", etc.)
+ * @param {ASTNode} argument The operator argument
+ * @returns {ASTNode} An ASTNode representing a postfix expression
+ */
+ createPostfixExpression: function (operator, argument) {
+ return {
+ type: astNodeTypes.UpdateExpression,
+ operator: operator,
+ argument: argument,
+ prefix: false
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an entire program
+ * @param {ASTNode} body The program body
+ * @returns {ASTNode} An ASTNode representing an entire program
+ */
+ createProgram: function (body) {
+ return {
+ type: astNodeTypes.Program,
+ body: body
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of an object property
+ * @param {string} kind The type of property represented ("get", "set", etc.)
+ * @param {ASTNode} key The property key
+ * @param {ASTNode} value The new property value
+ * @param {boolean} method True if the property is also a method (value is a function)
+ * @param {boolean} shorthand True if the property is shorthand
+ * @param {boolean} computed True if the property value has been computed
+ * @returns {ASTNode} An ASTNode representing an object property
+ */
+ createProperty: function (kind, key, value, method, shorthand, computed) {
+ return {
+ type: astNodeTypes.Property,
+ key: key,
+ value: value,
+ kind: kind,
+ method: method,
+ shorthand: shorthand,
+ computed: computed
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a return statement
+ * @param {?ASTNode} argument The return argument, null if no argument is provided
+ * @returns {ASTNode} An ASTNode representing a return statement
+ */
+ createReturnStatement: function (argument) {
+ return {
+ type: astNodeTypes.ReturnStatement,
+ argument: argument
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a sequence of expressions
+ * @param {ASTNode[]} expressions An array containing each expression, in order
+ * @returns {ASTNode} An ASTNode representing a sequence of expressions
+ */
+ createSequenceExpression: function (expressions) {
+ return {
+ type: astNodeTypes.SequenceExpression,
+ expressions: expressions
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a switch case statement
+ * @param {ASTNode} test The case value to test against the switch value
+ * @param {ASTNode} consequent The consequent case statement
+ * @returns {ASTNode} An ASTNode representing a switch case
+ */
+ createSwitchCase: function (test, consequent) {
+ return {
+ type: astNodeTypes.SwitchCase,
+ test: test,
+ consequent: consequent
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a switch statement
+ * @param {ASTNode} discriminant An expression to test against each case value
+ * @param {ASTNode[]} cases An array of switch case statements
+ * @returns {ASTNode} An ASTNode representing a switch statement
+ */
+ createSwitchStatement: function (discriminant, cases) {
+ return {
+ type: astNodeTypes.SwitchStatement,
+ discriminant: discriminant,
+ cases: cases
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a this statement
+ * @returns {ASTNode} An ASTNode representing a this statement
+ */
+ createThisExpression: function () {
+ return {
+ type: astNodeTypes.ThisExpression
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a throw statement
+ * @param {ASTNode} argument The argument to throw
+ * @returns {ASTNode} An ASTNode representing a throw statement
+ */
+ createThrowStatement: function (argument) {
+ return {
+ type: astNodeTypes.ThrowStatement,
+ argument: argument
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a try statement
+ * @param {ASTNode} block The try block
+ * @param {ASTNode} guardedHandlers Any guarded catch handlers
+ * @param {ASTNode} handlers Any catch handlers
+ * @param {?ASTNode} finalizer The final code block to run after the try/catch has run
+ * @returns {ASTNode} An ASTNode representing a try statement
+ */
+ createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
+ return {
+ type: astNodeTypes.TryStatement,
+ block: block,
+ guardedHandlers: guardedHandlers,
+ handlers: handlers,
+ finalizer: finalizer
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a unary expression
+ * @param {string} operator The unary operator
+ * @param {ASTNode} argument The unary operand
+ * @returns {ASTNode} An ASTNode representing a unary expression
+ */
+ createUnaryExpression: function (operator, argument) {
+ if (operator === "++" || operator === "--") {
+ return {
+ type: astNodeTypes.UpdateExpression,
+ operator: operator,
+ argument: argument,
+ prefix: true
+ };
+ }
+ return {
+ type: astNodeTypes.UnaryExpression,
+ operator: operator,
+ argument: argument,
+ prefix: true
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a variable declaration
+ * @param {ASTNode[]} declarations An array of variable declarations
+ * @param {string} kind The kind of variable created ("var", "let", etc.)
+ * @returns {ASTNode} An ASTNode representing a variable declaration
+ */
+ createVariableDeclaration: function (declarations, kind) {
+ return {
+ type: astNodeTypes.VariableDeclaration,
+ declarations: declarations,
+ kind: kind
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a variable declarator
+ * @param {ASTNode} id The variable ID
+ * @param {ASTNode} init The variable's initial value
+ * @returns {ASTNode} An ASTNode representing a variable declarator
+ */
+ createVariableDeclarator: function (id, init) {
+ return {
+ type: astNodeTypes.VariableDeclarator,
+ id: id,
+ init: init
+ };
+ },
+
+ /**
+ * Create an ASTNode representation of a with statement
+ * @param {ASTNode} object The with statement object expression
+ * @param {ASTNode} body The with statement body
+ * @returns {ASTNode} An ASTNode representing a with statement
+ */
+ createWithStatement: function (object, body) {
+ return {
+ type: astNodeTypes.WithStatement,
+ object: object,
+ body: body
+ };
+ },
+
+ createYieldExpression: function (argument, delegate) {
+ return {
+ type: astNodeTypes.YieldExpression,
+ argument: argument,
+ delegate: delegate
+ };
+ },
+
+ createJSXAttribute: function (name, value) {
+ return {
+ type: astNodeTypes.JSXAttribute,
+ name: name,
+ value: value || null
+ };
+ },
+
+ createJSXSpreadAttribute: function (argument) {
+ return {
+ type: astNodeTypes.JSXSpreadAttribute,
+ argument: argument
+ };
+ },
+
+ createJSXIdentifier: function (name) {
+ return {
+ type: astNodeTypes.JSXIdentifier,
+ name: name
+ };
+ },
+
+ createJSXNamespacedName: function (namespace, name) {
+ return {
+ type: astNodeTypes.JSXNamespacedName,
+ namespace: namespace,
+ name: name
+ };
+ },
+
+ createJSXMemberExpression: function (object, property) {
+ return {
+ type: astNodeTypes.JSXMemberExpression,
+ object: object,
+ property: property
+ };
+ },
+
+ createJSXElement: function (openingElement, closingElement, children) {
+ return {
+ type: astNodeTypes.JSXElement,
+ openingElement: openingElement,
+ closingElement: closingElement,
+ children: children
+ };
+ },
+
+ createJSXEmptyExpression: function () {
+ return {
+ type: astNodeTypes.JSXEmptyExpression
+ };
+ },
+
+ createJSXExpressionContainer: function (expression) {
+ return {
+ type: astNodeTypes.JSXExpressionContainer,
+ expression: expression
+ };
+ },
+
+ createJSXOpeningElement: function (name, attributes, selfClosing) {
+ return {
+ type: astNodeTypes.JSXOpeningElement,
+ name: name,
+ selfClosing: selfClosing,
+ attributes: attributes
+ };
+ },
+
+ createJSXClosingElement: function (name) {
+ return {
+ type: astNodeTypes.JSXClosingElement,
+ name: name
+ };
+ }
+
+};
+
+},{"./ast-node-types":15}],15:[function(require,module,exports){
+/**
+ * @fileoverview The AST node types produced by the parser.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2011-2013 Ariya Hidayat
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+ AssignmentExpression: "AssignmentExpression",
+ ArrayExpression: "ArrayExpression",
+ BlockStatement: "BlockStatement",
+ BinaryExpression: "BinaryExpression",
+ BreakStatement: "BreakStatement",
+ CallExpression: "CallExpression",
+ CatchClause: "CatchClause",
+ ConditionalExpression: "ConditionalExpression",
+ ContinueStatement: "ContinueStatement",
+ DoWhileStatement: "DoWhileStatement",
+ DebuggerStatement: "DebuggerStatement",
+ EmptyStatement: "EmptyStatement",
+ ExpressionStatement: "ExpressionStatement",
+ ForStatement: "ForStatement",
+ ForInStatement: "ForInStatement",
+ ForOfStatement: "ForOfStatement",
+ FunctionDeclaration: "FunctionDeclaration",
+ FunctionExpression: "FunctionExpression",
+ Identifier: "Identifier",
+ IfStatement: "IfStatement",
+ Literal: "Literal",
+ LabeledStatement: "LabeledStatement",
+ LogicalExpression: "LogicalExpression",
+ MemberExpression: "MemberExpression",
+ NewExpression: "NewExpression",
+ ObjectExpression: "ObjectExpression",
+ Program: "Program",
+ Property: "Property",
+ ReturnStatement: "ReturnStatement",
+ SequenceExpression: "SequenceExpression",
+ SwitchStatement: "SwitchStatement",
+ SwitchCase: "SwitchCase",
+ ThisExpression: "ThisExpression",
+ ThrowStatement: "ThrowStatement",
+ TryStatement: "TryStatement",
+ UnaryExpression: "UnaryExpression",
+ UpdateExpression: "UpdateExpression",
+ VariableDeclaration: "VariableDeclaration",
+ VariableDeclarator: "VariableDeclarator",
+ WhileStatement: "WhileStatement",
+ WithStatement: "WithStatement",
+ YieldExpression: "YieldExpression",
+ JSXIdentifier: "JSXIdentifier",
+ JSXNamespacedName: "JSXNamespacedName",
+ JSXMemberExpression: "JSXMemberExpression",
+ JSXEmptyExpression: "JSXEmptyExpression",
+ JSXExpressionContainer: "JSXExpressionContainer",
+ JSXElement: "JSXElement",
+ JSXClosingElement: "JSXClosingElement",
+ JSXOpeningElement: "JSXOpeningElement",
+ JSXAttribute: "JSXAttribute",
+ JSXSpreadAttribute: "JSXSpreadAttribute",
+ JSXText: "JSXText"
+};
+
+},{}],16:[function(require,module,exports){
+/**
+ * @fileoverview The list of feature flags supported by the parser and their default
+ * settings.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+
+ // enable parsing of let and const
+ blockBindings: true,
+
+ // enable parsing of regex u flag
+ regexUFlag: false,
+
+ // enable parsing of regex y flag
+ regexYFlag: false,
+
+ // enable parsing binary literals
+ binaryLiterals: false,
+
+ // enable parsing ES6 octal literals
+ octalLiterals: false,
+
+ // enable parsing of for-of statements
+ forOf: false,
+
+ // enable parsing computed object literal properties
+ objectLiteralComputedProperties: false,
+
+ // enable parsing of shorthand object literal methods
+ objectLiteralShorthandMethods: false,
+
+ // enable parsing of shorthand object literal properties
+ objectLiteralShorthandProperties: false,
+
+ // Allow duplicate object literal properties (except '__proto__')
+ objectLiteralDuplicateProperties: false,
+
+ // enable parsing of generators/yield
+ generators: false,
+
+ // React JSX parsing
+ jsx: false
+};
+
+},{}],17:[function(require,module,exports){
+/**
+ * @fileoverview Error messages returned by the parser.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2011-2013 Ariya Hidayat
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+// error messages should be identical to V8 where possible
+module.exports = {
+ UnexpectedToken: "Unexpected token %0",
+ UnexpectedNumber: "Unexpected number",
+ UnexpectedString: "Unexpected string",
+ UnexpectedIdentifier: "Unexpected identifier",
+ UnexpectedReserved: "Unexpected reserved word",
+ UnexpectedEOS: "Unexpected end of input",
+ NewlineAfterThrow: "Illegal newline after throw",
+ InvalidRegExp: "Invalid regular expression",
+ InvalidRegExpFlag: "Invalid regular expression flag",
+ UnterminatedRegExp: "Invalid regular expression: missing /",
+ InvalidLHSInAssignment: "Invalid left-hand side in assignment",
+ InvalidLHSInForIn: "Invalid left-hand side in for-in",
+ MultipleDefaultsInSwitch: "More than one default clause in switch statement",
+ NoCatchOrFinally: "Missing catch or finally after try",
+ UnknownLabel: "Undefined label '%0'",
+ Redeclaration: "%0 '%1' has already been declared",
+ IllegalContinue: "Illegal continue statement",
+ IllegalBreak: "Illegal break statement",
+ IllegalReturn: "Illegal return statement",
+ IllegalYield: "Illegal yield expression",
+ StrictModeWith: "Strict mode code may not include a with statement",
+ StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode",
+ StrictVarName: "Variable name may not be eval or arguments in strict mode",
+ StrictParamName: "Parameter name eval or arguments is not allowed in strict mode",
+ StrictParamDupe: "Strict mode function may not have duplicate parameter names",
+ StrictFunctionName: "Function name may not be eval or arguments in strict mode",
+ StrictOctalLiteral: "Octal literals are not allowed in strict mode.",
+ StrictDelete: "Delete of an unqualified identifier in strict mode.",
+ StrictDuplicateProperty: "Duplicate data property in object literal not allowed in strict mode",
+ DuplicatePrototypeProperty: "Duplicate '__proto__' property in object literal are not allowed",
+ AccessorDataProperty: "Object literal may not have data and accessor property with the same name",
+ AccessorGetSet: "Object literal may not have multiple get/set accessors with the same name",
+ StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode",
+ StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode",
+ StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode",
+ StrictReservedWord: "Use of future reserved word in strict mode",
+ InvalidJSXAttributeValue: "JSX value should be either an expression or a quoted JSX text",
+ ExpectedJSXClosingTag: "Expected corresponding JSX closing tag for %0",
+ AdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag"
+};
+
+},{}],18:[function(require,module,exports){
+/**
+ * @fileoverview Various syntax/pattern checks for parsing.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2011-2013 Ariya Hidayat
+ * @copyright 2012-2013 Mathias Bynens
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+
+// See also tools/generate-identifier-regex.js.
+var Regex = {
+ NonAsciiIdentifierStart: new RegExp("[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]"),
+ NonAsciiIdentifierPart: new RegExp("[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]"),
+ LeadingZeros: new RegExp("^0+(?!$)")
+};
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+
+ Regex: Regex,
+
+ isDecimalDigit: function(ch) {
+ return (ch >= 48 && ch <= 57); // 0..9
+ },
+
+ isHexDigit: function(ch) {
+ return "0123456789abcdefABCDEF".indexOf(ch) >= 0;
+ },
+
+ isOctalDigit: function(ch) {
+ return "01234567".indexOf(ch) >= 0;
+ },
+
+ // 7.2 White Space
+
+ isWhiteSpace: function(ch) {
+ return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
+ (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
+ },
+
+ // 7.3 Line Terminators
+
+ isLineTerminator: function(ch) {
+ return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
+ },
+
+ // 7.6 Identifier Names and Identifiers
+
+ isIdentifierStart: function(ch) {
+ return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
+ (ch >= 0x41 && ch <= 0x5A) || // A..Z
+ (ch >= 0x61 && ch <= 0x7A) || // a..z
+ (ch === 0x5C) || // \ (backslash)
+ ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
+ },
+
+ isIdentifierPart: function(ch) {
+ return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
+ (ch >= 0x41 && ch <= 0x5A) || // A..Z
+ (ch >= 0x61 && ch <= 0x7A) || // a..z
+ (ch >= 0x30 && ch <= 0x39) || // 0..9
+ (ch === 0x5C) || // \ (backslash)
+ ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
+ },
+
+ // 7.6.1.2 Future Reserved Words
+
+ isFutureReservedWord: function(id) {
+ switch (id) {
+ case "class":
+ case "enum":
+ case "export":
+ case "extends":
+ case "import":
+ case "super":
+ return true;
+ default:
+ return false;
+ }
+ },
+
+ isStrictModeReservedWord: function(id) {
+ switch (id) {
+ case "implements":
+ case "interface":
+ case "package":
+ case "private":
+ case "protected":
+ case "public":
+ case "static":
+ case "yield":
+ case "let":
+ return true;
+ default:
+ return false;
+ }
+ },
+
+ isRestrictedWord: function(id) {
+ return id === "eval" || id === "arguments";
+ },
+
+ // 7.6.1.1 Keywords
+
+ isKeyword: function(id, strict, ecmaFeatures) {
+
+ if (strict && this.isStrictModeReservedWord(id)) {
+ return true;
+ }
+
+ // "const" is specialized as Keyword in V8.
+ // "yield" and "let" are for compatiblity with SpiderMonkey and ES.next.
+ // Some others are from future reserved words.
+
+ switch (id.length) {
+ case 2:
+ return (id === "if") || (id === "in") || (id === "do");
+ case 3:
+ return (id === "var") || (id === "for") || (id === "new") ||
+ (id === "try") || (id === "let");
+ case 4:
+ return (id === "this") || (id === "else") || (id === "case") ||
+ (id === "void") || (id === "with") || (id === "enum");
+ case 5:
+ return (id === "while") || (id === "break") || (id === "catch") ||
+ (id === "throw") || (id === "const") || (!ecmaFeatures.generators && id === "yield") ||
+ (id === "class") || (id === "super");
+ case 6:
+ return (id === "return") || (id === "typeof") || (id === "delete") ||
+ (id === "switch") || (id === "export") || (id === "import");
+ case 7:
+ return (id === "default") || (id === "finally") || (id === "extends");
+ case 8:
+ return (id === "function") || (id === "continue") || (id === "debugger");
+ case 10:
+ return (id === "instanceof");
+ default:
+ return false;
+ }
+ },
+
+ isJSXIdentifierStart: function(ch) {
+ // exclude backslash (\)
+ return (ch !== 92) && this.isIdentifierStart(ch);
+ },
+
+ isJSXIdentifierPart: function(ch) {
+ // exclude backslash (\) and add hyphen (-)
+ return (ch !== 92) && (ch === 45 || this.isIdentifierPart(ch));
+ }
+
+
+};
+
+},{}],19:[function(require,module,exports){
+/**
+ * @fileoverview Contains token information.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2013 Thaddee Tyl
+ * @copyright 2011-2013 Ariya Hidayat
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Private
+//------------------------------------------------------------------------------
+
+var Token = {
+ BooleanLiteral: 1,
+ EOF: 2,
+ Identifier: 3,
+ Keyword: 4,
+ NullLiteral: 5,
+ NumericLiteral: 6,
+ Punctuator: 7,
+ StringLiteral: 8,
+ RegularExpression: 9,
+ JSXIdentifier: 11,
+ JSXText: 12
+};
+
+var TokenName = {};
+TokenName[Token.BooleanLiteral] = "Boolean";
+TokenName[Token.EOF] = "";
+TokenName[Token.Identifier] = "Identifier";
+TokenName[Token.Keyword] = "Keyword";
+TokenName[Token.NullLiteral] = "Null";
+TokenName[Token.NumericLiteral] = "Numeric";
+TokenName[Token.Punctuator] = "Punctuator";
+TokenName[Token.StringLiteral] = "String";
+TokenName[Token.RegularExpression] = "RegularExpression";
+TokenName[Token.JSXIdentifier] = "JSXIdentifier";
+TokenName[Token.JSXText] = "JSXText";
+
+// A function following one of those tokens is an expression.
+var FnExprTokens = ["(", "{", "[", "in", "typeof", "instanceof", "new",
+ "return", "case", "delete", "throw", "void",
+ // assignment operators
+ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
+ "&=", "|=", "^=", ",",
+ // binary/unary operators
+ "+", "-", "*", "/", "%", "++", "--", "<<", ">>", ">>>", "&",
+ "|", "^", "!", "~", "&&", "||", "?", ":", "===", "==", ">=",
+ "<=", "<", ">", "!=", "!=="];
+
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+ Token: Token,
+ TokenName: TokenName,
+ FnExprTokens: FnExprTokens
+};
+
+},{}],20:[function(require,module,exports){
+/**
+ * @fileoverview The list of XHTML entities that are valid in JSX.
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// None!
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = {
+ quot: "\u0022",
+ amp: "&",
+ apos: "\u0027",
+ lt: "<",
+ gt: ">",
+ nbsp: "\u00A0",
+ iexcl: "\u00A1",
+ cent: "\u00A2",
+ pound: "\u00A3",
+ curren: "\u00A4",
+ yen: "\u00A5",
+ brvbar: "\u00A6",
+ sect: "\u00A7",
+ uml: "\u00A8",
+ copy: "\u00A9",
+ ordf: "\u00AA",
+ laquo: "\u00AB",
+ not: "\u00AC",
+ shy: "\u00AD",
+ reg: "\u00AE",
+ macr: "\u00AF",
+ deg: "\u00B0",
+ plusmn: "\u00B1",
+ sup2: "\u00B2",
+ sup3: "\u00B3",
+ acute: "\u00B4",
+ micro: "\u00B5",
+ para: "\u00B6",
+ middot: "\u00B7",
+ cedil: "\u00B8",
+ sup1: "\u00B9",
+ ordm: "\u00BA",
+ raquo: "\u00BB",
+ frac14: "\u00BC",
+ frac12: "\u00BD",
+ frac34: "\u00BE",
+ iquest: "\u00BF",
+ Agrave: "\u00C0",
+ Aacute: "\u00C1",
+ Acirc: "\u00C2",
+ Atilde: "\u00C3",
+ Auml: "\u00C4",
+ Aring: "\u00C5",
+ AElig: "\u00C6",
+ Ccedil: "\u00C7",
+ Egrave: "\u00C8",
+ Eacute: "\u00C9",
+ Ecirc: "\u00CA",
+ Euml: "\u00CB",
+ Igrave: "\u00CC",
+ Iacute: "\u00CD",
+ Icirc: "\u00CE",
+ Iuml: "\u00CF",
+ ETH: "\u00D0",
+ Ntilde: "\u00D1",
+ Ograve: "\u00D2",
+ Oacute: "\u00D3",
+ Ocirc: "\u00D4",
+ Otilde: "\u00D5",
+ Ouml: "\u00D6",
+ times: "\u00D7",
+ Oslash: "\u00D8",
+ Ugrave: "\u00D9",
+ Uacute: "\u00DA",
+ Ucirc: "\u00DB",
+ Uuml: "\u00DC",
+ Yacute: "\u00DD",
+ THORN: "\u00DE",
+ szlig: "\u00DF",
+ agrave: "\u00E0",
+ aacute: "\u00E1",
+ acirc: "\u00E2",
+ atilde: "\u00E3",
+ auml: "\u00E4",
+ aring: "\u00E5",
+ aelig: "\u00E6",
+ ccedil: "\u00E7",
+ egrave: "\u00E8",
+ eacute: "\u00E9",
+ ecirc: "\u00EA",
+ euml: "\u00EB",
+ igrave: "\u00EC",
+ iacute: "\u00ED",
+ icirc: "\u00EE",
+ iuml: "\u00EF",
+ eth: "\u00F0",
+ ntilde: "\u00F1",
+ ograve: "\u00F2",
+ oacute: "\u00F3",
+ ocirc: "\u00F4",
+ otilde: "\u00F5",
+ ouml: "\u00F6",
+ divide: "\u00F7",
+ oslash: "\u00F8",
+ ugrave: "\u00F9",
+ uacute: "\u00FA",
+ ucirc: "\u00FB",
+ uuml: "\u00FC",
+ yacute: "\u00FD",
+ thorn: "\u00FE",
+ yuml: "\u00FF",
+ OElig: "\u0152",
+ oelig: "\u0153",
+ Scaron: "\u0160",
+ scaron: "\u0161",
+ Yuml: "\u0178",
+ fnof: "\u0192",
+ circ: "\u02C6",
+ tilde: "\u02DC",
+ Alpha: "\u0391",
+ Beta: "\u0392",
+ Gamma: "\u0393",
+ Delta: "\u0394",
+ Epsilon: "\u0395",
+ Zeta: "\u0396",
+ Eta: "\u0397",
+ Theta: "\u0398",
+ Iota: "\u0399",
+ Kappa: "\u039A",
+ Lambda: "\u039B",
+ Mu: "\u039C",
+ Nu: "\u039D",
+ Xi: "\u039E",
+ Omicron: "\u039F",
+ Pi: "\u03A0",
+ Rho: "\u03A1",
+ Sigma: "\u03A3",
+ Tau: "\u03A4",
+ Upsilon: "\u03A5",
+ Phi: "\u03A6",
+ Chi: "\u03A7",
+ Psi: "\u03A8",
+ Omega: "\u03A9",
+ alpha: "\u03B1",
+ beta: "\u03B2",
+ gamma: "\u03B3",
+ delta: "\u03B4",
+ epsilon: "\u03B5",
+ zeta: "\u03B6",
+ eta: "\u03B7",
+ theta: "\u03B8",
+ iota: "\u03B9",
+ kappa: "\u03BA",
+ lambda: "\u03BB",
+ mu: "\u03BC",
+ nu: "\u03BD",
+ xi: "\u03BE",
+ omicron: "\u03BF",
+ pi: "\u03C0",
+ rho: "\u03C1",
+ sigmaf: "\u03C2",
+ sigma: "\u03C3",
+ tau: "\u03C4",
+ upsilon: "\u03C5",
+ phi: "\u03C6",
+ chi: "\u03C7",
+ psi: "\u03C8",
+ omega: "\u03C9",
+ thetasym: "\u03D1",
+ upsih: "\u03D2",
+ piv: "\u03D6",
+ ensp: "\u2002",
+ emsp: "\u2003",
+ thinsp: "\u2009",
+ zwnj: "\u200C",
+ zwj: "\u200D",
+ lrm: "\u200E",
+ rlm: "\u200F",
+ ndash: "\u2013",
+ mdash: "\u2014",
+ lsquo: "\u2018",
+ rsquo: "\u2019",
+ sbquo: "\u201A",
+ ldquo: "\u201C",
+ rdquo: "\u201D",
+ bdquo: "\u201E",
+ dagger: "\u2020",
+ Dagger: "\u2021",
+ bull: "\u2022",
+ hellip: "\u2026",
+ permil: "\u2030",
+ prime: "\u2032",
+ Prime: "\u2033",
+ lsaquo: "\u2039",
+ rsaquo: "\u203A",
+ oline: "\u203E",
+ frasl: "\u2044",
+ euro: "\u20AC",
+ image: "\u2111",
+ weierp: "\u2118",
+ real: "\u211C",
+ trade: "\u2122",
+ alefsym: "\u2135",
+ larr: "\u2190",
+ uarr: "\u2191",
+ rarr: "\u2192",
+ darr: "\u2193",
+ harr: "\u2194",
+ crarr: "\u21B5",
+ lArr: "\u21D0",
+ uArr: "\u21D1",
+ rArr: "\u21D2",
+ dArr: "\u21D3",
+ hArr: "\u21D4",
+ forall: "\u2200",
+ part: "\u2202",
+ exist: "\u2203",
+ empty: "\u2205",
+ nabla: "\u2207",
+ isin: "\u2208",
+ notin: "\u2209",
+ ni: "\u220B",
+ prod: "\u220F",
+ sum: "\u2211",
+ minus: "\u2212",
+ lowast: "\u2217",
+ radic: "\u221A",
+ prop: "\u221D",
+ infin: "\u221E",
+ ang: "\u2220",
+ and: "\u2227",
+ or: "\u2228",
+ cap: "\u2229",
+ cup: "\u222A",
+ "int": "\u222B",
+ there4: "\u2234",
+ sim: "\u223C",
+ cong: "\u2245",
+ asymp: "\u2248",
+ ne: "\u2260",
+ equiv: "\u2261",
+ le: "\u2264",
+ ge: "\u2265",
+ sub: "\u2282",
+ sup: "\u2283",
+ nsub: "\u2284",
+ sube: "\u2286",
+ supe: "\u2287",
+ oplus: "\u2295",
+ otimes: "\u2297",
+ perp: "\u22A5",
+ sdot: "\u22C5",
+ lceil: "\u2308",
+ rceil: "\u2309",
+ lfloor: "\u230A",
+ rfloor: "\u230B",
+ lang: "\u2329",
+ rang: "\u232A",
+ loz: "\u25CA",
+ spades: "\u2660",
+ clubs: "\u2663",
+ hearts: "\u2665",
+ diams: "\u2666"
+};
+
+},{}],21:[function(require,module,exports){
+module.exports={
+ "name": "espree",
+ "description": "An actively-maintained fork of Esprima, the ECMAScript parsing infrastructure for multipurpose analysis",
+ "author": {
+ "name": "Nicholas C. Zakas",
+ "email": "nicholas+npm@nczconsulting.com"
+ },
+ "homepage": "https://github.com/eslint/espree",
+ "main": "espree.js",
+ "bin": {
+ "esparse": "./bin/esparse.js",
+ "esvalidate": "./bin/esvalidate.js"
+ },
+ "version": "1.6.0",
+ "files": [
+ "bin",
+ "lib",
+ "test/run.js",
+ "test/runner.js",
+ "test/test.js",
+ "test/compat.js",
+ "test/reflect.js",
+ "espree.js"
+ ],
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/eslint/espree.git"
+ },
+ "bugs": {
+ "url": "http://github.com/eslint/espree.git"
+ },
+ "licenses": [
+ {
+ "type": "BSD",
+ "url": "http://github.com/nzakas/espree/raw/master/LICENSE"
+ }
+ ],
+ "devDependencies": {
+ "browserify": "^7.0.0",
+ "chai": "^1.10.0",
+ "complexity-report": "~0.6.1",
+ "dateformat": "^1.0.11",
+ "eslint": "^0.9.2",
+ "esprima": "git://github.com/ariya/esprima#harmony",
+ "esprima-fb": "^8001.2001.0-dev-harmony-fb",
+ "istanbul": "~0.2.6",
+ "json-diff": "~0.3.1",
+ "leche": "^1.0.1",
+ "mocha": "^2.0.1",
+ "npm-license": "^0.2.3",
+ "optimist": "~0.6.0",
+ "regenerate": "~0.5.4",
+ "semver": "^4.1.1",
+ "shelljs": "^0.3.0",
+ "shelljs-nodecli": "^0.1.1",
+ "unicode-6.3.0": "~0.1.0"
+ },
+ "keywords": [
+ "ast",
+ "ecmascript",
+ "javascript",
+ "parser",
+ "syntax"
+ ],
+ "scripts": {
+ "generate-regex": "node tools/generate-identifier-regex.js",
+ "test": "npm run-script lint && node Makefile.js test && node test/run.js",
+ "lint": "node Makefile.js lint",
+ "patch": "node Makefile.js patch",
+ "minor": "node Makefile.js minor",
+ "major": "node Makefile.js major",
+ "browserify": "node Makefile.js browserify",
+ "coverage": "npm run-script analyze-coverage && npm run-script check-coverage",
+ "analyze-coverage": "node node_modules/istanbul/lib/cli.js cover test/runner.js",
+ "check-coverage": "node node_modules/istanbul/lib/cli.js check-coverage --statement 99 --branch 99 --function 99",
+ "complexity": "npm run-script analyze-complexity && npm run-script check-complexity",
+ "analyze-complexity": "node tools/list-complexity.js",
+ "check-complexity": "node node_modules/complexity-report/src/cli.js --maxcc 14 --silent -l -w espree.js",
+ "benchmark": "node test/benchmarks.js",
+ "benchmark-quick": "node test/benchmarks.js quick"
+ },
+ "dependencies": {},
+ "readme": "# Espree\n\nEspree is an actively-maintained fork Esprima, a high performance,\nstandard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)\nparser written in ECMAScript (also popularly known as\n[JavaScript](http://en.wikipedia.org/wiki/JavaScript)).\n\n## Features\n\n- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm))\n- Sensible syntax tree format compatible with Mozilla\n[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API)\n- Optional tracking of syntax node location (index-based and line-column)\n- Heavily tested (> 650 unit tests) with full code coverage\n\n## Usage\n\nInstall:\n\n```\nnpm i espree --save\n```\n\nAnd in your Node.js code:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code);\n```\n\nThere is a second argument to `parse()` that allows you to specify various options:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code, {\n\n // attach range information to each node\n range: true,\n\n // attach line/column location information to each node\n loc: true,\n\n // create a top-level comments array containing all comments\n comments: true,\n\n // attach comments to the closest relevant node as leadingComments and\n // trailingComments\n attachComment: true,\n\n // create a top-level tokens array containing all tokens\n tokens: true,\n\n // try to continue parsing if an error is encountered, store errors in a\n // top-level errors array\n tolerant: true,\n\n // specify parsing features (default only has blockBindings: true)\n ecmaFeatures: {\n\n // enable parsing of let/const\n blockBindings: true,\n\n // enable parsing of regular expression y flag\n regexYFlag: true,\n\n // enable parsing of regular expression u flag\n regexUFlag: true,\n\n // enable parsing of binary literals\n binaryLiterals: true,\n\n // enable parsing of ES6 octal literals\n octalLiterals: true,\n\n // enable parsing of for-of statement\n forOf: true,\n\n // enable parsing computed object literal properties\n objectLiteralComputedProperties: true,\n\n // enable parsing of shorthand object literal methods\n objectLiteralShorthandMethods: true,\n\n // enable parsing of shorthand object literal properties\n objectLiteralShorthandProperties: true,\n\n // Allow duplicate object literal properties (except '__proto__')\n objectLiteralDuplicateProperties: true,\n\n // enable parsing of generators/yield\n generators: true,\n\n // React JSX parsing\n jsx: true\n }\n});\n```\n\n## Plans\n\nEspree starts as a fork of Esprima v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree's first version is therefore v1.2.2 and is 100% compatible with Esprima v1.2.2 as a drop-in replacement. The version number will be incremented based on [semantic versioning](http://semver.org/) as features and bug fixes are added.\n\nThe immediate plans are:\n\n1. Move away from giant files and move towards small, modular files that are easier to manage.\n1. Move towards CommonJS for all files and use browserify to create browser bundles.\n1. Support ECMAScript version filtering, allowing users to specify which version the parser should work in (similar to Acorn's `ecmaVersion` property).\n1. Add tests to track comment attachment.\n1. Add well-thought-out features that are useful for tools developers.\n1. Add full support for ECMAScript 6.\n1. Add optional parsing of JSX.\n\n## Esprima Compatibility Going Forward\n\nThe primary goal is to produce the exact same AST structure as Esprima and Acorn, and that takes precedence over anything else. (The AST structure being the SpiderMonkey Parser API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.\n\nEspree may also deviate from Esprima in the interface it exposes.\n\n## Frequent and Incremental Releases\n\nEspree will not do giant releases. Releases will happen periodically as changes are made and incremental releases will be made towards larger goals. For instance, we will not have one big release for ECMAScript 6 support. Instead, we will implement ECMAScript 6, piece-by-piece, hiding those pieces behind an `ecmaFeatures` property that allows you to opt-in to use those features.\n\n## Contributing\n\nIssues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing.html), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues).\n\nEspree is licensed under a permissive BSD 3-clause license.\n\n## Build Commands\n\n* `npm test` - run all linting and tests\n* `npm run lint` - run all linting\n* `npm run browserify` - creates a version of Espree that is usable in a browser\n\n## Known Incompatibilities\n\nIn an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.\n\n### Esprima 1.2.2\n\n* None.\n\n### Esprima/Harmony Branch\n\n* Esprima/Harmony uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.\n\n### Esprima-FB\n\n* All Esprima/Harmony incompatibilities.\n* Esprima-FB uses the term \"XJS\" to refer to its JSX support. This is seen primarily in the AST node types, such as `\"XJSElement\"`. Espree uses \"JSX\" to refer to JSX functionality, including AST node types. So, `\"XJSElement\"` in Esprima-FB is `\"JSXElement\"` in Espree (and the same is true for all JSX-related node types).\n\n## Frequently Asked Questions\n\n### Why are you forking Esprima?\n\n[ESLint](http://eslint.org) has been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development has increased dramatically and Esprima has fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that has caused our users frustration.\n\nWe decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.\n\n### Have you tried working with Esprima?\n\nYes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima. Unfortunately, we've been unable to make much progress towards getting our needs addressed.\n\n### Why don't you just use Facebook's Esprima fork?\n\n`esprima-fb` is Facebook's Esprima fork that features JSX and Flow type annotations. We tried working with `esprima-fb` in our evaluation of how to support ECMAScript 6 and JSX in ESLint. Unfortunately, we were hampered by bugs that were part of Esprima (not necessarily Facebook's code). Since `esprima-fb` tracks the Esprima Harmony branch, that means we still were unable to get fixes or features we needed in a timely manner.\n\n### Why don't you just use Acorn?\n\nAcorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.\n\nWe expect there are other tools like ESLint that rely on more than just the AST produced by Esprima, and so a drop-in replacement will help those projects as well as ESLint.\n\n### What ECMAScript 6 features do you support?\n\nPlease see the [tracking issue](https://github.com/eslint/espree/issues/10) for the most up-to-date information.\n\n### Why use Espree instead of Esprima?\n\n* Faster turnaround time on bug fixes\n* More frequent releases\n* Better communication and responsiveness to issues\n* Ongoing development\n\n### Why use Espree instead of Esprima-FB?\n\n* Opt-in to just the ECMAScript 6 features you want\n* JSX support is off by default, so you're not forced to use it to use ECMAScript 6\n* Stricter ECMAScript 6 support\n",
+ "readmeFilename": "README.md",
+ "_id": "espree@1.6.0",
+ "_shasum": "0ee9d27cb3a835dffc2c890669c2b8617fa6f9ae",
+ "_from": "espree@^1.6.0",
+ "_resolved": "https://registry.npmjs.org/espree/-/espree-1.6.0.tgz"
+}
+
+},{}],22:[function(require,module,exports){
+/*
+ Copyright (C) 2012-2013 Yusuke Suzuki
+ Copyright (C) 2012 Ariya Hidayat
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/*jslint vars:false, bitwise:true*/
+/*jshint indent:4*/
+/*global exports:true, define:true*/
+(function (root, factory) {
+ 'use strict';
+
+ // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
+ // and plain browser loading,
+ if (typeof define === 'function' && define.amd) {
+ define(['exports'], factory);
+ } else if (typeof exports !== 'undefined') {
+ factory(exports);
+ } else {
+ factory((root.estraverse = {}));
+ }
+}(this, function clone(exports) {
+ 'use strict';
+
+ var Syntax,
+ isArray,
+ VisitorOption,
+ VisitorKeys,
+ objectCreate,
+ objectKeys,
+ BREAK,
+ SKIP,
+ REMOVE;
+
+ function ignoreJSHintError() { }
+
+ isArray = Array.isArray;
+ if (!isArray) {
+ isArray = function isArray(array) {
+ return Object.prototype.toString.call(array) === '[object Array]';
+ };
+ }
+
+ function deepCopy(obj) {
+ var ret = {}, key, val;
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ val = obj[key];
+ if (typeof val === 'object' && val !== null) {
+ ret[key] = deepCopy(val);
+ } else {
+ ret[key] = val;
+ }
+ }
+ }
+ return ret;
+ }
+
+ function shallowCopy(obj) {
+ var ret = {}, key;
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
+ }
+ ignoreJSHintError(shallowCopy);
+
+ // based on LLVM libc++ upper_bound / lower_bound
+ // MIT License
+
+ function upperBound(array, func) {
+ var diff, len, i, current;
+
+ len = array.length;
+ i = 0;
+
+ while (len) {
+ diff = len >>> 1;
+ current = i + diff;
+ if (func(array[current])) {
+ len = diff;
+ } else {
+ i = current + 1;
+ len -= diff + 1;
+ }
+ }
+ return i;
+ }
+
+ function lowerBound(array, func) {
+ var diff, len, i, current;
+
+ len = array.length;
+ i = 0;
+
+ while (len) {
+ diff = len >>> 1;
+ current = i + diff;
+ if (func(array[current])) {
+ i = current + 1;
+ len -= diff + 1;
+ } else {
+ len = diff;
+ }
+ }
+ return i;
+ }
+ ignoreJSHintError(lowerBound);
+
+ objectCreate = Object.create || (function () {
+ function F() { }
+
+ return function (o) {
+ F.prototype = o;
+ return new F();
+ };
+ })();
+
+ objectKeys = Object.keys || function (o) {
+ var keys = [], key;
+ for (key in o) {
+ keys.push(key);
+ }
+ return keys;
+ };
+
+ function extend(to, from) {
+ objectKeys(from).forEach(function (key) {
+ to[key] = from[key];
+ });
+ return to;
+ }
+
+ Syntax = {
+ AssignmentExpression: 'AssignmentExpression',
+ ArrayExpression: 'ArrayExpression',
+ ArrayPattern: 'ArrayPattern',
+ ArrowFunctionExpression: 'ArrowFunctionExpression',
+ AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
+ BlockStatement: 'BlockStatement',
+ BinaryExpression: 'BinaryExpression',
+ BreakStatement: 'BreakStatement',
+ CallExpression: 'CallExpression',
+ CatchClause: 'CatchClause',
+ ClassBody: 'ClassBody',
+ ClassDeclaration: 'ClassDeclaration',
+ ClassExpression: 'ClassExpression',
+ ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
+ ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
+ ConditionalExpression: 'ConditionalExpression',
+ ContinueStatement: 'ContinueStatement',
+ DebuggerStatement: 'DebuggerStatement',
+ DirectiveStatement: 'DirectiveStatement',
+ DoWhileStatement: 'DoWhileStatement',
+ EmptyStatement: 'EmptyStatement',
+ ExportBatchSpecifier: 'ExportBatchSpecifier',
+ ExportDeclaration: 'ExportDeclaration',
+ ExportSpecifier: 'ExportSpecifier',
+ ExpressionStatement: 'ExpressionStatement',
+ ForStatement: 'ForStatement',
+ ForInStatement: 'ForInStatement',
+ ForOfStatement: 'ForOfStatement',
+ FunctionDeclaration: 'FunctionDeclaration',
+ FunctionExpression: 'FunctionExpression',
+ GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
+ Identifier: 'Identifier',
+ IfStatement: 'IfStatement',
+ ImportDeclaration: 'ImportDeclaration',
+ ImportDefaultSpecifier: 'ImportDefaultSpecifier',
+ ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
+ ImportSpecifier: 'ImportSpecifier',
+ Literal: 'Literal',
+ LabeledStatement: 'LabeledStatement',
+ LogicalExpression: 'LogicalExpression',
+ MemberExpression: 'MemberExpression',
+ MethodDefinition: 'MethodDefinition',
+ ModuleSpecifier: 'ModuleSpecifier',
+ NewExpression: 'NewExpression',
+ ObjectExpression: 'ObjectExpression',
+ ObjectPattern: 'ObjectPattern',
+ Program: 'Program',
+ Property: 'Property',
+ ReturnStatement: 'ReturnStatement',
+ SequenceExpression: 'SequenceExpression',
+ SpreadElement: 'SpreadElement',
+ SwitchStatement: 'SwitchStatement',
+ SwitchCase: 'SwitchCase',
+ TaggedTemplateExpression: 'TaggedTemplateExpression',
+ TemplateElement: 'TemplateElement',
+ TemplateLiteral: 'TemplateLiteral',
+ ThisExpression: 'ThisExpression',
+ ThrowStatement: 'ThrowStatement',
+ TryStatement: 'TryStatement',
+ UnaryExpression: 'UnaryExpression',
+ UpdateExpression: 'UpdateExpression',
+ VariableDeclaration: 'VariableDeclaration',
+ VariableDeclarator: 'VariableDeclarator',
+ WhileStatement: 'WhileStatement',
+ WithStatement: 'WithStatement',
+ YieldExpression: 'YieldExpression'
+ };
+
+ VisitorKeys = {
+ AssignmentExpression: ['left', 'right'],
+ ArrayExpression: ['elements'],
+ ArrayPattern: ['elements'],
+ ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'],
+ AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
+ BlockStatement: ['body'],
+ BinaryExpression: ['left', 'right'],
+ BreakStatement: ['label'],
+ CallExpression: ['callee', 'arguments'],
+ CatchClause: ['param', 'body'],
+ ClassBody: ['body'],
+ ClassDeclaration: ['id', 'body', 'superClass'],
+ ClassExpression: ['id', 'body', 'superClass'],
+ ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
+ ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
+ ConditionalExpression: ['test', 'consequent', 'alternate'],
+ ContinueStatement: ['label'],
+ DebuggerStatement: [],
+ DirectiveStatement: [],
+ DoWhileStatement: ['body', 'test'],
+ EmptyStatement: [],
+ ExportBatchSpecifier: [],
+ ExportDeclaration: ['declaration', 'specifiers', 'source'],
+ ExportSpecifier: ['id', 'name'],
+ ExpressionStatement: ['expression'],
+ ForStatement: ['init', 'test', 'update', 'body'],
+ ForInStatement: ['left', 'right', 'body'],
+ ForOfStatement: ['left', 'right', 'body'],
+ FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'],
+ FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'],
+ GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
+ Identifier: [],
+ IfStatement: ['test', 'consequent', 'alternate'],
+ ImportDeclaration: ['specifiers', 'source'],
+ ImportDefaultSpecifier: ['id'],
+ ImportNamespaceSpecifier: ['id'],
+ ImportSpecifier: ['id', 'name'],
+ Literal: [],
+ LabeledStatement: ['label', 'body'],
+ LogicalExpression: ['left', 'right'],
+ MemberExpression: ['object', 'property'],
+ MethodDefinition: ['key', 'value'],
+ ModuleSpecifier: [],
+ NewExpression: ['callee', 'arguments'],
+ ObjectExpression: ['properties'],
+ ObjectPattern: ['properties'],
+ Program: ['body'],
+ Property: ['key', 'value'],
+ ReturnStatement: ['argument'],
+ SequenceExpression: ['expressions'],
+ SpreadElement: ['argument'],
+ SwitchStatement: ['discriminant', 'cases'],
+ SwitchCase: ['test', 'consequent'],
+ TaggedTemplateExpression: ['tag', 'quasi'],
+ TemplateElement: [],
+ TemplateLiteral: ['quasis', 'expressions'],
+ ThisExpression: [],
+ ThrowStatement: ['argument'],
+ TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'],
+ UnaryExpression: ['argument'],
+ UpdateExpression: ['argument'],
+ VariableDeclaration: ['declarations'],
+ VariableDeclarator: ['id', 'init'],
+ WhileStatement: ['test', 'body'],
+ WithStatement: ['object', 'body'],
+ YieldExpression: ['argument']
+ };
+
+ // unique id
+ BREAK = {};
+ SKIP = {};
+ REMOVE = {};
+
+ VisitorOption = {
+ Break: BREAK,
+ Skip: SKIP,
+ Remove: REMOVE
+ };
+
+ function Reference(parent, key) {
+ this.parent = parent;
+ this.key = key;
+ }
+
+ Reference.prototype.replace = function replace(node) {
+ this.parent[this.key] = node;
+ };
+
+ Reference.prototype.remove = function remove() {
+ if (isArray(this.parent)) {
+ this.parent.splice(this.key, 1);
+ return true;
+ } else {
+ this.replace(null);
+ return false;
+ }
+ };
+
+ function Element(node, path, wrap, ref) {
+ this.node = node;
+ this.path = path;
+ this.wrap = wrap;
+ this.ref = ref;
+ }
+
+ function Controller() { }
+
+ // API:
+ // return property path array from root to current node
+ Controller.prototype.path = function path() {
+ var i, iz, j, jz, result, element;
+
+ function addToPath(result, path) {
+ if (isArray(path)) {
+ for (j = 0, jz = path.length; j < jz; ++j) {
+ result.push(path[j]);
+ }
+ } else {
+ result.push(path);
+ }
+ }
+
+ // root node
+ if (!this.__current.path) {
+ return null;
+ }
+
+ // first node is sentinel, second node is root element
+ result = [];
+ for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
+ element = this.__leavelist[i];
+ addToPath(result, element.path);
+ }
+ addToPath(result, this.__current.path);
+ return result;
+ };
+
+ // API:
+ // return type of current node
+ Controller.prototype.type = function () {
+ var node = this.current();
+ return node.type || this.__current.wrap;
+ };
+
+ // API:
+ // return array of parent elements
+ Controller.prototype.parents = function parents() {
+ var i, iz, result;
+
+ // first node is sentinel
+ result = [];
+ for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
+ result.push(this.__leavelist[i].node);
+ }
+
+ return result;
+ };
+
+ // API:
+ // return current node
+ Controller.prototype.current = function current() {
+ return this.__current.node;
+ };
+
+ Controller.prototype.__execute = function __execute(callback, element) {
+ var previous, result;
+
+ result = undefined;
+
+ previous = this.__current;
+ this.__current = element;
+ this.__state = null;
+ if (callback) {
+ result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
+ }
+ this.__current = previous;
+
+ return result;
+ };
+
+ // API:
+ // notify control skip / break
+ Controller.prototype.notify = function notify(flag) {
+ this.__state = flag;
+ };
+
+ // API:
+ // skip child nodes of current node
+ Controller.prototype.skip = function () {
+ this.notify(SKIP);
+ };
+
+ // API:
+ // break traversals
+ Controller.prototype['break'] = function () {
+ this.notify(BREAK);
+ };
+
+ // API:
+ // remove node
+ Controller.prototype.remove = function () {
+ this.notify(REMOVE);
+ };
+
+ Controller.prototype.__initialize = function(root, visitor) {
+ this.visitor = visitor;
+ this.root = root;
+ this.__worklist = [];
+ this.__leavelist = [];
+ this.__current = null;
+ this.__state = null;
+ this.__fallback = visitor.fallback === 'iteration';
+ this.__keys = VisitorKeys;
+ if (visitor.keys) {
+ this.__keys = extend(objectCreate(this.__keys), visitor.keys);
+ }
+ };
+
+ function isNode(node) {
+ if (node == null) {
+ return false;
+ }
+ return typeof node === 'object' && typeof node.type === 'string';
+ }
+
+ function isProperty(nodeType, key) {
+ return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
+ }
+
+ Controller.prototype.traverse = function traverse(root, visitor) {
+ var worklist,
+ leavelist,
+ element,
+ node,
+ nodeType,
+ ret,
+ key,
+ current,
+ current2,
+ candidates,
+ candidate,
+ sentinel;
+
+ this.__initialize(root, visitor);
+
+ sentinel = {};
+
+ // reference
+ worklist = this.__worklist;
+ leavelist = this.__leavelist;
+
+ // initialize
+ worklist.push(new Element(root, null, null, null));
+ leavelist.push(new Element(null, null, null, null));
+
+ while (worklist.length) {
+ element = worklist.pop();
+
+ if (element === sentinel) {
+ element = leavelist.pop();
+
+ ret = this.__execute(visitor.leave, element);
+
+ if (this.__state === BREAK || ret === BREAK) {
+ return;
+ }
+ continue;
+ }
+
+ if (element.node) {
+
+ ret = this.__execute(visitor.enter, element);
+
+ if (this.__state === BREAK || ret === BREAK) {
+ return;
+ }
+
+ worklist.push(sentinel);
+ leavelist.push(element);
+
+ if (this.__state === SKIP || ret === SKIP) {
+ continue;
+ }
+
+ node = element.node;
+ nodeType = element.wrap || node.type;
+ candidates = this.__keys[nodeType];
+ if (!candidates) {
+ if (this.__fallback) {
+ candidates = objectKeys(node);
+ } else {
+ throw new Error('Unknown node type ' + nodeType + '.');
+ }
+ }
+
+ current = candidates.length;
+ while ((current -= 1) >= 0) {
+ key = candidates[current];
+ candidate = node[key];
+ if (!candidate) {
+ continue;
+ }
+
+ if (isArray(candidate)) {
+ current2 = candidate.length;
+ while ((current2 -= 1) >= 0) {
+ if (!candidate[current2]) {
+ continue;
+ }
+ if (isProperty(nodeType, candidates[current])) {
+ element = new Element(candidate[current2], [key, current2], 'Property', null);
+ } else if (isNode(candidate[current2])) {
+ element = new Element(candidate[current2], [key, current2], null, null);
+ } else {
+ continue;
+ }
+ worklist.push(element);
+ }
+ } else if (isNode(candidate)) {
+ worklist.push(new Element(candidate, key, null, null));
+ }
+ }
+ }
+ }
+ };
+
+ Controller.prototype.replace = function replace(root, visitor) {
+ function removeElem(element) {
+ var i,
+ key,
+ nextElem,
+ parent;
+
+ if (element.ref.remove()) {
+ // When the reference is an element of an array.
+ key = element.ref.key;
+ parent = element.ref.parent;
+
+ // If removed from array, then decrease following items' keys.
+ i = worklist.length;
+ while (i--) {
+ nextElem = worklist[i];
+ if (nextElem.ref && nextElem.ref.parent === parent) {
+ if (nextElem.ref.key < key) {
+ break;
+ }
+ --nextElem.ref.key;
+ }
+ }
+ }
+ }
+
+ var worklist,
+ leavelist,
+ node,
+ nodeType,
+ target,
+ element,
+ current,
+ current2,
+ candidates,
+ candidate,
+ sentinel,
+ outer,
+ key;
+
+ this.__initialize(root, visitor);
+
+ sentinel = {};
+
+ // reference
+ worklist = this.__worklist;
+ leavelist = this.__leavelist;
+
+ // initialize
+ outer = {
+ root: root
+ };
+ element = new Element(root, null, null, new Reference(outer, 'root'));
+ worklist.push(element);
+ leavelist.push(element);
+
+ while (worklist.length) {
+ element = worklist.pop();
+
+ if (element === sentinel) {
+ element = leavelist.pop();
+
+ target = this.__execute(visitor.leave, element);
+
+ // node may be replaced with null,
+ // so distinguish between undefined and null in this place
+ if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
+ // replace
+ element.ref.replace(target);
+ }
+
+ if (this.__state === REMOVE || target === REMOVE) {
+ removeElem(element);
+ }
+
+ if (this.__state === BREAK || target === BREAK) {
+ return outer.root;
+ }
+ continue;
+ }
+
+ target = this.__execute(visitor.enter, element);
+
+ // node may be replaced with null,
+ // so distinguish between undefined and null in this place
+ if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
+ // replace
+ element.ref.replace(target);
+ element.node = target;
+ }
+
+ if (this.__state === REMOVE || target === REMOVE) {
+ removeElem(element);
+ element.node = null;
+ }
+
+ if (this.__state === BREAK || target === BREAK) {
+ return outer.root;
+ }
+
+ // node may be null
+ node = element.node;
+ if (!node) {
+ continue;
+ }
+
+ worklist.push(sentinel);
+ leavelist.push(element);
+
+ if (this.__state === SKIP || target === SKIP) {
+ continue;
+ }
+
+ nodeType = element.wrap || node.type;
+ candidates = this.__keys[nodeType];
+ if (!candidates) {
+ if (this.__fallback) {
+ candidates = objectKeys(node);
+ } else {
+ throw new Error('Unknown node type ' + nodeType + '.');
+ }
+ }
+
+ current = candidates.length;
+ while ((current -= 1) >= 0) {
+ key = candidates[current];
+ candidate = node[key];
+ if (!candidate) {
+ continue;
+ }
+
+ if (isArray(candidate)) {
+ current2 = candidate.length;
+ while ((current2 -= 1) >= 0) {
+ if (!candidate[current2]) {
+ continue;
+ }
+ if (isProperty(nodeType, candidates[current])) {
+ element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
+ } else if (isNode(candidate[current2])) {
+ element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
+ } else {
+ continue;
+ }
+ worklist.push(element);
+ }
+ } else if (isNode(candidate)) {
+ worklist.push(new Element(candidate, key, null, new Reference(node, key)));
+ }
+ }
+ }
+
+ return outer.root;
+ };
+
+ function traverse(root, visitor) {
+ var controller = new Controller();
+ return controller.traverse(root, visitor);
+ }
+
+ function replace(root, visitor) {
+ var controller = new Controller();
+ return controller.replace(root, visitor);
+ }
+
+ function extendCommentRange(comment, tokens) {
+ var target;
+
+ target = upperBound(tokens, function search(token) {
+ return token.range[0] > comment.range[0];
+ });
+
+ comment.extendedRange = [comment.range[0], comment.range[1]];
+
+ if (target !== tokens.length) {
+ comment.extendedRange[1] = tokens[target].range[0];
+ }
+
+ target -= 1;
+ if (target >= 0) {
+ comment.extendedRange[0] = tokens[target].range[1];
+ }
+
+ return comment;
+ }
+
+ function attachComments(tree, providedComments, tokens) {
+ // At first, we should calculate extended comment ranges.
+ var comments = [], comment, len, i, cursor;
+
+ if (!tree.range) {
+ throw new Error('attachComments needs range information');
+ }
+
+ // tokens array is empty, we attach comments to tree as 'leadingComments'
+ if (!tokens.length) {
+ if (providedComments.length) {
+ for (i = 0, len = providedComments.length; i < len; i += 1) {
+ comment = deepCopy(providedComments[i]);
+ comment.extendedRange = [0, tree.range[0]];
+ comments.push(comment);
+ }
+ tree.leadingComments = comments;
+ }
+ return tree;
+ }
+
+ for (i = 0, len = providedComments.length; i < len; i += 1) {
+ comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
+ }
+
+ // This is based on John Freeman's implementation.
+ cursor = 0;
+ traverse(tree, {
+ enter: function (node) {
+ var comment;
+
+ while (cursor < comments.length) {
+ comment = comments[cursor];
+ if (comment.extendedRange[1] > node.range[0]) {
+ break;
+ }
+
+ if (comment.extendedRange[1] === node.range[0]) {
+ if (!node.leadingComments) {
+ node.leadingComments = [];
+ }
+ node.leadingComments.push(comment);
+ comments.splice(cursor, 1);
+ } else {
+ cursor += 1;
+ }
+ }
+
+ // already out of owned node
+ if (cursor === comments.length) {
+ return VisitorOption.Break;
+ }
+
+ if (comments[cursor].extendedRange[0] > node.range[1]) {
+ return VisitorOption.Skip;
+ }
+ }
+ });
+
+ cursor = 0;
+ traverse(tree, {
+ leave: function (node) {
+ var comment;
+
+ while (cursor < comments.length) {
+ comment = comments[cursor];
+ if (node.range[1] < comment.extendedRange[0]) {
+ break;
+ }
+
+ if (node.range[1] === comment.extendedRange[0]) {
+ if (!node.trailingComments) {
+ node.trailingComments = [];
+ }
+ node.trailingComments.push(comment);
+ comments.splice(cursor, 1);
+ } else {
+ cursor += 1;
+ }
+ }
+
+ // already out of owned node
+ if (cursor === comments.length) {
+ return VisitorOption.Break;
+ }
+
+ if (comments[cursor].extendedRange[0] > node.range[1]) {
+ return VisitorOption.Skip;
+ }
+ }
+ });
+
+ return tree;
+ }
+
+ exports.version = '1.8.1-dev';
+ exports.Syntax = Syntax;
+ exports.traverse = traverse;
+ exports.replace = replace;
+ exports.attachComments = attachComments;
+ exports.VisitorKeys = VisitorKeys;
+ exports.VisitorOption = VisitorOption;
+ exports.Controller = Controller;
+ exports.cloneEnvironment = function () { return clone({}); };
+
+ return exports;
+}));
+/* vim: set sw=4 ts=4 et tw=80 : */
+
+},{}],23:[function(require,module,exports){
+module.exports={
+ "builtin": {
+ "Array": false,
+ "ArrayBuffer": false,
+ "Boolean": false,
+ "constructor": false,
+ "Date": false,
+ "decodeURI": false,
+ "decodeURIComponent": false,
+ "encodeURI": false,
+ "encodeURIComponent": false,
+ "Error": false,
+ "eval": false,
+ "EvalError": false,
+ "Float32Array": false,
+ "Float64Array": false,
+ "Function": false,
+ "hasOwnProperty": false,
+ "Infinity": false,
+ "Int16Array": false,
+ "Int32Array": false,
+ "Int8Array": false,
+ "isFinite": false,
+ "isNaN": false,
+ "isPrototypeOf": false,
+ "JSON": false,
+ "Map": false,
+ "Math": false,
+ "NaN": false,
+ "Number": false,
+ "Object": false,
+ "parseFloat": false,
+ "parseInt": false,
+ "Promise": false,
+ "propertyIsEnumerable": false,
+ "Proxy": false,
+ "RangeError": false,
+ "ReferenceError": false,
+ "Reflect": false,
+ "RegExp": false,
+ "Set": false,
+ "String": false,
+ "Symbol": false,
+ "SyntaxError": false,
+ "System": false,
+ "toLocaleString": false,
+ "toString": false,
+ "TypeError": false,
+ "Uint16Array": false,
+ "Uint32Array": false,
+ "Uint8Array": false,
+ "Uint8ClampedArray": false,
+ "undefined": false,
+ "URIError": false,
+ "valueOf": false,
+ "WeakMap": false,
+ "WeakSet": false
+ },
+ "nonstandard": {
+ "escape": false,
+ "unescape": false
+ },
+ "browser": {
+ "addEventListener": false,
+ "applicationCache": false,
+ "atob": false,
+ "Audio": false,
+ "Blob": false,
+ "blur": false,
+ "btoa": false,
+ "cancelAnimationFrame": false,
+ "CanvasGradient": false,
+ "CanvasPattern": false,
+ "CanvasRenderingContext2D": false,
+ "clearInterval": false,
+ "clearTimeout": false,
+ "close": false,
+ "closed": false,
+ "crypto": false,
+ "CSS": false,
+ "CustomEvent": false,
+ "DataView": false,
+ "defaultStatus": false,
+ "devicePixelRatio": false,
+ "dispatchEvent": false,
+ "document": false,
+ "DOMParser": false,
+ "Element": false,
+ "ElementTimeControl": false,
+ "Event": false,
+ "event": false,
+ "FileReader": false,
+ "find": false,
+ "focus": false,
+ "FormData": false,
+ "frameElement": false,
+ "frames": false,
+ "getComputedStyle": false,
+ "getSelection": false,
+ "history": false,
+ "HTMLAnchorElement": false,
+ "HTMLBaseElement": false,
+ "HTMLBlockquoteElement": false,
+ "HTMLBodyElement": false,
+ "HTMLBRElement": false,
+ "HTMLButtonElement": false,
+ "HTMLCanvasElement": false,
+ "HTMLDirectoryElement": false,
+ "HTMLDivElement": false,
+ "HTMLDListElement": false,
+ "HTMLElement": false,
+ "HTMLFieldSetElement": false,
+ "HTMLFontElement": false,
+ "HTMLFormElement": false,
+ "HTMLFrameElement": false,
+ "HTMLFrameSetElement": false,
+ "HTMLHeadElement": false,
+ "HTMLHeadingElement": false,
+ "HTMLHRElement": false,
+ "HTMLHtmlElement": false,
+ "HTMLIFrameElement": false,
+ "HTMLImageElement": false,
+ "HTMLInputElement": false,
+ "HTMLIsIndexElement": false,
+ "HTMLLabelElement": false,
+ "HTMLLayerElement": false,
+ "HTMLLegendElement": false,
+ "HTMLLIElement": false,
+ "HTMLLinkElement": false,
+ "HTMLMapElement": false,
+ "HTMLMenuElement": false,
+ "HTMLMetaElement": false,
+ "HTMLModElement": false,
+ "HTMLObjectElement": false,
+ "HTMLOListElement": false,
+ "HTMLOptGroupElement": false,
+ "HTMLOptionElement": false,
+ "HTMLParagraphElement": false,
+ "HTMLParamElement": false,
+ "HTMLPreElement": false,
+ "HTMLQuoteElement": false,
+ "HTMLScriptElement": false,
+ "HTMLSelectElement": false,
+ "HTMLStyleElement": false,
+ "HTMLTableCaptionElement": false,
+ "HTMLTableCellElement": false,
+ "HTMLTableColElement": false,
+ "HTMLTableElement": false,
+ "HTMLTableRowElement": false,
+ "HTMLTableSectionElement": false,
+ "HTMLTextAreaElement": false,
+ "HTMLTitleElement": false,
+ "HTMLUListElement": false,
+ "HTMLVideoElement": false,
+ "Image": false,
+ "indexedDB": false,
+ "innerHeight": false,
+ "innerWidth": false,
+ "Intl": false,
+ "length": false,
+ "localStorage": false,
+ "location": false,
+ "matchMedia": false,
+ "MessageChannel": false,
+ "MessageEvent": false,
+ "MessagePort": false,
+ "MouseEvent": false,
+ "moveBy": false,
+ "moveTo": false,
+ "MutationObserver": false,
+ "name": false,
+ "navigator": false,
+ "Node": false,
+ "NodeFilter": false,
+ "NodeList": false,
+ "onbeforeunload": true,
+ "onblur": true,
+ "onerror": true,
+ "onfocus": true,
+ "onload": true,
+ "onresize": true,
+ "onunload": true,
+ "open": false,
+ "openDatabase": false,
+ "opener": false,
+ "Option": false,
+ "outerHeight": false,
+ "outerWidth": false,
+ "pageXOffset": false,
+ "pageYOffset": false,
+ "parent": false,
+ "postMessage": false,
+ "print": false,
+ "removeEventListener": false,
+ "requestAnimationFrame": false,
+ "resizeBy": false,
+ "resizeTo": false,
+ "screen": false,
+ "screenX": false,
+ "screenY": false,
+ "scroll": false,
+ "scrollbars": false,
+ "scrollBy": false,
+ "scrollTo": false,
+ "scrollX": false,
+ "scrollY": false,
+ "self": false,
+ "sessionStorage": false,
+ "setInterval": false,
+ "setTimeout": false,
+ "SharedWorker": false,
+ "showModalDialog": false,
+ "status": false,
+ "stop": false,
+ "SVGAElement": false,
+ "SVGAltGlyphDefElement": false,
+ "SVGAltGlyphElement": false,
+ "SVGAltGlyphItemElement": false,
+ "SVGAngle": false,
+ "SVGAnimateColorElement": false,
+ "SVGAnimatedAngle": false,
+ "SVGAnimatedBoolean": false,
+ "SVGAnimatedEnumeration": false,
+ "SVGAnimatedInteger": false,
+ "SVGAnimatedLength": false,
+ "SVGAnimatedLengthList": false,
+ "SVGAnimatedNumber": false,
+ "SVGAnimatedNumberList": false,
+ "SVGAnimatedPathData": false,
+ "SVGAnimatedPoints": false,
+ "SVGAnimatedPreserveAspectRatio": false,
+ "SVGAnimatedRect": false,
+ "SVGAnimatedString": false,
+ "SVGAnimatedTransformList": false,
+ "SVGAnimateElement": false,
+ "SVGAnimateMotionElement": false,
+ "SVGAnimateTransformElement": false,
+ "SVGAnimationElement": false,
+ "SVGCircleElement": false,
+ "SVGClipPathElement": false,
+ "SVGColor": false,
+ "SVGColorProfileElement": false,
+ "SVGColorProfileRule": false,
+ "SVGComponentTransferFunctionElement": false,
+ "SVGCSSRule": false,
+ "SVGCursorElement": false,
+ "SVGDefsElement": false,
+ "SVGDescElement": false,
+ "SVGDocument": false,
+ "SVGElement": false,
+ "SVGElementInstance": false,
+ "SVGElementInstanceList": false,
+ "SVGEllipseElement": false,
+ "SVGExternalResourcesRequired": false,
+ "SVGFEBlendElement": false,
+ "SVGFEColorMatrixElement": false,
+ "SVGFEComponentTransferElement": false,
+ "SVGFECompositeElement": false,
+ "SVGFEConvolveMatrixElement": false,
+ "SVGFEDiffuseLightingElement": false,
+ "SVGFEDisplacementMapElement": false,
+ "SVGFEDistantLightElement": false,
+ "SVGFEFloodElement": false,
+ "SVGFEFuncAElement": false,
+ "SVGFEFuncBElement": false,
+ "SVGFEFuncGElement": false,
+ "SVGFEFuncRElement": false,
+ "SVGFEGaussianBlurElement": false,
+ "SVGFEImageElement": false,
+ "SVGFEMergeElement": false,
+ "SVGFEMergeNodeElement": false,
+ "SVGFEMorphologyElement": false,
+ "SVGFEOffsetElement": false,
+ "SVGFEPointLightElement": false,
+ "SVGFESpecularLightingElement": false,
+ "SVGFESpotLightElement": false,
+ "SVGFETileElement": false,
+ "SVGFETurbulenceElement": false,
+ "SVGFilterElement": false,
+ "SVGFilterPrimitiveStandardAttributes": false,
+ "SVGFitToViewBox": false,
+ "SVGFontElement": false,
+ "SVGFontFaceElement": false,
+ "SVGFontFaceFormatElement": false,
+ "SVGFontFaceNameElement": false,
+ "SVGFontFaceSrcElement": false,
+ "SVGFontFaceUriElement": false,
+ "SVGForeignObjectElement": false,
+ "SVGGElement": false,
+ "SVGGlyphElement": false,
+ "SVGGlyphRefElement": false,
+ "SVGGradientElement": false,
+ "SVGHKernElement": false,
+ "SVGICCColor": false,
+ "SVGImageElement": false,
+ "SVGLangSpace": false,
+ "SVGLength": false,
+ "SVGLengthList": false,
+ "SVGLinearGradientElement": false,
+ "SVGLineElement": false,
+ "SVGLocatable": false,
+ "SVGMarkerElement": false,
+ "SVGMaskElement": false,
+ "SVGMatrix": false,
+ "SVGMetadataElement": false,
+ "SVGMissingGlyphElement": false,
+ "SVGMPathElement": false,
+ "SVGNumber": false,
+ "SVGNumberList": false,
+ "SVGPaint": false,
+ "SVGPathElement": false,
+ "SVGPathSeg": false,
+ "SVGPathSegArcAbs": false,
+ "SVGPathSegArcRel": false,
+ "SVGPathSegClosePath": false,
+ "SVGPathSegCurvetoCubicAbs": false,
+ "SVGPathSegCurvetoCubicRel": false,
+ "SVGPathSegCurvetoCubicSmoothAbs": false,
+ "SVGPathSegCurvetoCubicSmoothRel": false,
+ "SVGPathSegCurvetoQuadraticAbs": false,
+ "SVGPathSegCurvetoQuadraticRel": false,
+ "SVGPathSegCurvetoQuadraticSmoothAbs": false,
+ "SVGPathSegCurvetoQuadraticSmoothRel": false,
+ "SVGPathSegLinetoAbs": false,
+ "SVGPathSegLinetoHorizontalAbs": false,
+ "SVGPathSegLinetoHorizontalRel": false,
+ "SVGPathSegLinetoRel": false,
+ "SVGPathSegLinetoVerticalAbs": false,
+ "SVGPathSegLinetoVerticalRel": false,
+ "SVGPathSegList": false,
+ "SVGPathSegMovetoAbs": false,
+ "SVGPathSegMovetoRel": false,
+ "SVGPatternElement": false,
+ "SVGPoint": false,
+ "SVGPointList": false,
+ "SVGPolygonElement": false,
+ "SVGPolylineElement": false,
+ "SVGPreserveAspectRatio": false,
+ "SVGRadialGradientElement": false,
+ "SVGRect": false,
+ "SVGRectElement": false,
+ "SVGRenderingIntent": false,
+ "SVGScriptElement": false,
+ "SVGSetElement": false,
+ "SVGStopElement": false,
+ "SVGStringList": false,
+ "SVGStylable": false,
+ "SVGStyleElement": false,
+ "SVGSVGElement": false,
+ "SVGSwitchElement": false,
+ "SVGSymbolElement": false,
+ "SVGTests": false,
+ "SVGTextContentElement": false,
+ "SVGTextElement": false,
+ "SVGTextPathElement": false,
+ "SVGTextPositioningElement": false,
+ "SVGTitleElement": false,
+ "SVGTransform": false,
+ "SVGTransformable": false,
+ "SVGTransformList": false,
+ "SVGTRefElement": false,
+ "SVGTSpanElement": false,
+ "SVGUnitTypes": false,
+ "SVGURIReference": false,
+ "SVGUseElement": false,
+ "SVGViewElement": false,
+ "SVGViewSpec": false,
+ "SVGVKernElement": false,
+ "SVGZoomAndPan": false,
+ "TextDecoder": false,
+ "TextEncoder": false,
+ "TimeEvent": false,
+ "top": false,
+ "URL": false,
+ "WebGLActiveInfo": false,
+ "WebGLBuffer": false,
+ "WebGLContextEvent": false,
+ "WebGLFramebuffer": false,
+ "WebGLProgram": false,
+ "WebGLRenderbuffer": false,
+ "WebGLRenderingContext": false,
+ "WebGLShader": false,
+ "WebGLShaderPrecisionFormat": false,
+ "WebGLTexture": false,
+ "WebGLUniformLocation": false,
+ "WebSocket": false,
+ "window": false,
+ "Worker": false,
+ "XDomainRequest": false,
+ "XMLHttpRequest": false,
+ "XMLSerializer": false,
+ "XPathEvaluator": false,
+ "XPathException": false,
+ "XPathExpression": false,
+ "XPathNamespace": false,
+ "XPathNSResolver": false,
+ "XPathResult": false
+ },
+ "worker": {
+ "importScripts": true,
+ "postMessage": true,
+ "self": true
+ },
+ "devel": {
+ "alert": false,
+ "confirm": false,
+ "console": false,
+ "Debug": false,
+ "opera": false,
+ "prompt": false
+ },
+ "node": {
+ "__filename": false,
+ "__dirname": false,
+ "arguments": false,
+ "Buffer": false,
+ "DataView": false,
+ "console": false,
+ "exports": true,
+ "GLOBAL": false,
+ "global": false,
+ "module": false,
+ "process": false,
+ "require": false,
+ "setTimeout": false,
+ "clearTimeout": false,
+ "setInterval": false,
+ "clearInterval": false,
+ "setImmediate": false,
+ "clearImmediate": false
+ },
+ "amd": {
+ "require": false,
+ "define": false
+ },
+ "mocha": {
+ "describe": false,
+ "it": false,
+ "before": false,
+ "after": false,
+ "beforeEach": false,
+ "afterEach": false,
+ "suite": false,
+ "test": false,
+ "setup": false,
+ "teardown": false,
+ "suiteSetup": false,
+ "suiteTeardown": false
+ },
+ "jasmine": {
+ "afterAll": false,
+ "afterEach": false,
+ "beforeAll": false,
+ "beforeEach": false,
+ "describe": false,
+ "expect": false,
+ "it": false,
+ "jasmine": false,
+ "pending": false,
+ "spyOn": false,
+ "waits": false,
+ "waitsFor": false,
+ "xdescribe": false,
+ "xit": false
+ },
+ "qunit": {
+ "asyncTest": false,
+ "deepEqual": false,
+ "equal": false,
+ "expect": false,
+ "module": false,
+ "notDeepEqual": false,
+ "notEqual": false,
+ "notPropEqual": false,
+ "notStrictEqual": false,
+ "ok": false,
+ "propEqual": false,
+ "QUnit": false,
+ "raises": false,
+ "start": false,
+ "stop": false,
+ "strictEqual": false,
+ "test": false,
+ "throws": false
+ },
+ "phantom": {
+ "phantom": true,
+ "require": true,
+ "WebPage": true,
+ "console": true,
+ "exports": true
+ },
+ "couch": {
+ "require": false,
+ "respond": false,
+ "getRow": false,
+ "emit": false,
+ "send": false,
+ "start": false,
+ "sum": false,
+ "log": false,
+ "exports": false,
+ "module": false,
+ "provides": false
+ },
+ "rhino": {
+ "defineClass": false,
+ "deserialize": false,
+ "gc": false,
+ "help": false,
+ "importPackage": false,
+ "java": false,
+ "load": false,
+ "loadClass": false,
+ "print": false,
+ "quit": false,
+ "readFile": false,
+ "readUrl": false,
+ "runCommand": false,
+ "seal": false,
+ "serialize": false,
+ "spawn": false,
+ "sync": false,
+ "toint32": false,
+ "version": false
+ },
+ "wsh": {
+ "ActiveXObject": true,
+ "Enumerator": true,
+ "GetObject": true,
+ "ScriptEngine": true,
+ "ScriptEngineBuildVersion": true,
+ "ScriptEngineMajorVersion": true,
+ "ScriptEngineMinorVersion": true,
+ "VBArray": true,
+ "WSH": true,
+ "WScript": true,
+ "XDomainRequest": true
+ },
+ "jquery": {
+ "$": false,
+ "jQuery": false
+ },
+ "yui": {
+ "YUI": false,
+ "Y": false,
+ "YUI_config": false
+ }
+}
+
+},{}],24:[function(require,module,exports){
+module.exports = require('./globals.json');
+
+},{"./globals.json":23}],25:[function(require,module,exports){
+'use strict';
+
+function ToObject(val) {
+ if (val == null) {
+ throw new TypeError('Object.assign cannot be called with null or undefined');
+ }
+
+ return Object(val);
+}
+
+module.exports = Object.assign || function (target, source) {
+ var from;
+ var keys;
+ var to = ToObject(target);
+
+ for (var s = 1; s < arguments.length; s++) {
+ from = arguments[s];
+ keys = Object.keys(Object(from));
+
+ for (var i = 0; i < keys.length; i++) {
+ to[keys[i]] = from[keys[i]];
+ }
+ }
+
+ return to;
+};
+
+},{}],26:[function(require,module,exports){
+/**
+ * @fileoverview Main ESLint object.
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var espree = require("espree"),
+ estraverse = require("./util/estraverse-custom"),
+ escope = require("escope"),
+ environments = require("../conf/environments"),
+ assign = require("object-assign"),
+ rules = require("./rules"),
+ util = require("./util"),
+ RuleContext = require("./rule-context"),
+ timing = require("./timing"),
+ createTokenStore = require("./token-store.js"),
+ EventEmitter = require("events").EventEmitter,
+ escapeRegExp = require("escape-string-regexp");
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/**
+ * Parses a list of "name:boolean_value" or/and "name" options divided by comma or
+ * whitespace.
+ * @param {string} string The string to parse.
+ * @returns {Object} Result map object of names and boolean values
+ */
+function parseBooleanConfig(string) {
+ var items = {};
+ // Collapse whitespace around : to make parsing easier
+ string = string.replace(/\s*:\s*/g, ":");
+ // Collapse whitespace around ,
+ string = string.replace(/\s*,\s*/g, ",");
+ string.split(/\s|,+/).forEach(function(name) {
+ if (!name) {
+ return;
+ }
+ var pos = name.indexOf(":"),
+ value;
+ if (pos !== -1) {
+ value = name.substring(pos + 1, name.length);
+ name = name.substring(0, pos);
+ }
+
+ items[name] = (value === "true");
+
+ });
+ return items;
+}
+
+/**
+ * Parses a JSON-like config.
+ * @param {string} string The string to parse.
+ * @returns {Object} Result map object
+ */
+function parseJsonConfig(string) {
+ var items = {};
+ string = string.replace(/([a-z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,");
+ try {
+ items = JSON.parse("{" + string + "}");
+ } catch(e) { }
+
+ return items;
+}
+
+/**
+ * Parses a config of values separated by comma.
+ * @param {string} string The string to parse.
+ * @returns {Object} Result map of values and true values
+ */
+function parseListConfig(string) {
+ var items = {};
+ // Collapse whitespace around ,
+ string = string.replace(/\s*,\s*/g, ",");
+ string.split(/,+/).forEach(function(name) {
+ name = name.trim();
+ if (!name) {
+ return;
+ }
+ items[name] = true;
+ });
+ return items;
+}
+
+/**
+ * @param {Scope} scope The scope object to check.
+ * @param {string} name The name of the variable to look up.
+ * @returns {Variable} The variable object if found or null if not.
+ */
+function getVariable(scope, name) {
+ var variable = null;
+ scope.variables.some(function(v) {
+ if (v.name === name) {
+ variable = v;
+ return true;
+ } else {
+ return false;
+ }
+
+ });
+ return variable;
+}
+
+/**
+ * Ensures that variables representing built-in properties of the Global Object,
+ * and any globals declared by special block comments, are present in the global
+ * scope.
+ * @param {ASTNode} program The top node of the AST.
+ * @param {Scope} globalScope The global scope.
+ * @param {Object} config The existing configuration data.
+ * @returns {void}
+ */
+function addDeclaredGlobals(program, globalScope, config) {
+ var declaredGlobals = {},
+ explicitGlobals = {},
+ builtin = environments.builtin;
+
+ assign(declaredGlobals, builtin);
+
+ Object.keys(config.env).forEach(function (name) {
+ if (config.env[name]) {
+ var environmentGlobals = environments[name] && environments[name].globals;
+ if (environmentGlobals) {
+ assign(declaredGlobals, environmentGlobals);
+ }
+ }
+ });
+
+ assign(declaredGlobals, config.globals);
+ assign(explicitGlobals, config.astGlobals);
+
+ Object.keys(declaredGlobals).forEach(function(name) {
+ var variable = getVariable(globalScope, name);
+ if (!variable) {
+ variable = new escope.Variable(name, globalScope);
+ variable.eslintExplicitGlobal = false;
+ globalScope.variables.push(variable);
+ }
+ variable.writeable = declaredGlobals[name];
+ });
+
+ Object.keys(explicitGlobals).forEach(function(name) {
+ var variable = getVariable(globalScope, name);
+ if (!variable) {
+ variable = new escope.Variable(name, globalScope);
+ variable.eslintExplicitGlobal = true;
+ globalScope.variables.push(variable);
+ }
+ variable.writeable = explicitGlobals[name];
+ });
+}
+
+/**
+ * Add data to reporting configuration to disable reporting for list of rules
+ * starting from start location
+ * @param {Object[]} reportingConfig Current reporting configuration
+ * @param {Object} start Position to start
+ * @param {string[]} rulesToDisable List of rules
+ * @returns {void}
+ */
+function disableReporting(reportingConfig, start, rulesToDisable) {
+
+ if (rulesToDisable.length) {
+ rulesToDisable.forEach(function(rule) {
+ reportingConfig.push({
+ start: start,
+ end: null,
+ rule: rule
+ });
+ });
+ } else {
+ reportingConfig.push({
+ start: start,
+ end: null,
+ rule: null
+ });
+ }
+}
+
+/**
+ * Add data to reporting configuration to enable reporting for list of rules
+ * starting from start location
+ * @param {Object[]} reportingConfig Current reporting configuration
+ * @param {Object} start Position to start
+ * @param {string[]} rulesToEnable List of rules
+ * @returns {void}
+ */
+function enableReporting(reportingConfig, start, rulesToEnable) {
+ var i;
+
+ if (rulesToEnable.length) {
+ rulesToEnable.forEach(function(rule) {
+ for (i = reportingConfig.length - 1; i >= 0; i--) {
+ if (!reportingConfig[i].end && reportingConfig[i].rule === rule ) {
+ reportingConfig[i].end = start;
+ break;
+ }
+ }
+ });
+ } else {
+ // find all previous disabled locations if they was started as list of rules
+ var prevStart;
+ for (i = reportingConfig.length - 1; i >= 0; i--) {
+ if (prevStart && prevStart !== reportingConfig[i].start) {
+ break;
+ }
+
+ if (!reportingConfig[i].end) {
+ reportingConfig[i].end = start;
+ prevStart = reportingConfig[i].start;
+ }
+ }
+ }
+}
+
+
+/**
+ * Parses comments in file to extract file-specific config of rules, globals
+ * and environments and merges them with global config; also code blocks
+ * where reporting is disabled or enabled and merges them with reporting config.
+ * @param {ASTNode} ast The top node of the AST.
+ * @param {Object} config The existing configuration data.
+ * @param {Object[]} reportingConfig The existing reporting configuration data.
+ * @returns {void}
+ */
+function modifyConfigsFromComments(ast, config, reportingConfig) {
+
+ var commentConfig = {
+ astGlobals: {},
+ rules: {},
+ env: {}
+ };
+ var commentRules = {};
+
+ ast.comments.forEach(function(comment) {
+ if (comment.type === "Block") {
+
+ var value = comment.value.trim();
+ var match = /^(eslint-\w+|eslint|globals?)(\s|$)/.exec(value);
+
+ if (match) {
+ value = value.substring(match.index + match[1].length);
+
+ switch (match[1]) {
+ case "globals":
+ case "global":
+ util.mixin(commentConfig.astGlobals, parseBooleanConfig(value));
+ break;
+
+ case "eslint-env":
+ util.mixin(commentConfig.env, parseListConfig(value));
+ break;
+
+ case "eslint-disable":
+ disableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value)));
+ break;
+
+ case "eslint-enable":
+ enableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value)));
+ break;
+
+ case "eslint":
+ var items = parseJsonConfig(value);
+ Object.keys(items).forEach(function(name) {
+ var ruleValue = items[name];
+ if (typeof ruleValue === "number" || (Array.isArray(ruleValue) && typeof ruleValue[0] === "number")) {
+ commentRules[name] = ruleValue;
+ }
+ });
+ break;
+
+ // no default
+ }
+ }
+ }
+ });
+
+ // apply environment rules before user rules
+ Object.keys(commentConfig.env).forEach(function (name) {
+ var environmentRules = environments[name] && environments[name].rules;
+ if (commentConfig.env[name] && environmentRules) {
+ util.mixin(commentConfig.rules, environmentRules);
+ }
+ });
+ util.mixin(commentConfig.rules, commentRules);
+
+ util.mergeConfigs(config, commentConfig);
+}
+
+/**
+ * Check if message of rule with ruleId should be ignored in location
+ * @param {Object[]} reportingConfig Collection of ignore records
+ * @param {string} ruleId Id of rule
+ * @param {Object} location Location of message
+ * @returns {boolean} True if message should be ignored, false otherwise
+ */
+function isDisabledByReportingConfig(reportingConfig, ruleId, location) {
+
+ for (var i = 0, c = reportingConfig.length; i < c; i++) {
+
+ var ignore = reportingConfig[i];
+ if ((!ignore.rule || ignore.rule === ruleId) &&
+ (location.line > ignore.start.line || (location.line === ignore.start.line && location.column >= ignore.start.column)) &&
+ (!ignore.end || (location.line < ignore.end.line || (location.line === ignore.end.line && location.column <= ignore.end.column)))) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Process initial config to make it safe to extend by file comment config
+ * @param {Object} config Initial config
+ * @returns {Object} Processed config
+ */
+function prepareConfig(config) {
+
+ config.globals = config.globals || config.global || {};
+ delete config.global;
+
+ var copiedRules = {};
+
+ if (typeof config.rules === "object") {
+ Object.keys(config.rules).forEach(function(k) {
+ var rule = config.rules[k];
+ if (Array.isArray(rule)) {
+ copiedRules[k] = rule.slice();
+ } else {
+ copiedRules[k] = rule;
+ }
+ });
+ }
+
+ return {
+ rules: copiedRules,
+ globals: util.mergeConfigs({}, config.globals),
+ env: util.mergeConfigs({}, config.env || {}),
+ settings: util.mergeConfigs({}, config.settings || {}),
+ ecmaFeatures: util.mergeConfigs({}, config.ecmaFeatures || {})
+ };
+}
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/**
+ * Object that is responsible for verifying JavaScript text
+ * @name eslint
+ */
+module.exports = (function() {
+
+ var api = Object.create(new EventEmitter()),
+ messages = [],
+ currentText = null,
+ currentTextLines = [],
+ currentConfig = null,
+ currentTokens = null,
+ currentScopes = null,
+ scopeMap = null,
+ currentFilename = null,
+ controller = null,
+ reportingConfig = [],
+ commentLocsEnter = [],
+ commentLocsExit = [];
+
+ /**
+ * Parses text into an AST. Moved out here because the try-catch prevents
+ * optimization of functions, so it's best to keep the try-catch as isolated
+ * as possible
+ * @param {string} text The text to parse.
+ * @param {Object} config The ESLint configuration object.
+ * @returns {ASTNode} The AST if successful or null if not.
+ * @private
+ */
+ function parse(text, config) {
+
+ /*
+ * Check for parsing errors first. If there's a parsing error, nothing
+ * else can happen. However, a parsing error does not throw an error
+ * from this method - it's just considered a fatal error message, a
+ * problem that ESLint identified just like any other.
+ */
+ try {
+ return espree.parse(text, {
+ loc: true,
+ range: true,
+ raw: true,
+ tokens: true,
+ comment: true,
+ attachComment: true,
+ ecmaFeatures: config.ecmaFeatures
+ });
+ } catch (ex) {
+
+ messages.push({
+ fatal: true,
+ severity: 2,
+
+ // messages come as "Line X: Unexpected token foo", so strip off leading part
+ message: ex.message.substring(ex.message.indexOf(":") + 1).trim(),
+
+ line: ex.lineNumber,
+ column: ex.column
+ });
+
+ return null;
+ }
+ }
+
+ /**
+ * Check collection of comments to prevent double event for comment as
+ * leading and trailing, then emit event if passing
+ * @param {ASTNode[]} comments Collection of comment nodes
+ * @param {Object[]} locs List of locations of previous comment nodes
+ * @param {string} eventName Event name postfix
+ * @returns {void}
+ */
+ function emitComments(comments, locs, eventName) {
+
+ if (comments.length) {
+ comments.forEach(function(node) {
+ if (locs.indexOf(node.loc) >= 0) {
+ locs.splice(locs.indexOf(node.loc), 1);
+ } else {
+ locs.push(node.loc);
+ api.emit(node.type + eventName, node);
+ }
+ });
+ }
+ }
+
+ /**
+ * Shortcut to check and emit enter of comment nodes
+ * @param {ASTNode[]} comments Collection of comment nodes
+ * @returns {void}
+ */
+ function emitCommentsEnter(comments) {
+ emitComments(comments, commentLocsEnter, "Comment");
+ }
+
+ /**
+ * Shortcut to check and emit exit of comment nodes
+ * @param {ASTNode[]} comments Collection of comment nodes
+ * @returns {void}
+ */
+ function emitCommentsExit(comments) {
+ emitComments(comments, commentLocsExit, "Comment:exit");
+ }
+
+ /**
+ * Get the severity level of a rule (0 - none, 1 - warning, 2 - error)
+ * Returns 0 if the rule config is not valid (an Array or a number)
+ * @param {Array|number} ruleConfig rule configuration
+ * @returns {number} 0, 1, or 2, indicating rule severity
+ */
+ function getRuleSeverity(ruleConfig) {
+ if (typeof ruleConfig === "number") {
+ return ruleConfig;
+ } else if (Array.isArray(ruleConfig)) {
+ return ruleConfig[0];
+ } else {
+ return 0;
+ }
+ }
+
+ /**
+ * Get the options for a rule (not including severity), if any
+ * @param {Array|number} ruleConfig rule configuration
+ * @returns {Array} of rule options, empty Array if none
+ */
+ function getRuleOptions(ruleConfig) {
+ if (Array.isArray(ruleConfig)) {
+ return ruleConfig.slice(1);
+ } else {
+ return [];
+ }
+ }
+
+ // set unlimited listeners (see https://github.com/eslint/eslint/issues/524)
+ api.setMaxListeners(0);
+
+ /**
+ * Resets the internal state of the object.
+ * @returns {void}
+ */
+ api.reset = function() {
+ this.removeAllListeners();
+ messages = [];
+ currentConfig = null;
+ currentText = null;
+ currentTextLines = [];
+ currentTokens = null;
+ currentScopes = null;
+ scopeMap = null;
+ controller = null;
+ reportingConfig = [];
+ commentLocsEnter = [];
+ commentLocsExit = [];
+ };
+
+ /**
+ * Verifies the text against the rules specified by the second argument.
+ * @param {string} text The JavaScript text to verify.
+ * @param {Object} config An object whose keys specify the rules to use.
+ * @param {string=} filename The optional filename of the file being checked.
+ * If this is not set, the filename will default to '' in the rule context.
+ * @param {boolean=} saveState Indicates if the state from the last run should be saved.
+ * Mostly useful for testing purposes.
+ * @returns {Object[]} The results as an array of messages or null if no messages.
+ */
+ api.verify = function(text, config, filename, saveState) {
+
+ var ast,
+ shebang;
+
+ // set the current parsed filename
+ currentFilename = filename;
+
+ if (!saveState) {
+ this.reset();
+ }
+
+ ast = parse(text.replace(/^#!([^\r\n]+)/, function(match, captured) {
+ shebang = captured;
+ return "//" + captured;
+ }), config);
+
+ // if espree failed to parse the file, there's no sense in setting up rules
+ if (ast) {
+ // process initial config to make it safe to extend
+ config = prepareConfig(config);
+
+ // parse global comments and modify config
+ modifyConfigsFromComments(ast, config, reportingConfig);
+
+ // enable appropriate rules
+ Object.keys(config.rules).filter(function(key) {
+ return getRuleSeverity(config.rules[key]) > 0;
+ }).forEach(function(key) {
+
+ var ruleCreator = rules.get(key),
+ severity = getRuleSeverity(config.rules[key]),
+ options = getRuleOptions(config.rules[key]),
+ rule;
+
+ if (ruleCreator) {
+ try {
+ rule = ruleCreator(new RuleContext(key, api, severity, options, config.settings));
+
+ // add all the node types as listeners
+ Object.keys(rule).forEach(function(nodeType) {
+ api.on(nodeType, timing.enabled
+ ? timing.time(key, rule[nodeType])
+ : rule[nodeType]
+ );
+ });
+ } catch(ex) {
+ ex.message = "Error while loading rule '" + key + "': " + ex.message;
+ throw ex;
+ }
+
+ } else {
+ throw new Error("Definition for rule '" + key + "' was not found.");
+ }
+ });
+
+ // save config so rules can access as necessary
+ currentConfig = config;
+ currentText = text;
+ controller = new estraverse.Controller();
+
+ // gather data that may be needed by the rules
+ currentScopes = escope.analyze(ast, { ignoreEval: true }).scopes;
+
+ /*
+ * Index the scopes by the start range of their block for efficient
+ * lookup in getScope.
+ */
+ scopeMap = [];
+ currentScopes.forEach(function (scope, index) {
+ var range = scope.block.range[0];
+
+ // Sometimes two scopes are returned for a given node. This is
+ // handled later in a known way, so just don't overwrite here.
+ if (!scopeMap[range]) {
+ scopeMap[range] = index;
+ }
+ });
+
+ /*
+ * Split text here into array of lines so
+ * it's not being done repeatedly
+ * by individual rules.
+ */
+ currentTextLines = currentText.split(/\r?\n|\u2028|\u2029/g);
+
+ // Freezing so array isn't accidentally changed by a rule.
+ Object.freeze(currentTextLines);
+
+ currentTokens = createTokenStore(ast.tokens);
+ Object.keys(currentTokens).forEach(function(method) {
+ api[method] = currentTokens[method];
+ });
+
+ // augment global scope with declared global variables
+ addDeclaredGlobals(ast, currentScopes[0], currentConfig);
+
+ // remove shebang comments
+ if (shebang && ast.comments.length && ast.comments[0].value === shebang) {
+ ast.comments.splice(0, 1);
+
+ if (ast.body.length && ast.body[0].leadingComments && ast.body[0].leadingComments[0].value === shebang) {
+ ast.body[0].leadingComments.splice(0, 1);
+ }
+ }
+
+ /*
+ * Each node has a type property. Whenever a particular type of node is found,
+ * an event is fired. This allows any listeners to automatically be informed
+ * that this type of node has been found and react accordingly.
+ */
+ controller.traverse(ast, {
+ enter: function(node, parent) {
+
+ var comments = api.getComments(node);
+
+ emitCommentsEnter(comments.leading);
+ node.parent = parent;
+ api.emit(node.type, node);
+ emitCommentsEnter(comments.trailing);
+ },
+ leave: function(node) {
+
+ var comments = api.getComments(node);
+
+ emitCommentsExit(comments.trailing);
+ api.emit(node.type + ":exit", node);
+ emitCommentsExit(comments.leading);
+ }
+ });
+
+ }
+
+ // sort by line and column
+ messages.sort(function(a, b) {
+ var lineDiff = a.line - b.line;
+
+ if (lineDiff === 0) {
+ return a.column - b.column;
+ } else {
+ return lineDiff;
+ }
+ });
+
+ return messages;
+ };
+
+ /**
+ * Reports a message from one of the rules.
+ * @param {string} ruleId The ID of the rule causing the message.
+ * @param {number} severity The severity level of the rule as configured.
+ * @param {ASTNode} node The AST node that the message relates to.
+ * @param {Object=} location An object containing the error line and column
+ * numbers. If location is not provided the node's start location will
+ * be used.
+ * @param {string} message The actual message.
+ * @param {Object} opts Optional template data which produces a formatted message
+ * with symbols being replaced by this object's values.
+ * @returns {void}
+ */
+ api.report = function(ruleId, severity, node, location, message, opts) {
+
+ if (typeof location === "string") {
+ opts = message;
+ message = location;
+ location = node.loc.start;
+ }
+
+ Object.keys(opts || {}).forEach(function (key) {
+ var rx = new RegExp("{{" + escapeRegExp(key) + "}}", "g");
+ message = message.replace(rx, opts[key]);
+ });
+
+ if (isDisabledByReportingConfig(reportingConfig, ruleId, location)) {
+ return;
+ }
+
+ messages.push({
+ ruleId: ruleId,
+ severity: severity,
+ node: node,
+ message: message,
+ line: location.line,
+ column: location.column,
+ source: api.getSource(node)
+ });
+ };
+
+ /**
+ * Gets the source code for the given node.
+ * @param {ASTNode=} node The AST node to get the text for.
+ * @param {int=} beforeCount The number of characters before the node to retrieve.
+ * @param {int=} afterCount The number of characters after the node to retrieve.
+ * @returns {string} The text representing the AST node.
+ */
+ api.getSource = function(node, beforeCount, afterCount) {
+ if (node) {
+ return (currentText !== null) ? currentText.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
+ node.range[1] + (afterCount || 0)) : null;
+ } else {
+ return currentText;
+ }
+
+ };
+
+ /**
+ * Gets the entire source text split into an array of lines.
+ * @returns {Array} The source text as an array of lines.
+ */
+ api.getSourceLines = function() {
+ return currentTextLines;
+ };
+
+ /**
+ * Gets all comments for the given node.
+ * @param {ASTNode} node The AST node to get the comments for.
+ * @returns {Object} The list of comments indexed by their position.
+ */
+ api.getComments = function(node) {
+
+ var leadingComments = node.leadingComments || [],
+ trailingComments = node.trailingComments || [];
+
+ /*
+ * espree adds a "comments" array on Program nodes rather than
+ * leadingComments/trailingComments. Comments are only left in the
+ * Program node comments array if there is no executable code.
+ */
+ if (node.type === "Program") {
+ if (node.body.length === 0) {
+ leadingComments = node.comments;
+ }
+ }
+
+ return {
+ leading: leadingComments,
+ trailing: trailingComments
+ };
+ };
+
+ /**
+ * Retrieves the JSDoc comment for a given node.
+ * @param {ASTNode} node The AST node to get the comment for.
+ * @returns {ASTNode} The BlockComment node containing the JSDoc for the
+ * given node or null if not found.
+ */
+ api.getJSDocComment = function(node) {
+
+ var parent = node.parent,
+ line = node.loc.start.line;
+
+ /**
+ * Finds a JSDoc comment node in an array of comment nodes.
+ * @param {ASTNode[]} comments The array of comment nodes to search.
+ * @returns {ASTNode} The node if found, null if not.
+ * @private
+ */
+ function findJSDocComment(comments) {
+
+ if (comments) {
+ for (var i = comments.length - 1; i >= 0; i--) {
+ if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") {
+
+ if (line - comments[i].loc.end.line <= 1) {
+ return comments[i];
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+ switch (node.type) {
+ case "FunctionDeclaration":
+ return findJSDocComment(node.leadingComments);
+
+ case "FunctionExpression":
+
+ if (parent.type !== "CallExpression" || parent.callee !== node) {
+ while (parent && !parent.leadingComments && parent.type !== "FunctionExpression" && parent.type !== "FunctionDeclaration") {
+ parent = parent.parent;
+ }
+
+ return parent && (parent.type !== "FunctionDeclaration") ? findJSDocComment(parent.leadingComments) : null;
+ }
+
+ // falls through
+
+ default:
+ return null;
+ }
+ };
+
+ /**
+ * Gets nodes that are ancestors of current node.
+ * @returns {ASTNode[]} Array of objects representing ancestors.
+ */
+ api.getAncestors = function() {
+ return controller.parents();
+ };
+
+
+ /**
+ * Gets the scope for the current node.
+ * @returns {Object} An object representing the current node's scope.
+ */
+ api.getScope = function() {
+ var parents = controller.parents(),
+ innerBlock = null,
+ selectedScopeIndex;
+
+ // Don't do this for Program nodes - they have no parents
+ if (parents.length) {
+
+ // if current node is function declaration, add it to the list
+ var current = controller.current();
+ if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression") {
+ parents.push(current);
+ }
+
+ // Ascend the current node's parents
+ for (var i = parents.length - 1; i >= 0; --i) {
+
+ // The first node that requires a scope is the node that will be
+ // our current node's innermost scope.
+ if (escope.Scope.isScopeRequired(parents[i])) {
+ innerBlock = parents[i];
+ break;
+ }
+ }
+
+ // Find and return the innermost scope
+ selectedScopeIndex = scopeMap[innerBlock.range[0]];
+
+ // Named function expressions create two nested scope objects. The
+ // outer scope contains only the function expression name. We return
+ // the inner scope.
+ if (innerBlock.type === "FunctionExpression" && innerBlock.id && innerBlock.id.name) {
+ ++selectedScopeIndex;
+ }
+
+ return currentScopes[selectedScopeIndex];
+ } else {
+ return currentScopes[0]; // global scope
+ }
+ };
+
+ /**
+ * Gets the filename for the currently parsed source.
+ * @returns {string} The filename associated with the source being parsed.
+ * Defaults to "" if no filename info is present.
+ */
+ api.getFilename = function() {
+ if (typeof currentFilename === "string") {
+ return currentFilename;
+ } else {
+ return "";
+ }
+ };
+
+ /**
+ * Defines a new linting rule.
+ * @param {string} ruleId A unique rule identifier
+ * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers
+ * @returns {void}
+ */
+ var defineRule = api.defineRule = function(ruleId, ruleModule) {
+ rules.define(ruleId, ruleModule);
+ };
+
+ /**
+ * Defines many new linting rules.
+ * @param {object} rulesToDefine map from unique rule identifier to rule
+ * @returns {void}
+ */
+ api.defineRules = function(rulesToDefine) {
+ Object.getOwnPropertyNames(rulesToDefine).forEach(function(ruleId) {
+ defineRule(ruleId, rulesToDefine[ruleId]);
+ });
+ };
+
+ /**
+ * Gets the default eslint configuration.
+ * @returns {Object} Object mapping rule IDs to their default configurations
+ */
+ api.defaults = function() {
+ return require("../conf/eslint.json");
+ };
+
+ return api;
+
+}());
+
+},{"../conf/environments":1,"../conf/eslint.json":2,"./rule-context":28,"./rules":29,"./timing":173,"./token-store.js":174,"./util":175,"./util/estraverse-custom":176,"escape-string-regexp":11,"escope":12,"espree":13,"events":3,"object-assign":25}],27:[function(require,module,exports){
+module.exports = function() {
+ var rules = Object.create(null);
+ rules["block-scoped-var"] = require("./rules/block-scoped-var");
+ rules["brace-style"] = require("./rules/brace-style");
+ rules["camelcase"] = require("./rules/camelcase");
+ rules["comma-spacing"] = require("./rules/comma-spacing");
+ rules["comma-style"] = require("./rules/comma-style");
+ rules["complexity"] = require("./rules/complexity");
+ rules["consistent-return"] = require("./rules/consistent-return");
+ rules["consistent-this"] = require("./rules/consistent-this");
+ rules["curly"] = require("./rules/curly");
+ rules["default-case"] = require("./rules/default-case");
+ rules["dot-notation"] = require("./rules/dot-notation");
+ rules["eol-last"] = require("./rules/eol-last");
+ rules["eqeqeq"] = require("./rules/eqeqeq");
+ rules["func-names"] = require("./rules/func-names");
+ rules["func-style"] = require("./rules/func-style");
+ rules["generator-star"] = require("./rules/generator-star");
+ rules["global-strict"] = require("./rules/global-strict");
+ rules["guard-for-in"] = require("./rules/guard-for-in");
+ rules["handle-callback-err"] = require("./rules/handle-callback-err");
+ rules["key-spacing"] = require("./rules/key-spacing");
+ rules["max-depth"] = require("./rules/max-depth");
+ rules["max-len"] = require("./rules/max-len");
+ rules["max-nested-callbacks"] = require("./rules/max-nested-callbacks");
+ rules["max-params"] = require("./rules/max-params");
+ rules["max-statements"] = require("./rules/max-statements");
+ rules["new-cap"] = require("./rules/new-cap");
+ rules["new-parens"] = require("./rules/new-parens");
+ rules["no-alert"] = require("./rules/no-alert");
+ rules["no-array-constructor"] = require("./rules/no-array-constructor");
+ rules["no-bitwise"] = require("./rules/no-bitwise");
+ rules["no-caller"] = require("./rules/no-caller");
+ rules["no-catch-shadow"] = require("./rules/no-catch-shadow");
+ rules["no-comma-dangle"] = require("./rules/no-comma-dangle");
+ rules["no-cond-assign"] = require("./rules/no-cond-assign");
+ rules["no-console"] = require("./rules/no-console");
+ rules["no-constant-condition"] = require("./rules/no-constant-condition");
+ rules["no-control-regex"] = require("./rules/no-control-regex");
+ rules["no-debugger"] = require("./rules/no-debugger");
+ rules["no-delete-var"] = require("./rules/no-delete-var");
+ rules["no-div-regex"] = require("./rules/no-div-regex");
+ rules["no-dupe-keys"] = require("./rules/no-dupe-keys");
+ rules["no-else-return"] = require("./rules/no-else-return");
+ rules["no-empty-class"] = require("./rules/no-empty-class");
+ rules["no-empty-label"] = require("./rules/no-empty-label");
+ rules["no-empty"] = require("./rules/no-empty");
+ rules["no-eq-null"] = require("./rules/no-eq-null");
+ rules["no-eval"] = require("./rules/no-eval");
+ rules["no-ex-assign"] = require("./rules/no-ex-assign");
+ rules["no-extend-native"] = require("./rules/no-extend-native");
+ rules["no-extra-bind"] = require("./rules/no-extra-bind");
+ rules["no-extra-boolean-cast"] = require("./rules/no-extra-boolean-cast");
+ rules["no-extra-parens"] = require("./rules/no-extra-parens");
+ rules["no-extra-semi"] = require("./rules/no-extra-semi");
+ rules["no-extra-strict"] = require("./rules/no-extra-strict");
+ rules["no-fallthrough"] = require("./rules/no-fallthrough");
+ rules["no-floating-decimal"] = require("./rules/no-floating-decimal");
+ rules["no-func-assign"] = require("./rules/no-func-assign");
+ rules["no-implied-eval"] = require("./rules/no-implied-eval");
+ rules["no-inline-comments"] = require("./rules/no-inline-comments");
+ rules["no-inner-declarations"] = require("./rules/no-inner-declarations");
+ rules["no-invalid-regexp"] = require("./rules/no-invalid-regexp");
+ rules["no-irregular-whitespace"] = require("./rules/no-irregular-whitespace");
+ rules["no-iterator"] = require("./rules/no-iterator");
+ rules["no-label-var"] = require("./rules/no-label-var");
+ rules["no-labels"] = require("./rules/no-labels");
+ rules["no-lone-blocks"] = require("./rules/no-lone-blocks");
+ rules["no-lonely-if"] = require("./rules/no-lonely-if");
+ rules["no-loop-func"] = require("./rules/no-loop-func");
+ rules["no-mixed-requires"] = require("./rules/no-mixed-requires");
+ rules["no-mixed-spaces-and-tabs"] = require("./rules/no-mixed-spaces-and-tabs");
+ rules["no-multi-spaces"] = require("./rules/no-multi-spaces");
+ rules["no-multi-str"] = require("./rules/no-multi-str");
+ rules["no-multiple-empty-lines"] = require("./rules/no-multiple-empty-lines");
+ rules["no-native-reassign"] = require("./rules/no-native-reassign");
+ rules["no-negated-in-lhs"] = require("./rules/no-negated-in-lhs");
+ rules["no-nested-ternary"] = require("./rules/no-nested-ternary");
+ rules["no-new-func"] = require("./rules/no-new-func");
+ rules["no-new-object"] = require("./rules/no-new-object");
+ rules["no-new-require"] = require("./rules/no-new-require");
+ rules["no-new-wrappers"] = require("./rules/no-new-wrappers");
+ rules["no-new"] = require("./rules/no-new");
+ rules["no-obj-calls"] = require("./rules/no-obj-calls");
+ rules["no-octal-escape"] = require("./rules/no-octal-escape");
+ rules["no-octal"] = require("./rules/no-octal");
+ rules["no-path-concat"] = require("./rules/no-path-concat");
+ rules["no-plusplus"] = require("./rules/no-plusplus");
+ rules["no-process-env"] = require("./rules/no-process-env");
+ rules["no-process-exit"] = require("./rules/no-process-exit");
+ rules["no-proto"] = require("./rules/no-proto");
+ rules["no-redeclare"] = require("./rules/no-redeclare");
+ rules["no-regex-spaces"] = require("./rules/no-regex-spaces");
+ rules["no-reserved-keys"] = require("./rules/no-reserved-keys");
+ rules["no-restricted-modules"] = require("./rules/no-restricted-modules");
+ rules["no-return-assign"] = require("./rules/no-return-assign");
+ rules["no-script-url"] = require("./rules/no-script-url");
+ rules["no-self-compare"] = require("./rules/no-self-compare");
+ rules["no-sequences"] = require("./rules/no-sequences");
+ rules["no-shadow-restricted-names"] = require("./rules/no-shadow-restricted-names");
+ rules["no-shadow"] = require("./rules/no-shadow");
+ rules["no-space-before-semi"] = require("./rules/no-space-before-semi");
+ rules["no-spaced-func"] = require("./rules/no-spaced-func");
+ rules["no-sparse-arrays"] = require("./rules/no-sparse-arrays");
+ rules["no-sync"] = require("./rules/no-sync");
+ rules["no-ternary"] = require("./rules/no-ternary");
+ rules["no-trailing-spaces"] = require("./rules/no-trailing-spaces");
+ rules["no-undef-init"] = require("./rules/no-undef-init");
+ rules["no-undef"] = require("./rules/no-undef");
+ rules["no-undefined"] = require("./rules/no-undefined");
+ rules["no-underscore-dangle"] = require("./rules/no-underscore-dangle");
+ rules["no-unreachable"] = require("./rules/no-unreachable");
+ rules["no-unused-expressions"] = require("./rules/no-unused-expressions");
+ rules["no-unused-vars"] = require("./rules/no-unused-vars");
+ rules["no-use-before-define"] = require("./rules/no-use-before-define");
+ rules["no-var"] = require("./rules/no-var");
+ rules["no-void"] = require("./rules/no-void");
+ rules["no-warning-comments"] = require("./rules/no-warning-comments");
+ rules["no-with"] = require("./rules/no-with");
+ rules["no-wrap-func"] = require("./rules/no-wrap-func");
+ rules["one-var"] = require("./rules/one-var");
+ rules["operator-assignment"] = require("./rules/operator-assignment");
+ rules["padded-blocks"] = require("./rules/padded-blocks");
+ rules["quote-props"] = require("./rules/quote-props");
+ rules["quotes"] = require("./rules/quotes");
+ rules["radix"] = require("./rules/radix");
+ rules["semi"] = require("./rules/semi");
+ rules["sort-vars"] = require("./rules/sort-vars");
+ rules["space-after-function-name"] = require("./rules/space-after-function-name");
+ rules["space-after-keywords"] = require("./rules/space-after-keywords");
+ rules["space-before-blocks"] = require("./rules/space-before-blocks");
+ rules["space-in-brackets"] = require("./rules/space-in-brackets");
+ rules["space-in-parens"] = require("./rules/space-in-parens");
+ rules["space-infix-ops"] = require("./rules/space-infix-ops");
+ rules["space-return-throw-case"] = require("./rules/space-return-throw-case");
+ rules["space-unary-ops"] = require("./rules/space-unary-ops");
+ rules["spaced-line-comment"] = require("./rules/spaced-line-comment");
+ rules["strict"] = require("./rules/strict");
+ rules["use-isnan"] = require("./rules/use-isnan");
+ rules["valid-jsdoc"] = require("./rules/valid-jsdoc");
+ rules["valid-typeof"] = require("./rules/valid-typeof");
+ rules["vars-on-top"] = require("./rules/vars-on-top");
+ rules["wrap-iife"] = require("./rules/wrap-iife");
+ rules["wrap-regex"] = require("./rules/wrap-regex");
+ rules["yoda"] = require("./rules/yoda");
+
+ return rules;
+};
+},{"./rules/block-scoped-var":30,"./rules/brace-style":31,"./rules/camelcase":32,"./rules/comma-spacing":33,"./rules/comma-style":34,"./rules/complexity":35,"./rules/consistent-return":36,"./rules/consistent-this":37,"./rules/curly":38,"./rules/default-case":39,"./rules/dot-notation":40,"./rules/eol-last":41,"./rules/eqeqeq":42,"./rules/func-names":43,"./rules/func-style":44,"./rules/generator-star":45,"./rules/global-strict":46,"./rules/guard-for-in":47,"./rules/handle-callback-err":48,"./rules/key-spacing":49,"./rules/max-depth":50,"./rules/max-len":51,"./rules/max-nested-callbacks":52,"./rules/max-params":53,"./rules/max-statements":54,"./rules/new-cap":55,"./rules/new-parens":56,"./rules/no-alert":57,"./rules/no-array-constructor":58,"./rules/no-bitwise":59,"./rules/no-caller":60,"./rules/no-catch-shadow":61,"./rules/no-comma-dangle":62,"./rules/no-cond-assign":63,"./rules/no-console":64,"./rules/no-constant-condition":65,"./rules/no-control-regex":66,"./rules/no-debugger":67,"./rules/no-delete-var":68,"./rules/no-div-regex":69,"./rules/no-dupe-keys":70,"./rules/no-else-return":71,"./rules/no-empty":74,"./rules/no-empty-class":72,"./rules/no-empty-label":73,"./rules/no-eq-null":75,"./rules/no-eval":76,"./rules/no-ex-assign":77,"./rules/no-extend-native":78,"./rules/no-extra-bind":79,"./rules/no-extra-boolean-cast":80,"./rules/no-extra-parens":81,"./rules/no-extra-semi":82,"./rules/no-extra-strict":83,"./rules/no-fallthrough":84,"./rules/no-floating-decimal":85,"./rules/no-func-assign":86,"./rules/no-implied-eval":87,"./rules/no-inline-comments":88,"./rules/no-inner-declarations":89,"./rules/no-invalid-regexp":90,"./rules/no-irregular-whitespace":91,"./rules/no-iterator":92,"./rules/no-label-var":93,"./rules/no-labels":94,"./rules/no-lone-blocks":95,"./rules/no-lonely-if":96,"./rules/no-loop-func":97,"./rules/no-mixed-requires":98,"./rules/no-mixed-spaces-and-tabs":99,"./rules/no-multi-spaces":100,"./rules/no-multi-str":101,"./rules/no-multiple-empty-lines":102,"./rules/no-native-reassign":103,"./rules/no-negated-in-lhs":104,"./rules/no-nested-ternary":105,"./rules/no-new":110,"./rules/no-new-func":106,"./rules/no-new-object":107,"./rules/no-new-require":108,"./rules/no-new-wrappers":109,"./rules/no-obj-calls":111,"./rules/no-octal":113,"./rules/no-octal-escape":112,"./rules/no-path-concat":114,"./rules/no-plusplus":115,"./rules/no-process-env":116,"./rules/no-process-exit":117,"./rules/no-proto":118,"./rules/no-redeclare":119,"./rules/no-regex-spaces":120,"./rules/no-reserved-keys":121,"./rules/no-restricted-modules":122,"./rules/no-return-assign":123,"./rules/no-script-url":124,"./rules/no-self-compare":125,"./rules/no-sequences":126,"./rules/no-shadow":128,"./rules/no-shadow-restricted-names":127,"./rules/no-space-before-semi":129,"./rules/no-spaced-func":130,"./rules/no-sparse-arrays":131,"./rules/no-sync":132,"./rules/no-ternary":133,"./rules/no-trailing-spaces":134,"./rules/no-undef":136,"./rules/no-undef-init":135,"./rules/no-undefined":137,"./rules/no-underscore-dangle":138,"./rules/no-unreachable":139,"./rules/no-unused-expressions":140,"./rules/no-unused-vars":141,"./rules/no-use-before-define":142,"./rules/no-var":143,"./rules/no-void":144,"./rules/no-warning-comments":145,"./rules/no-with":146,"./rules/no-wrap-func":147,"./rules/one-var":148,"./rules/operator-assignment":149,"./rules/padded-blocks":150,"./rules/quote-props":151,"./rules/quotes":152,"./rules/radix":153,"./rules/semi":154,"./rules/sort-vars":155,"./rules/space-after-function-name":156,"./rules/space-after-keywords":157,"./rules/space-before-blocks":158,"./rules/space-in-brackets":159,"./rules/space-in-parens":160,"./rules/space-infix-ops":161,"./rules/space-return-throw-case":162,"./rules/space-unary-ops":163,"./rules/spaced-line-comment":164,"./rules/strict":165,"./rules/use-isnan":166,"./rules/valid-jsdoc":167,"./rules/valid-typeof":168,"./rules/vars-on-top":169,"./rules/wrap-iife":170,"./rules/wrap-regex":171,"./rules/yoda":172}],28:[function(require,module,exports){
+/**
+ * @fileoverview RuleContext utility for rules
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+var PASSTHROUGHS = [
+ "getSource",
+ "getSourceLines",
+ "getTokens",
+ "getTokensBefore",
+ "getTokenBefore",
+ "getTokensAfter",
+ "getTokenAfter",
+ "getFirstTokens",
+ "getFirstToken",
+ "getLastTokens",
+ "getLastToken",
+ "getTokensBetween",
+ "getComments",
+ "getAncestors",
+ "getScope",
+ "getJSDocComment",
+ "getFilename"
+ ];
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+/**
+ * Acts as an abstraction layer between rules and the main eslint object.
+ * @constructor
+ * @param {string} ruleId The ID of the rule using this object.
+ * @param {eslint} eslint The eslint object.
+ * @param {number} severity The configured severity level of the rule.
+ * @param {array} options The configuration information to be added to the rule.
+ * @param {object} settings The configuration settings passed from the config file.
+ */
+function RuleContext(ruleId, eslint, severity, options, settings) {
+
+ /**
+ * The read-only ID of the rule.
+ */
+ Object.defineProperty(this, "id", {
+ value: ruleId
+ });
+
+ /**
+ * The read-only options of the rule
+ */
+ Object.defineProperty(this, "options", {
+ value: options
+ });
+
+ /**
+ * The read-only settings shared between all rules
+ */
+ Object.defineProperty(this, "settings", {
+ value: settings
+ });
+
+ // copy over passthrough methods
+ PASSTHROUGHS.forEach(function(name) {
+ this[name] = function() {
+ return eslint[name].apply(eslint, arguments);
+ };
+ }, this);
+
+ /**
+ * Passthrough to eslint.report() that automatically assigns the rule ID and severity.
+ * @param {ASTNode} node The AST node related to the message.
+ * @param {Object=} location The location of the error.
+ * @param {string} message The message to display to the user.
+ * @param {Object} opts Optional template data which produces a formatted message
+ * with symbols being replaced by this object's values.
+ * @returns {void}
+ */
+ this.report = function(node, location, message, opts) {
+ eslint.report(ruleId, severity, node, location, message, opts);
+ };
+
+}
+
+RuleContext.prototype = {
+ constructor: RuleContext
+};
+
+module.exports = RuleContext;
+
+},{}],29:[function(require,module,exports){
+/**
+ * @fileoverview Defines a storage for rules.
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var loadRules = require("./load-rules");
+
+//------------------------------------------------------------------------------
+// Privates
+//------------------------------------------------------------------------------
+
+var rules = Object.create(null);
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+/**
+ * Registers a rule module for rule id in storage.
+ * @param {String} ruleId Rule id (file name).
+ * @param {Function} ruleModule Rule handler.
+ * @returns {void}
+ */
+function define(ruleId, ruleModule) {
+ rules[ruleId] = ruleModule;
+}
+
+exports.define = define;
+
+/**
+ * Loads and registers all rules from passed rules directory.
+ * @param {String} [rulesDir] Path to rules directory, may be relative. Defaults to `lib/rules`.
+ * @returns {void}
+ */
+function load(rulesDir) {
+ var newRules = loadRules(rulesDir);
+ Object.keys(newRules).forEach(function(ruleId) {
+ define(ruleId, newRules[ruleId]);
+ });
+}
+
+exports.load = load;
+
+/**
+ * Registers all given rules of a plugin.
+ * @param {Object} pluginRules A key/value map of rule definitions.
+ * @param {String} pluginName The name of the plugin without prefix (`eslint-plugin-`).
+ * @returns {void}
+ */
+exports.import = function (pluginRules, pluginName) {
+ Object.keys(pluginRules).forEach(function (ruleId) {
+ var qualifiedRuleId = pluginName + "/" + ruleId,
+ rule = pluginRules[ruleId];
+
+ define(qualifiedRuleId, rule);
+ });
+};
+
+/**
+ * Access rule handler by id (file name).
+ * @param {String} ruleId Rule id (file name).
+ * @returns {Function} Rule handler.
+ */
+exports.get = function(ruleId) {
+ return rules[ruleId];
+};
+
+/**
+ * Reset rules storage.
+ * Should be used only in tests.
+ * @returns {void}
+ */
+exports.testClear = function() {
+ rules = Object.create(null);
+};
+
+//------------------------------------------------------------------------------
+// Initialization
+//------------------------------------------------------------------------------
+
+// loads built-in rules
+load();
+
+},{"./load-rules":27}],30:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for "block scoped" variables by binding context
+ * @author Matt DuVall
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var scopeStack = [];
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Determines whether an identifier is in declaration position or is a non-declaration reference.
+ * @param {ASTNode} id The identifier.
+ * @param {ASTNode} parent The identifier's parent AST node.
+ * @returns {Boolean} true when the identifier is in declaration position.
+ */
+ function isDeclaration(id, parent) {
+ switch (parent.type) {
+ case "FunctionDeclaration":
+ case "FunctionExpression":
+ return parent.params.indexOf(id) > -1 || id === parent.id;
+
+ case "VariableDeclarator":
+ return id === parent.id;
+
+ case "CatchClause":
+ return id === parent.param;
+
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Determines whether an identifier is in property position.
+ * @param {ASTNode} id The identifier.
+ * @param {ASTNode} parent The identifier's parent AST node.
+ * @returns {Boolean} true when the identifier is in property position.
+ */
+ function isProperty(id, parent) {
+ switch (parent.type) {
+ case "MemberExpression":
+ return id === parent.property && !parent.computed;
+
+ case "Property":
+ return id === parent.key;
+
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Pushes a new scope object on the scope stack.
+ * @returns {void}
+ */
+ function pushScope() {
+ scopeStack.push([]);
+ }
+
+ /**
+ * Removes the topmost scope object from the scope stack.
+ * @returns {void}
+ */
+ function popScope() {
+ scopeStack.pop();
+ }
+
+ /**
+ * Declares the given names in the topmost scope object.
+ * @param {[String]} names A list of names to declare.
+ * @returns {void}
+ */
+ function declare(names) {
+ [].push.apply(scopeStack[scopeStack.length - 1], names);
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ function functionHandler(node) {
+ pushScope();
+ declare(node.params.map(function(id) {
+ return id.name;
+ }));
+ declare(node.id ? [node.id.name] : []);
+ declare(["arguments"]);
+ }
+
+ function variableDeclarationHandler(node) {
+ declare(node.declarations.map(function(decl) {
+ return decl.id.name;
+ }));
+ }
+
+ return {
+ "Program": function() {
+ scopeStack = [context.getScope().variables.map(function(v) {
+ return v.name;
+ })];
+ },
+
+ "BlockStatement": function(node) {
+ var statements = node.body;
+ pushScope();
+ statements.forEach(function(stmt) {
+ if (stmt.type === "VariableDeclaration") {
+ variableDeclarationHandler(stmt);
+ } else if (stmt.type === "FunctionDeclaration") {
+ declare([stmt.id.name]);
+ }
+ });
+ },
+
+ "VariableDeclaration": function (node) {
+ if (node.parent.type === "SwitchCase") {
+ variableDeclarationHandler(node);
+ }
+ },
+
+ "BlockStatement:exit": popScope,
+
+ "CatchClause": function(node) {
+ pushScope();
+ declare([node.param.name]);
+ },
+ "CatchClause:exit": popScope,
+
+ "FunctionDeclaration": functionHandler,
+ "FunctionDeclaration:exit": popScope,
+
+ "FunctionExpression": functionHandler,
+ "FunctionExpression:exit": popScope,
+
+ "ForStatement": function(node) {
+ pushScope();
+ if (node.init && node.init.type === "VariableDeclaration") {
+ variableDeclarationHandler(node.init);
+ }
+ },
+ "ForStatement:exit": popScope,
+
+ "ForInStatement": function(node) {
+ pushScope();
+ if (node.left.type === "VariableDeclaration") {
+ variableDeclarationHandler(node.left);
+ }
+ },
+ "ForInStatement:exit": popScope,
+
+ "Identifier": function(node) {
+ var ancestor = context.getAncestors().pop();
+ if (isDeclaration(node, ancestor) || isProperty(node, ancestor) || ancestor.type === "LabeledStatement") {
+ return;
+ }
+ for (var i = 0, l = scopeStack.length; i < l; i++) {
+ if (scopeStack[i].indexOf(node.name) > -1) {
+ return;
+ }
+ }
+
+ context.report(node, "\"" + node.name + "\" used outside of binding context.");
+ }
+ };
+
+};
+
+},{}],31:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag block statements that do not use the one true brace style
+ * @author Ian Christian Myers
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ var style = context.options[0] || "1tbs";
+ var params = context.options[1] || {};
+
+ var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.",
+ BODY_MESSAGE = "Statement inside of curly braces should be on next line.",
+ CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.",
+ CLOSE_MESSAGE_SINGLE = "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.",
+ CLOSE_MESSAGE_STROUSTRUP = "Closing curly brace appears on the same line as the subsequent block.";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Binds a list of properties to a function that verifies that the opening
+ * curly brace is on the same line as its controlling statement of a given
+ * node.
+ * @param {...string} The properties to check on the node.
+ * @returns {Function} A function that will perform the check on a node
+ */
+ function checkBlock() {
+ var blockProperties = arguments;
+ return function(node) {
+ [].forEach.call(blockProperties, function(blockProp) {
+ var block = node[blockProp], previousToken, curlyToken, curlyTokenEnd, curlyTokensOnSameLine;
+ block = node[blockProp];
+ if (block && block.type === "BlockStatement") {
+ previousToken = context.getTokenBefore(block);
+ curlyToken = context.getFirstToken(block);
+ curlyTokenEnd = context.getLastToken(block);
+ curlyTokensOnSameLine = curlyToken.loc.start.line === curlyTokenEnd.loc.start.line;
+
+ if (previousToken.loc.start.line !== curlyToken.loc.start.line) {
+ context.report(node, OPEN_MESSAGE);
+ } else if (block.body.length && params.allowSingleLine) {
+ if (curlyToken.loc.start.line === block.body[0].loc.start.line && !curlyTokensOnSameLine) {
+ context.report(block.body[0], BODY_MESSAGE);
+ } else if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line && !curlyTokensOnSameLine) {
+ context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE);
+ }
+ } else if (block.body.length && curlyToken.loc.start.line === block.body[0].loc.start.line) {
+ context.report(block.body[0], BODY_MESSAGE);
+ }
+ }
+ });
+ };
+ }
+
+ /**
+ * Enforces the configured brace style on IfStatements
+ * @param {ASTNode} node An IfStatement node.
+ * @returns {void}
+ */
+ function checkIfStatement(node) {
+ var tokens,
+ checkedTypes = ["BlockStatement", "IfStatement"];
+
+ checkBlock("consequent", "alternate")(node);
+
+ if (node.alternate && checkedTypes.indexOf(node.alternate.type) > -1) {
+ tokens = context.getTokensBefore(node.alternate, 2);
+ if (style === "1tbs") {
+ if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
+ context.report(node.alternate, CLOSE_MESSAGE);
+ }
+ } else if (style === "stroustrup") {
+ if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
+ context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP);
+ }
+ }
+ }
+ }
+
+ /**
+ * Enforces the configured brace style on TryStatements
+ * @param {ASTNode} node A TryStatement node.
+ * @returns {void}
+ */
+ function checkTryStatement(node) {
+ var tokens;
+
+ checkBlock("block", "finalizer")(node);
+
+ if (node.finalizer && node.finalizer.type === "BlockStatement") {
+ tokens = context.getTokensBefore(node.finalizer, 2);
+ if (style === "1tbs") {
+ if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
+ context.report(node.finalizer, CLOSE_MESSAGE);
+ }
+ } else if (style === "stroustrup") {
+ if (tokens[0].loc.start.line === tokens[1].loc.start.line) {
+ context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP);
+ }
+ }
+ }
+ }
+
+ /**
+ * Enforces the configured brace style on CatchClauses
+ * @param {ASTNode} node A CatchClause node.
+ * @returns {void}
+ */
+ function checkCatchClause(node) {
+ var previousToken = context.getTokenBefore(node),
+ firstToken = context.getFirstToken(node);
+
+ checkBlock("body")(node);
+
+ if (node.body && node.body.type === "BlockStatement") {
+ if (style === "1tbs") {
+ if (previousToken.loc.start.line !== firstToken.loc.start.line) {
+ context.report(node, CLOSE_MESSAGE);
+ }
+ } else if (style === "stroustrup") {
+ if (previousToken.loc.start.line === firstToken.loc.start.line) {
+ context.report(node, CLOSE_MESSAGE_STROUSTRUP);
+ }
+ }
+ }
+ }
+
+ /**
+ * Enforces the configured brace style on SwitchStatements
+ * @param {ASTNode} node A SwitchStatement node.
+ * @returns {void}
+ */
+ function checkSwitchStatement(node) {
+ var tokens;
+ if (node.cases && node.cases.length) {
+ tokens = context.getTokensBefore(node.cases[0], 2);
+ if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
+ context.report(node, OPEN_MESSAGE);
+ }
+ } else {
+ tokens = context.getLastTokens(node, 3);
+ if (tokens[0].loc.start.line !== tokens[1].loc.start.line) {
+ context.report(node, OPEN_MESSAGE);
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "FunctionDeclaration": checkBlock("body"),
+ "FunctionExpression": checkBlock("body"),
+ "IfStatement": checkIfStatement,
+ "TryStatement": checkTryStatement,
+ "CatchClause": checkCatchClause,
+ "DoWhileStatement": checkBlock("body"),
+ "WhileStatement": checkBlock("body"),
+ "WithStatement": checkBlock("body"),
+ "ForStatement": checkBlock("body"),
+ "ForInStatement": checkBlock("body"),
+ "SwitchStatement": checkSwitchStatement
+ };
+
+};
+
+},{}],32:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag non-camelcased identifiers
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Checks if a string contains an underscore and isn't all upper-case
+ * @param {String} name The string to check.
+ * @returns {boolean} if the string is underscored
+ * @private
+ */
+ function isUnderscored(name) {
+
+ // if there's an underscore, it might be A_CONSTANT, which is okay
+ return name.indexOf("_") > -1 && name !== name.toUpperCase();
+ }
+
+ /**
+ * Reports an AST node as a rule violation.
+ * @param {ASTNode} node The node to report.
+ * @returns {void}
+ * @private
+ */
+ function report(node) {
+ context.report(node, "Identifier '{{name}}' is not in camel case.", { name: node.name });
+ }
+
+ return {
+
+ "Identifier": function(node) {
+
+ // Leading and trailing underscores are commonly used to flag private/protected identifiers, strip them
+ var name = node.name.replace(/^_+|_+$/g, ""),
+ effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
+
+ // MemberExpressions get special rules
+ if (node.parent.type === "MemberExpression") {
+
+ // Always report underscored object names
+ if (node.parent.object.type === "Identifier" &&
+ node.parent.object.name === node.name &&
+ isUnderscored(name)) {
+ report(node);
+
+ // Report AssignmentExpressions only if they are the left side of the assignment
+ } else if (effectiveParent.type === "AssignmentExpression" &&
+ isUnderscored(name) &&
+ (effectiveParent.right.type !== "MemberExpression" ||
+ effectiveParent.left.type === "MemberExpression" &&
+ effectiveParent.left.property.name === node.name)) {
+ report(node);
+ }
+
+ // Report anything that is underscored that isn't a CallExpression
+ } else if (isUnderscored(name) && effectiveParent.type !== "CallExpression") {
+ report(node);
+ }
+ }
+ };
+
+};
+
+},{}],33:[function(require,module,exports){
+/**
+ * @fileoverview Comma spacing - validates spacing before and after comma
+ * @author Vignesh Anand aka vegetableman.
+ * @copyright 2014 Vignesh Anand. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ var options = {
+ before: context.options[0] ? !!context.options[0].before : false,
+ after: context.options[0] ? !!context.options[0].after : true
+ };
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Determines whether two adjacent tokens have whitespace between them.
+ * @param {Object} left - The left token object.
+ * @param {Object} right - The right token object.
+ * @returns {boolean} Whether or not there is space between the tokens.
+ */
+ function isSpaced(left, right) {
+ var punctuationLength = context.getTokensBetween(left, right).length; // the length of any parenthesis
+ return (left.range[1] + punctuationLength) < right.range[0];
+ }
+
+ /**
+ * Checks whether two tokens are on the same line.
+ * @param {ASTNode} left The leftmost token.
+ * @param {ASTNode} right The rightmost token.
+ * @returns {boolean} True if the tokens are on the same line, false if not.
+ * @private
+ */
+ function isSameLine(left, right) {
+ return left.loc.end.line === right.loc.start.line;
+ }
+
+ /**
+ * Determines if a given token is a comma operator.
+ * @param {ASTNode} token The token to check.
+ * @returns {boolean} True if the token is a comma, false if not.
+ * @private
+ */
+ function isComma(token) {
+ return !!token && (token.type === "Punctuator") && (token.value === ",");
+ }
+
+ /**
+ * Reports a spacing error with an appropriate message.
+ * @param {ASTNode} node The binary expression node to report.
+ * @param {string} dir Is the error "before" or "after" the comma?
+ * @returns {void}
+ * @private
+ */
+ function report(node, dir) {
+ context.report(node, options[dir] ?
+ "A space is required " + dir + " ','." :
+ "There should be no space " + dir + " ','.");
+ }
+
+ /**
+ * Validates the spacing around single items in lists.
+ * @param {Token} previousItemToken The last token from the previous item.
+ * @param {Token} commaToken The token representing the comma.
+ * @param {Token} currentItemToken The first token of the current item.
+ * @param {Token} reportItem The item to use when reporting an error.
+ * @returns {void}
+ * @private
+ */
+ function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
+ if (isSameLine(previousItemToken, commaToken) &&
+ isSameLine(commaToken, currentItemToken)) {
+
+ if (options.before !== isSpaced(previousItemToken, commaToken)) {
+ report(reportItem, "before");
+ }
+ if (options.after !== isSpaced(commaToken, currentItemToken)) {
+ report(reportItem, "after");
+ }
+ }
+ }
+
+ /**
+ * Validates the spacing before and after commas.
+ * @param {ASTNode} node The binary expression node to check.
+ * @param {string} property The property of the node.
+ * @returns {void}
+ * @private
+ */
+ function validateCommaSpacing(node, property) {
+ var items = node[property],
+ previousItemToken,
+ arrayLiteral = (node.type === "ArrayExpression");
+
+ if (items && (items.length > 1 || arrayLiteral)) {
+
+ // seed as opening [
+ previousItemToken = context.getFirstToken(node);
+
+ items.forEach(function(item) {
+ var commaToken = item ? context.getTokenBefore(item) : previousItemToken,
+ currentItemToken = item ? context.getFirstToken(item) : context.getTokenAfter(commaToken),
+ reportItem = item || currentItemToken;
+
+ /*
+ * This works by comparing three token locations:
+ * - previousItemToken is the last token of the previous item
+ * - commaToken is the location of the comma before the current item
+ * - currentItemToken is the first token of the current item
+ *
+ * These values get switched around if item is undefined.
+ * previousItemToken will refer to the last token not belonging
+ * to the current item, which could be a comma or an opening
+ * square bracket. currentItemToken could be a comma.
+ *
+ * All comparisons are done based on these tokens directly, so
+ * they are always valid regardless of an undefined item.
+ */
+ if (isComma(commaToken)) {
+ validateCommaItemSpacing(previousItemToken, commaToken,
+ currentItemToken, reportItem);
+ }
+
+ previousItemToken = item ? context.getLastToken(item) : previousItemToken;
+ });
+
+ /*
+ * Special case for array literals that have empty last items, such
+ * as [ 1, 2, ]. These arrays only have two items show up in the
+ * AST, so we need to look at the token to verify that there's no
+ * dangling comma.
+ */
+ if (arrayLiteral) {
+
+ var lastToken = context.getLastToken(node),
+ nextToLastToken = context.getTokenBefore(lastToken);
+
+ if (isComma(nextToLastToken)) {
+ validateCommaItemSpacing(
+ context.getTokenBefore(nextToLastToken),
+ nextToLastToken,
+ lastToken,
+ lastToken
+ );
+ }
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "VariableDeclaration": function(node) {
+ validateCommaSpacing(node, "declarations");
+ },
+ "ObjectExpression": function(node) {
+ validateCommaSpacing(node, "properties");
+ },
+ "ArrayExpression": function(node) {
+ validateCommaSpacing(node, "elements");
+ },
+ "SequenceExpression": function(node) {
+ validateCommaSpacing(node, "expressions");
+ },
+ "FunctionExpression": function(node) {
+ validateCommaSpacing(node, "params");
+ },
+ "FunctionDeclaration": function(node) {
+ validateCommaSpacing(node, "params");
+ },
+ "CallExpression": function(node) {
+ validateCommaSpacing(node, "arguments");
+ },
+ "NewExpression": function(node) {
+ validateCommaSpacing(node, "arguments");
+ }
+ };
+
+};
+
+},{}],34:[function(require,module,exports){
+/**
+ * @fileoverview Comma style - enforces comma styles of two types: last and first
+ * @author Vignesh Anand aka vegetableman
+ * @copyright 2014 Vignesh Anand. All rights reserved.
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var style = context.options[0] || "last";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Checks whether two tokens are on the same line.
+ * @param {ASTNode} left The leftmost token.
+ * @param {ASTNode} right The rightmost token.
+ * @returns {boolean} True if the tokens are on the same line, false if not.
+ * @private
+ */
+ function isSameLine(left, right) {
+ return left.loc.end.line === right.loc.start.line;
+ }
+
+ /**
+ * Determines if a given token is a comma operator.
+ * @param {ASTNode} token The token to check.
+ * @returns {boolean} True if the token is a comma, false if not.
+ * @private
+ */
+ function isComma(token) {
+ return !!token && (token.type === "Punctuator") && (token.value === ",");
+ }
+
+ /**
+ * Validates the spacing around single items in lists.
+ * @param {Token} previousItemToken The last token from the previous item.
+ * @param {Token} commaToken The token representing the comma.
+ * @param {Token} currentItemToken The first token of the current item.
+ * @param {Token} reportItem The item to use when reporting an error.
+ * @returns {void}
+ * @private
+ */
+ function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
+
+ // if single line
+ if (isSameLine(commaToken, currentItemToken) &&
+ isSameLine(previousItemToken, commaToken)) {
+
+ return;
+
+ } else if (!isSameLine(commaToken, currentItemToken) &&
+ !isSameLine(previousItemToken, commaToken)) {
+
+ // lone comma
+ context.report(reportItem, {
+ line: commaToken.loc.end.line,
+ column: commaToken.loc.start.column
+ }, "Bad line breaking before and after ','.");
+
+ } else if (style === "first" && !isSameLine(commaToken, currentItemToken)) {
+
+ context.report(reportItem, "',' should be placed first.");
+
+ } else if (style === "last" && isSameLine(commaToken, currentItemToken)) {
+
+ context.report(reportItem, {
+ line: commaToken.loc.end.line,
+ column: commaToken.loc.end.column
+ }, "',' should be placed last.");
+ }
+ }
+
+ /**
+ * Checks the comma placement with regards to a declaration/property/element
+ * @param {ASTNode} node The binary expression node to check
+ * @param {string} property The property of the node containing child nodes.
+ * @private
+ * @returns {void}
+ */
+ function validateComma(node, property) {
+ var items = node[property],
+ arrayLiteral = (node.type === "ArrayExpression"),
+ previousItemToken;
+
+ if (items.length > 1 || arrayLiteral) {
+
+ // seed as opening [
+ previousItemToken = context.getFirstToken(node);
+
+ items.forEach(function(item) {
+ var commaToken = item ? context.getTokenBefore(item) : previousItemToken,
+ currentItemToken = item ? context.getFirstToken(item) : context.getTokenAfter(commaToken),
+ reportItem = item || currentItemToken;
+
+ /*
+ * This works by comparing three token locations:
+ * - previousItemToken is the last token of the previous item
+ * - commaToken is the location of the comma before the current item
+ * - currentItemToken is the first token of the current item
+ *
+ * These values get switched around if item is undefined.
+ * previousItemToken will refer to the last token not belonging
+ * to the current item, which could be a comma or an opening
+ * square bracket. currentItemToken could be a comma.
+ *
+ * All comparisons are done based on these tokens directly, so
+ * they are always valid regardless of an undefined item.
+ */
+ if (isComma(commaToken)) {
+ validateCommaItemSpacing(previousItemToken, commaToken,
+ currentItemToken, reportItem);
+ }
+
+ previousItemToken = item ? context.getLastToken(item) : previousItemToken;
+ });
+
+ /*
+ * Special case for array literals that have empty last items, such
+ * as [ 1, 2, ]. These arrays only have two items show up in the
+ * AST, so we need to look at the token to verify that there's no
+ * dangling comma.
+ */
+ if (arrayLiteral) {
+
+ var lastToken = context.getLastToken(node),
+ nextToLastToken = context.getTokenBefore(lastToken);
+
+ if (isComma(nextToLastToken)) {
+ validateCommaItemSpacing(
+ context.getTokenBefore(nextToLastToken),
+ nextToLastToken,
+ lastToken,
+ lastToken
+ );
+ }
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "VariableDeclaration": function(node) {
+ validateComma(node, "declarations");
+ },
+ "ObjectExpression": function(node) {
+ validateComma(node, "properties");
+ },
+ "ArrayExpression": function(node) {
+ validateComma(node, "elements");
+ }
+ };
+
+};
+
+},{}],35:[function(require,module,exports){
+/**
+ * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity.
+ * Counts the number of if, conditional, for, whilte, try, switch/case,
+ * @author Patrick Brosset
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var THRESHOLD = context.options[0];
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ // Using a stack to store complexity (handling nested functions)
+ var fns = [];
+
+ // When parsing a new function, store it in our function stack
+ function startFunction() {
+ fns.push(1);
+ }
+
+ function endFunction(node) {
+ var complexity = fns.pop(), name = "anonymous";
+
+ if (node.id) {
+ name = node.id.name;
+ }
+ if (complexity > THRESHOLD) {
+ context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: complexity });
+ }
+ }
+
+ function increaseComplexity() {
+ if (fns.length) {
+ fns[fns.length - 1] ++;
+ }
+ }
+
+ function increaseSwitchComplexity(node) {
+ // Avoiding `default`
+ if (node.test) {
+ increaseComplexity(node);
+ }
+ }
+
+ function increaseLogicalComplexity(node) {
+ // Avoiding &&
+ if (node.operator === "||") {
+ increaseComplexity(node);
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression": startFunction,
+ "FunctionDeclaration:exit": endFunction,
+ "FunctionExpression:exit": endFunction,
+
+ "CatchClause": increaseComplexity,
+ "ConditionalExpression": increaseComplexity,
+ "LogicalExpression": increaseLogicalComplexity,
+ "ForStatement": increaseComplexity,
+ "ForInStatement": increaseComplexity,
+ "IfStatement": increaseComplexity,
+ "SwitchCase": increaseSwitchComplexity,
+ "WhileStatement": increaseComplexity,
+ "DoWhileStatement": increaseComplexity
+ };
+
+};
+
+},{}],36:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag consistent return values
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var functions = [];
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ function enterFunction() {
+ functions.push({});
+ }
+
+ function exitFunction() {
+ functions.pop();
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "FunctionDeclaration": enterFunction,
+ "FunctionExpression": enterFunction,
+ "FunctionDeclaration:exit": exitFunction,
+ "FunctionExpression:exit": exitFunction,
+
+ "ReturnStatement": function(node) {
+
+ var returnInfo = functions[functions.length - 1],
+ returnTypeDefined = "type" in returnInfo;
+
+ if (returnTypeDefined) {
+
+ if (returnInfo.type !== !!node.argument) {
+ context.report(node, "Expected " + (returnInfo.type ? "a" : "no") + " return value.");
+ }
+
+ } else {
+ returnInfo.type = !!node.argument;
+ }
+
+ }
+ };
+
+};
+
+},{}],37:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce consistent naming of "this" context variables
+ * @author Raphael Pigulla
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "VariableDeclaration": function(node) {
+ var alias = context.options[0];
+
+ node.declarations.forEach(function(declaration) {
+ if (declaration.id.name === alias &&
+ !(declaration.init && declaration.init.type === "ThisExpression")) {
+
+ context.report(
+ node,
+ "Designated 'this' alias '{{alias}}' is not assigned " +
+ "to the current execution context.",
+ { alias: declaration.id.name }
+ );
+ }
+
+ if (declaration.init &&
+ declaration.init.type === "ThisExpression" &&
+ declaration.id.name !== alias) {
+
+ context.report(
+ node,
+ "Unexpected alias '{{alias}}' for 'this'.",
+ { alias: declaration.id.name }
+ );
+ }
+ });
+ }
+ };
+
+};
+
+},{}],38:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag statements without curly braces
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var multiOnly = (context.options[0] === "multi");
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Checks the body of a node to see if it's a block statement. Depending on
+ * the rule options, reports the appropriate problems.
+ * @param {ASTNode} node The node to report if there's a problem.
+ * @param {ASTNode} body The body node to check for blocks.
+ * @param {string} name The name to report if there's a problem.
+ * @param {string} suffix Additional string to add to the end of a report.
+ * @returns {void}
+ */
+ function checkBody(node, body, name, suffix) {
+ var hasBlock = (body.type === "BlockStatement");
+
+ if (multiOnly) {
+ if (hasBlock && body.body.length === 1) {
+ context.report(node, "Unnecessary { after '{{name}}'{{suffix}}.",
+ {
+ name: name,
+ suffix: (suffix ? " " + suffix : "")
+ }
+ );
+ }
+ } else {
+ if (!hasBlock) {
+ context.report(node, "Expected { after '{{name}}'{{suffix}}.",
+ {
+ name: name,
+ suffix: (suffix ? " " + suffix : "")
+ }
+ );
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "IfStatement": function(node) {
+
+ checkBody(node, node.consequent, "if", "condition");
+
+ if (node.alternate && node.alternate.type !== "IfStatement") {
+ checkBody(node, node.alternate, "else");
+ }
+
+ },
+
+ "WhileStatement": function(node) {
+ checkBody(node, node.body, "while", "condition");
+ },
+
+ "DoWhileStatement": function (node) {
+ checkBody(node, node.body, "do");
+ },
+
+ "ForStatement": function(node) {
+ checkBody(node, node.body, "for", "condition");
+ }
+ };
+
+};
+
+},{}],39:[function(require,module,exports){
+/**
+ * @fileoverview require default case in switch statements
+ * @author Aliaksei Shytkin
+ */
+"use strict";
+
+var COMMENT_VALUE = "no default";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Shortcut to get last element of array
+ * @param {*[]} collection Array
+ * @returns {*} Last element
+ */
+ function last(collection) {
+ return collection[collection.length - 1];
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "SwitchStatement": function(node) {
+
+ if (!node.cases.length) {
+ // skip check of empty switch because there is no easy way
+ // to extract comments inside it now
+ return;
+ }
+
+ var hasDefault = node.cases.some(function(v) {
+ return v.test === null;
+ });
+
+ if (!hasDefault) {
+
+ var comment;
+ var comments;
+
+ var lastCase = last(node.cases);
+ comments = context.getComments(lastCase).trailing;
+
+ if (comments.length) {
+ comment = last(comments);
+ }
+
+ if (!comment || comment.value.trim() !== COMMENT_VALUE) {
+ context.report(node, "Expected a default case.");
+ }
+ }
+ }
+ };
+};
+
+},{}],40:[function(require,module,exports){
+/**
+ * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
+ * @author Josh Perez
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+var validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
+var keywords = [
+ "this",
+ "function",
+ "if",
+ "return",
+ "var",
+ "else",
+ "for",
+ "new",
+ "arguments",
+ "in",
+ "typeof",
+ "while",
+ "case",
+ "break",
+ "try",
+ "catch",
+ "delete",
+ "throw",
+ "switch",
+ "continue",
+ "default",
+ "instanceof",
+ "do",
+ "void",
+ "finally",
+ "with",
+ "debugger",
+ "eval",
+ "implements",
+ "interface",
+ "package",
+ "private",
+ "protected",
+ "public",
+ "static",
+ "yield",
+ "let",
+ "class",
+ "enum",
+ "export",
+ "extends",
+ "import",
+ "super",
+ "true",
+ "false",
+ "null",
+ "abstract",
+ "boolean",
+ "byte",
+ "char",
+ "const",
+ "double",
+ "final",
+ "float",
+ "goto",
+ "int",
+ "long",
+ "native",
+ "short",
+ "synchronized",
+ "throws",
+ "transient",
+ "volatile"
+];
+
+module.exports = function(context) {
+ var options = context.options[0] || {};
+ var allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords;
+
+ return {
+ "MemberExpression": function(node) {
+ if (
+ node.computed &&
+ node.property.type === "Literal" &&
+ validIdentifier.test(node.property.value) &&
+ (allowKeywords || keywords.indexOf("" + node.property.value) === -1)
+ ) {
+ context.report(node, "[" + JSON.stringify(node.property.value) + "] is better written in dot notation.");
+ }
+ if (
+ !allowKeywords &&
+ !node.computed &&
+ keywords.indexOf("" + node.property.name) !== -1
+ ) {
+ context.report(node, "." + node.property.name + " is a syntax error.");
+ }
+ }
+ };
+};
+
+},{}],41:[function(require,module,exports){
+/**
+ * @fileoverview Require file to end with single newline.
+ * @author Nodeca Team
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Program": function checkBadEOF(node) {
+ // Get the whole source code, not for node only.
+ var src = context.getSource(), location = {column: 1};
+
+ if (src.length === 0) {
+ return;
+ }
+
+ if (src[src.length - 1] !== "\n") {
+ // file is not newline-terminated
+ location.line = src.split(/\n/g).length;
+ context.report(node, location, "Newline required at end of file but not found.");
+ } else if (/\n\s*\n$/.test(src)) {
+ // last line is empty
+ location.line = src.split(/\n/g).length - 1;
+ context.report(node, location, "Unexpected blank line at end of file.");
+ }
+ }
+
+ };
+
+};
+
+},{}],42:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag statements that use != and == instead of !== and ===
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ /**
+ * Checks if an expression is a typeof expression
+ * @param {ASTNode} node The node to check
+ * @returns {boolean} if the node is a typeof expression
+ */
+ function isTypeOf(node) {
+ return node.type === "UnaryExpression" && node.operator === "typeof";
+ }
+
+ /**
+ * Checks if either operand of a binary expression is a typeof operation
+ * @param {ASTNode} node The node to check
+ * @returns {boolean} if one of the operands is typeof
+ * @private
+ */
+ function isTypeOfBinary(node) {
+ return isTypeOf(node.left) || isTypeOf(node.right);
+ }
+
+ /**
+ * Checks if operands are literals of the same type (via typeof)
+ * @param {ASTNode} node The node to check
+ * @returns {boolean} if operands are of same type
+ * @private
+ */
+ function areLiteralsAndSameType(node) {
+ return node.left.type === "Literal" && node.right.type === "Literal" &&
+ typeof node.left.value === typeof node.right.value;
+ }
+
+ /**
+ * Checks if one of the operands is a literal null
+ * @param {ASTNode} node The node to check
+ * @returns {boolean} if operands are null
+ * @private
+ */
+ function isNullCheck(node) {
+ return (node.right.type === "Literal" && node.right.value === null) ||
+ (node.left.type === "Literal" && node.left.value === null);
+ }
+
+ /**
+ * Gets the location (line and column) of the binary expression's operator
+ * @param {ASTNode} node The binary expression node to check
+ * @param {String} operator The operator to find
+ * @returns {Object} { line, column } location of operator
+ * @private
+ */
+ function getOperatorLocation(node) {
+ var opToken = context.getTokenAfter(node.left);
+ return {line: opToken.loc.start.line, column: opToken.loc.start.column};
+ }
+
+ return {
+ "BinaryExpression": function(node) {
+ if (node.operator !== "==" && node.operator !== "!=") {
+ return;
+ }
+
+ if (context.options[0] === "smart" && (isTypeOfBinary(node) ||
+ areLiteralsAndSameType(node)) || isNullCheck(node)) {
+ return;
+ }
+
+ if (context.options[0] === "allow-null" && isNullCheck(node)) {
+ return;
+ }
+
+ context.report(
+ node, getOperatorLocation(node),
+ "Expected '{{op}}=' and instead saw '{{op}}'.",
+ {op: node.operator}
+ );
+ }
+ };
+
+};
+
+},{}],43:[function(require,module,exports){
+/**
+ * @fileoverview Rule to warn when a function expression does not have a name.
+ * @author Kyle T. Nunery
+ */
+ "use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ return {
+ "FunctionExpression": function(node) {
+
+ var name = node.id && node.id.name;
+
+ if (!name) {
+ context.report(node, "Missing function expression name.");
+ }
+ }
+ };
+};
+
+},{}],44:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce a particular function style
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var style = context.options[0],
+ enforceDeclarations = (style === "declaration");
+
+ return {
+
+ "FunctionDeclaration": function(node) {
+ if (!enforceDeclarations) {
+ context.report(node, "Expected a function expression.");
+ }
+ },
+
+ "FunctionExpression": function() {
+ var parent = context.getAncestors().pop();
+
+ if (enforceDeclarations && parent.type === "VariableDeclarator") {
+ context.report(parent, "Expected a function declaration.");
+ }
+ }
+ };
+
+};
+
+},{}],45:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for the position of the * in your generator functions
+ * @author Jamund Ferguson
+ * @copyright 2014 Jamund Ferguson. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var position = context.options[0] || "end";
+
+ /**
+ * Check the position of the start compared to the expected position.
+ * @param {Object} node - the entire function node
+ * @param {Object} starToken - the star token
+ * @returns {void}
+ */
+ function checkStarPosition(node, starToken) {
+
+ if (!node.generator) {
+ return;
+ }
+
+ // check for function *name() {}
+ if (position === "end") {
+
+ // * starts where the next identifier begins
+ if (starToken.range[1] !== context.getTokenAfter(starToken).range[0]) {
+ context.report(node, "Expected a space before *.");
+ }
+ }
+
+ // check for function* name() {}
+ if (position === "start") {
+
+ // * ends where the previous identifier ends
+ if (starToken.range[0] !== context.getTokenBefore(starToken).range[1]) {
+ context.report(node, "Expected no space before *.");
+ }
+ }
+ }
+
+ return {
+
+ "FunctionDeclaration": function (node) {
+ var starToken = context.getTokenBefore(node.id);
+ checkStarPosition(node, starToken);
+ },
+
+ "FunctionExpression": function (node) {
+
+ // count back an extra token if you have a named anonymous function
+ var starToken = context.getTokenBefore(node.body, node.id ? 3 : 2);
+ checkStarPosition(node, starToken);
+ }
+ };
+
+};
+
+},{}],46:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag or require global strict mode.
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var mode = context.options[0];
+
+ if (mode === "always") {
+
+ return {
+ "Program": function(node) {
+ if (node.body.length > 0) {
+ var statement = node.body[0];
+
+ if (!(statement.type === "ExpressionStatement" && statement.expression.value === "use strict")) {
+ context.report(node, "Use the global form of \"use strict\".");
+ }
+ }
+ }
+ };
+
+ } else { // mode = "never"
+
+ return {
+ "ExpressionStatement": function(node) {
+ var parent = context.getAncestors().pop();
+
+ if (node.expression.value === "use strict" && parent.type === "Program") {
+ context.report(node, "Use the function form of \"use strict\".");
+ }
+ }
+ };
+
+ }
+
+};
+
+},{}],47:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag for-in loops without if statements inside
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "ForInStatement": function(node) {
+
+ /*
+ * If the for-in statement has {}, then the real body is the body
+ * of the BlockStatement. Otherwise, just use body as provided.
+ */
+ var body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body;
+
+ if (body && body.type !== "IfStatement") {
+ context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.");
+ }
+ }
+ };
+
+};
+
+},{}],48:[function(require,module,exports){
+/**
+ * @fileoverview Ensure handling of errors when we know they exist.
+ * @author Jamund Ferguson
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var errorArgument = context.options[0] || "err";
+ var callbacks = [];
+ var scopes = 0;
+
+ /**
+ * Checks if the given argument should be interpreted as a regexp pattern.
+ * @param {string} stringToCheck The string which should be checked.
+ * @returns {boolean} Whether or not the string should be interpreted as a pattern.
+ */
+ function isPattern(stringToCheck) {
+ var firstChar = stringToCheck[0];
+ return firstChar === "^";
+ }
+
+ /**
+ * Checks if the given name matches the configured error argument.
+ * @param {string} name The name which should be compared.
+ * @returns {boolean} Whether or not the given name matches the configured error variable name.
+ */
+ function matchesConfiguredErrorName(name) {
+ if (isPattern(errorArgument)) {
+ var regexp = new RegExp(errorArgument);
+ return regexp.test(name);
+ }
+ return name === errorArgument;
+ }
+
+ /**
+ * Check the arguments to see if we need to start tracking the error object.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {void}
+ */
+ function startFunction(node) {
+
+ // keep track of nested scopes
+ scopes++;
+
+ // check if the first argument matches our argument name
+ var firstArg = node.params && node.params[0];
+ if (firstArg && matchesConfiguredErrorName(firstArg.name)) {
+ callbacks.push({handled: false, depth: scopes, errorVariableName: firstArg.name});
+ }
+ }
+
+ /**
+ * At the end of a function check to see if the error was handled.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {void}
+ */
+ function endFunction(node) {
+
+ var callback = callbacks[callbacks.length - 1] || {};
+
+ // check if a callback is ending, if so pop it off the stack
+ if (callback.depth === scopes) {
+ callbacks.pop();
+
+ // check if there were no handled errors since the last callback
+ if (!callback.handled) {
+ context.report(node, "Expected error to be handled.");
+ }
+ }
+
+ // less nested functions
+ scopes--;
+
+ }
+
+ /**
+ * Check to see if we're handling the error object properly.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {void}
+ */
+ function checkForError(node) {
+ if (callbacks.length > 0) {
+ var callback = callbacks[callbacks.length - 1] || {};
+
+ // make sure the node's name matches our error argument name
+ var isAboutError = node.name === callback.errorVariableName;
+
+ // we don't consider these use cases as "handling" the error
+ var doNotCount = ["FunctionDeclaration", "FunctionExpression", "CatchClause"];
+
+ // make sure this identifier isn't used as part of one of them
+ var isHandled = doNotCount.indexOf(node.parent.type) === -1;
+
+ if (isAboutError && isHandled) {
+ // record that this callback handled its error
+ callback.handled = true;
+ }
+ }
+ }
+
+ return {
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression": startFunction,
+ "Identifier": checkForError,
+ "FunctionDeclaration:exit": endFunction,
+ "FunctionExpression:exit": endFunction
+ };
+
+};
+
+},{}],49:[function(require,module,exports){
+/**
+ * @fileoverview Rule to specify spacing of object literal keys and values
+ * @author Brandon Mills
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/**
+ * Checks whether a string contains a line terminator as defined in
+ * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3
+ * @param {string} str String to test.
+ * @returns {boolean} True if str contains a line terminator.
+ */
+function containsLineTerminator(str) {
+ return /[\n\r\u2028\u2029]/.test(str);
+}
+
+/**
+ * Gets an object literal property's key as the identifier name or string value.
+ * @param {ASTNode} property Property node whose key to retrieve.
+ * @returns {string} The property's key.
+ */
+function getKey(property) {
+ return property.key.name || property.key.value;
+}
+
+/**
+ * Gets the number of characters in a key, including quotes around string keys.
+ * @param {ASTNode} property Property of on object literal.
+ * @returns {int} Width of the key, including string quotes where present.
+ */
+function getKeyWidth(property) {
+ var key = property.key;
+ return (key.type === "Identifier" ? key.name : key.raw).length;
+}
+
+/**
+ * Gets the last element of an array.
+ * @param {Array} arr An array.
+ * @returns {any} Last element of arr.
+ */
+function last(arr) {
+ return arr[arr.length - 1];
+}
+
+/**
+ * Checks whether a property is a member of the property group it follows.
+ * @param {ASTNode} lastMember The last Property known to be in the group.
+ * @param {ASTNode} candidate The next Property that might be in the group.
+ * @returns {boolean} True if the candidate property is part of the group.
+ */
+function continuesPropertyGroup(lastMember, candidate) {
+ var groupEndLine = lastMember.loc.end.line,
+ candidateStartLine = candidate.loc.start.line,
+ comments, i;
+
+ if (candidateStartLine - groupEndLine <= 1) {
+ return true;
+ }
+
+ // Check that the first comment is adjacent to the end of the group, the
+ // last comment is adjacent to the candidate property, and that successive
+ // comments are adjacent to each other.
+ comments = candidate.leadingComments;
+ if (
+ comments &&
+ comments[0].loc.start.line - groupEndLine <= 1 &&
+ candidateStartLine - last(comments).loc.end.line <= 1
+ ) {
+ for (i = 1; i < comments.length; i++) {
+ if (comments[i].loc.start.line - comments[i - 1].loc.end.line > 1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ return false;
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+var messages = {
+ key: "{{error}} space after key \"{{key}}\".",
+ value: "{{error}} space before value for key \"{{key}}\"."
+};
+
+module.exports = function(context) {
+
+ /**
+ * OPTIONS
+ * "key-spacing": [2, {
+ * beforeColon: false,
+ * afterColon: true,
+ * align: "colon" // Optional, or "value"
+ * }
+ */
+
+ var options = context.options[0] || {},
+ align = options.align,
+ beforeColon = +!!options.beforeColon, // Defaults to false
+ afterColon = +!(options.afterColon === false); // Defaults to true
+
+ /**
+ * Gets the whitespace around the colon in an object literal property.
+ * @param {ASTNode} property Property node from an object literal.
+ * @returns {Object} Whitespace before and after the property's colon.
+ */
+ function getPropertyWhitespace(property) {
+ var whitespace = /^(\s*):(\s*)/.exec(context.getSource().slice(
+ property.key.range[1], property.value.range[0]
+ ));
+
+ if (whitespace) {
+ return {
+ beforeColon: whitespace[1],
+ afterColon: whitespace[2]
+ };
+ }
+ }
+
+ /**
+ * Reports an appropriately-formatted error if spacing is incorrect on one
+ * side of the colon.
+ * @param {ASTNode} property Key-value pair in an object literal.
+ * @param {string} side Side being verified - either "key" or "value".
+ * @param {string} whitespace Actual whitespace string.
+ * @param {int} expected Expected whitespace length.
+ * @returns {void}
+ */
+ function report(property, side, whitespace, expected) {
+ var diff = whitespace.length - expected,
+ key = property.key,
+ firstTokenAfterColon = context.getTokenAfter(key, 1),
+ location = side === "key" ? key.loc.start : firstTokenAfterColon.loc.start;
+
+ if (diff && !(expected && containsLineTerminator(whitespace))) {
+ context.report(property[side], location, messages[side], {
+ error: diff > 0 ? "Extra" : "Missing",
+ key: getKey(property)
+ });
+ }
+ }
+
+ /**
+ * Verifies correct vertical alignment of a group of properties.
+ * @param {ASTNode[]} properties List of Property AST nodes.
+ * @returns {void}
+ */
+ function verifyAlignment(properties) {
+ var length = properties.length,
+ widths = properties.map(getKeyWidth), // Width of keys, including quotes
+ targetWidth = Math.max.apply(null, widths),
+ i, property, whitespace, width;
+
+ // Conditionally include one space before or after colon
+ targetWidth += (align === "colon" ? beforeColon : afterColon);
+
+ for (i = 0; i < length; i++) {
+ property = properties[i];
+ whitespace = getPropertyWhitespace(property);
+
+ if (!whitespace) {
+ continue; // Object literal getters/setters lack a colon
+ }
+
+ width = widths[i];
+
+ if (align === "value") {
+ report(property, "key", whitespace.beforeColon, beforeColon);
+ report(property, "value", whitespace.afterColon, targetWidth - width);
+ } else { // align = "colon"
+ report(property, "key", whitespace.beforeColon, targetWidth - width);
+ report(property, "value", whitespace.afterColon, afterColon);
+ }
+ }
+ }
+
+ if (align) { // Verify vertical alignment
+
+ return {
+ "ObjectExpression": function(node) {
+ node.properties.reduce(function(groups, property) {
+ var currentGroup = last(groups),
+ prev = last(currentGroup);
+
+ if (!prev || continuesPropertyGroup(prev, property)) {
+ currentGroup.push(property);
+ } else {
+ groups.push([property]);
+ }
+
+ return groups;
+ }, [[]]).forEach(function(group) {
+ verifyAlignment(group);
+ });
+ }
+ };
+
+ } else { // Strictly obey beforeColon and afterColon in each property
+
+ return {
+ "Property": function (node) {
+ var whitespace = getPropertyWhitespace(node);
+ if (whitespace) { // Object literal getters/setters lack colons
+ report(node, "key", whitespace.beforeColon, beforeColon);
+ report(node, "value", whitespace.afterColon, afterColon);
+ }
+ }
+ };
+
+ }
+
+};
+
+},{}],50:[function(require,module,exports){
+/**
+ * @fileoverview A rule to set the maximum depth block can be nested in a function.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ var functionStack = [],
+ maxDepth = context.options[0] || 4;
+
+ function startFunction() {
+ functionStack.push(0);
+ }
+
+ function endFunction() {
+ functionStack.pop();
+ }
+
+ function pushBlock(node) {
+ var len = ++functionStack[functionStack.length - 1];
+
+ if (len > maxDepth) {
+ context.report(node, "Blocks are nested too deeply ({{depth}}).",
+ { depth: len });
+ }
+ }
+
+ function popBlock() {
+ functionStack[functionStack.length - 1]--;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "Program": startFunction,
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression": startFunction,
+
+ "IfStatement": pushBlock,
+ "SwitchStatement": pushBlock,
+ "TryStatement": pushBlock,
+ "DoWhileStatement": pushBlock,
+ "WhileStatement": pushBlock,
+ "WithStatement": pushBlock,
+ "ForStatement": pushBlock,
+ "ForInStatement": pushBlock,
+
+ "IfStatement:exit": popBlock,
+ "SwitchStatement:exit": popBlock,
+ "TryStatement:exit": popBlock,
+ "DoWhileStatement:exit": popBlock,
+ "WhileStatement:exit": popBlock,
+ "WithStatement:exit": popBlock,
+ "ForStatement:exit": popBlock,
+ "ForInStatement:exit": popBlock,
+
+ "FunctionDeclaration:exit": endFunction,
+ "FunctionExpression:exit": endFunction,
+ "Program:exit": endFunction
+ };
+
+};
+
+},{}],51:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for max length on a line.
+ * @author Matt DuVall
+ * @copyright 2013 Matt DuVall. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ /**
+ * Creates a string that is made up of repeating a given string a certain
+ * number of times. This uses exponentiation of squares to achieve significant
+ * performance gains over the more traditional implementation of such
+ * functionality.
+ * @param {string} str The string to repeat.
+ * @param {int} num The number of times to repeat the string.
+ * @returns {string} The created string.
+ * @private
+ */
+ function stringRepeat(str, num) {
+ var result = "";
+ for (num |= 0; num > 0; num >>>= 1, str += str) {
+ if (num & 1) {
+ result += str;
+ }
+ }
+ return result;
+ }
+
+ var tabWidth = context.options[1];
+
+ var maxLength = context.options[0],
+ tabString = stringRepeat(" ", tabWidth);
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+ function checkProgramForMaxLength(node) {
+ var lines = context.getSourceLines();
+
+ // Replace the tabs
+ // Split (honors line-ending)
+ // Iterate
+ lines.forEach(function(line, i) {
+ if (line.replace(/\t/g, tabString).length > maxLength) {
+ context.report(node, { line: i + 1, col: 1 }, "Line " + (i + 1) + " exceeds the maximum line length of " + maxLength + ".");
+ }
+ });
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "Program": checkProgramForMaxLength
+ };
+
+};
+
+},{}],52:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce a maximum number of nested callbacks.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Constants
+ //--------------------------------------------------------------------------
+
+ var THRESHOLD = context.options[0];
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ var callbackStack = [];
+
+ return {
+
+ "FunctionExpression": function (node) {
+ var parent = context.getAncestors().pop();
+
+ if (parent.type === "CallExpression") {
+ callbackStack.push(node);
+ }
+
+ if (callbackStack.length > THRESHOLD) {
+ var opts = {num: callbackStack.length, max: THRESHOLD};
+ context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts);
+ }
+ },
+
+
+ "FunctionExpression:exit": function() {
+ callbackStack.pop();
+ }
+
+ };
+
+};
+
+},{}],53:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when a function has too many parameters
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var numParams = context.options[0] || 3;
+
+ return {
+
+ "FunctionDeclaration": function(node) {
+ if (node.params.length > numParams) {
+ context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", {
+ count: node.params.length,
+ max: numParams
+ });
+ }
+ },
+
+ "FunctionExpression": function(node) {
+ if (node.params.length > numParams) {
+ context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", {
+ count: node.params.length,
+ max: numParams
+ });
+ }
+ }
+ };
+
+};
+
+},{}],54:[function(require,module,exports){
+/**
+ * @fileoverview A rule to set the maximum number of statements in a function.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ var functionStack = [],
+ maxStatements = context.options[0] || 10;
+
+ function startFunction() {
+ functionStack.push(0);
+ }
+
+ function endFunction(node) {
+ var count = functionStack.pop();
+
+ if (count > maxStatements) {
+ context.report(node, "This function has too many statements ({{count}}). Maximum allowed is {{max}}.",
+ { count: count, max: maxStatements });
+ }
+ }
+
+ function countStatements(node) {
+ functionStack[functionStack.length - 1] += node.body.length;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression": startFunction,
+
+ "BlockStatement": countStatements,
+
+ "FunctionDeclaration:exit": endFunction,
+ "FunctionExpression:exit": endFunction
+ };
+
+};
+
+},{}],55:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of constructors without capital letters
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Jordan Harband. All rights reserved.
+ * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved.
+ */
+
+"use strict";
+
+var CAPS_ALLOWED = [
+ "Object",
+ "Function",
+ "Number",
+ "String",
+ "Boolean",
+ "Date",
+ "Array",
+ "Symbol",
+ "RegExp"
+];
+
+/**
+ * Ensure that if the key is provided, it must be an array.
+ * @param {Object} obj Object to check with `key`.
+ * @param {string} key Object key to check on `obj`.
+ * @param {*} fallback If obj[key] is not present, this will be returned.
+ * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback`
+ */
+function checkArray(obj, key, fallback) {
+ if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
+ throw new TypeError(key + ", if provided, must be an Array");
+ }
+ return obj[key] || fallback;
+}
+
+/**
+ * A reducer function to invert an array to an Object mapping the string form of the key, to `true`.
+ * @param {Object} map Accumulator object for the reduce.
+ * @param {string} key Object key to set to `true`.
+ * @returns {Object} Returns the updated Object for further reduction.
+ */
+function invert(map, key) {
+ map[key] = true;
+ return map;
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var config = context.options[0] || {};
+ config.newIsCap = config.newIsCap === false ? false : true;
+ config.capIsNew = config.capIsNew === false ? false : true;
+
+ var newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
+
+ var capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED).reduce(invert, {});
+
+ var listeners = {};
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Get exact callee name from expression
+ * @param {ASTNode} node CallExpression or NewExpression node
+ * @returns {string} name
+ */
+ function extractNameFromExpression(node) {
+
+ var name = "",
+ property;
+
+ if (node.callee.type === "MemberExpression") {
+ property = node.callee.property;
+
+ if (property.type === "Literal" && (typeof property.value === "string")) {
+ name = property.value;
+ } else if (property.type === "Identifier" && !node.callee.computed) {
+ name = property.name;
+ }
+ } else {
+ name = node.callee.name;
+ }
+ return name;
+ }
+
+ /**
+ * Returns the capitalization state of the string -
+ * Whether the first character is uppercase, lowercase, or non-alphabetic
+ * @param {string} str String
+ * @returns {string} capitalization state: "non-alpha", "lower", or "upper"
+ */
+ function getCap(str) {
+ var firstChar = str.charAt(0);
+
+ var firstCharLower = firstChar.toLowerCase();
+ var firstCharUpper = firstChar.toUpperCase();
+
+ if (firstCharLower === firstCharUpper) {
+ // char has no uppercase variant, so it's non-alphabetic
+ return "non-alpha";
+ } else if (firstChar === firstCharLower) {
+ return "lower";
+ } else {
+ return "upper";
+ }
+ }
+
+ /**
+ * Check if capitalization is allowed for a CallExpression
+ * @param {Object} allowedMap Object mapping calleeName to a Boolean
+ * @param {ASTNode} node CallExpression node
+ * @param {string} calleeName Capitalized callee name from a CallExpression
+ * @returns {Boolean} Returns true if the callee may be capitalized
+ */
+ function isCapAllowed(allowedMap, node, calleeName) {
+ if (allowedMap[calleeName]) {
+ return true;
+ }
+ if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
+ // allow if callee is Date.UTC
+ return node.callee.object.type === "Identifier" &&
+ node.callee.object.name === "Date";
+ }
+ return false;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ if (config.newIsCap) {
+ listeners.NewExpression = function(node) {
+
+ var constructorName = extractNameFromExpression(node);
+ if (constructorName) {
+ var capitalization = getCap(constructorName);
+ var isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName);
+ if (!isAllowed) {
+ context.report(node, "A constructor name should not start with a lowercase letter.");
+ }
+ }
+ };
+ }
+
+ if (config.capIsNew) {
+ listeners.CallExpression = function(node) {
+
+ var calleeName = extractNameFromExpression(node);
+ if (calleeName) {
+ var capitalization = getCap(calleeName);
+ var isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName);
+ if (!isAllowed) {
+ context.report(node, "A function with a name starting with an uppercase letter should only be used as a constructor.");
+ }
+ }
+ };
+ }
+
+ return listeners;
+};
+
+},{}],56:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when using constructor without parentheses
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "NewExpression": function(node) {
+ var tokens = context.getTokens(node);
+ var prenticesTokens = tokens.filter(function(token) {
+ return token.value === "(" || token.value === ")";
+ });
+ if (prenticesTokens.length < 2) {
+ context.report(node, "Missing '()' invoking a constructor");
+ }
+ }
+ };
+
+};
+
+},{}],57:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of alert, confirm, prompt
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+function matchProhibited(name) {
+ return name.match(/^(alert|confirm|prompt)$/);
+}
+
+function report(context, node, result) {
+ context.report(node, "Unexpected {{name}}.", { name: result[1] });
+}
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "CallExpression": function(node) {
+
+ var result;
+
+ // without window.
+ if (node.callee.type === "Identifier") {
+
+ result = matchProhibited(node.callee.name);
+
+ if (result) {
+ report(context, node, result);
+ }
+
+ } else if (node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier") {
+
+ result = matchProhibited(node.callee.property.name);
+
+ if (result && node.callee.object.name === "window") {
+ report(context, node, result);
+ }
+
+ }
+
+ }
+ };
+
+};
+
+},{}],58:[function(require,module,exports){
+/**
+ * @fileoverview Disallow construction of dense arrays using the Array constructor
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ function check(node) {
+ if (
+ node.arguments.length !== 1 &&
+ node.callee.type === "Identifier" &&
+ node.callee.name === "Array"
+ ) {
+ context.report(node, "The array literal notation [] is preferrable.");
+ }
+ }
+
+ return {
+ "CallExpression": check,
+ "NewExpression": check
+ };
+
+};
+
+},{}],59:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag bitwise identifiers
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var BITWISE_OPERATORS = [
+ "^", "|", "&", "<<", ">>", ">>>",
+ "^=", "|=", "&=", "<<=", ">>=", ">>>=",
+ "~"
+ ];
+
+ /**
+ * Reports an unexpected use of a bitwise operator.
+ * @param {ASTNode} node Node which contains the bitwise operator.
+ * @returns {void}
+ */
+ function report(node) {
+ context.report(node, "Unexpected use of '{{operator}}'.", { operator: node.operator });
+ }
+
+ /**
+ * Checks if the given node has a bitwise operator.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} Whether or not the node has a bitwise operator.
+ */
+ function hasBitwiseOperator(node) {
+ return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
+ }
+
+ /**
+ * Report if the given node contains a bitwise operator.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ */
+ function checkNodeForBitwiseOperator(node) {
+ if (hasBitwiseOperator(node)) {
+ report(node);
+ }
+ }
+
+ return {
+ "AssignmentExpression": checkNodeForBitwiseOperator,
+ "BinaryExpression": checkNodeForBitwiseOperator,
+ "UnaryExpression": checkNodeForBitwiseOperator
+ };
+
+};
+
+},{}],60:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of arguments.callee and arguments.caller.
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "MemberExpression": function(node) {
+ var objectName = node.object.name,
+ propertyName = node.property.name;
+
+ if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) {
+ context.report(node, "Avoid arguments.{{property}}.", { property: propertyName });
+ }
+
+ }
+ };
+
+};
+
+},{}],61:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ function paramIsShadowing(scope, name) {
+ var found = scope.variables.some(function(variable) {
+ return variable.name === name;
+ });
+
+ if (found) {
+ return true;
+ }
+
+ if (scope.upper) {
+ return paramIsShadowing(scope.upper, name);
+ }
+
+ return false;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "CatchClause": function(node) {
+ var scope = context.getScope();
+
+ if (paramIsShadowing(scope, node.param.name)) {
+ context.report(node, "Value of '{{name}}' may be overwritten in IE 8 and earlier.",
+ { name: node.param.name });
+ }
+ }
+ };
+
+};
+
+},{}],62:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag trailing commas in object literals.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //-------------------------------------------------------------------------
+ // Helpers
+ //-------------------------------------------------------------------------
+
+ function checkForTrailingComma(node) {
+ var items = node.properties || node.elements,
+ length = items.length,
+ lastItem, penultimateToken;
+
+ if (length) {
+ lastItem = items[length - 1];
+ if (lastItem) {
+ penultimateToken = context.getLastToken(node, 1);
+ if (penultimateToken.value === ",") {
+ context.report(lastItem, penultimateToken.loc.start, "Trailing comma.");
+ }
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "ObjectExpression": checkForTrailingComma,
+ "ArrayExpression": checkForTrailingComma
+ };
+
+};
+
+},{}],63:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag assignment in a conditional statement's test expression
+ * @author Stephen Murray
+ */
+"use strict";
+
+var NODE_DESCRIPTIONS = {
+ "DoWhileStatement": "a 'do...while' statement",
+ "ForStatement": "a 'for' statement",
+ "IfStatement": "an 'if' statement",
+ "WhileStatement": "a 'while' statement"
+};
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var prohibitAssign = (context.options[0] || "except-parens");
+
+ /**
+ * Check whether an AST node is the test expression for a conditional statement.
+ * @param {!Object} node The node to test.
+ * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`.
+ */
+ function isConditionalTestExpression(node) {
+ return node.parent &&
+ node.parent.test &&
+ node === node.parent.test;
+ }
+
+ /**
+ * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement.
+ * @param {!Object} node The node to use at the start of the search.
+ * @returns {?Object} The closest ancestor node that represents a conditional statement.
+ */
+ function findConditionalAncestor(node) {
+ var currentAncestor = node;
+
+ while ((currentAncestor = currentAncestor.parent)) {
+ if (isConditionalTestExpression(currentAncestor)) {
+ return currentAncestor.parent;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Check whether the code represented by an AST node is enclosed in parentheses.
+ * @param {!Object} node The node to test.
+ * @returns {boolean} `true` if the code is enclosed in parentheses; otherwise, `false`.
+ */
+ function isParenthesised(node) {
+ var previousToken = context.getTokenBefore(node),
+ nextToken = context.getTokenAfter(node);
+
+ return previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ /**
+ * Check whether the code represented by an AST node is enclosed in two sets of parentheses.
+ * @param {!Object} node The node to test.
+ * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`.
+ */
+ function isParenthesisedTwice(node) {
+ var previousToken = context.getTokenBefore(node, 1),
+ nextToken = context.getTokenAfter(node, 1);
+
+ return isParenthesised(node) &&
+ previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ /**
+ * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses.
+ * @param {!Object} node The node for the conditional statement.
+ * @returns {void}
+ */
+ function testForAssign(node) {
+ if (node.test && (node.test.type === "AssignmentExpression") && !isParenthesisedTwice(node.test)) {
+ // must match JSHint's error message
+ context.report(node, "Expected a conditional expression and instead saw an assignment.");
+ }
+ }
+
+ /**
+ * Check whether an assignment expression is descended from a conditional statement's test expression.
+ * @param {!Object} node The node for the assignment expression.
+ * @returns {void}
+ */
+ function testForConditionalAncestor(node) {
+ var ancestor = findConditionalAncestor(node);
+
+ if (ancestor) {
+ context.report(ancestor, "Unexpected assignment within {{type}}.", {
+ type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type
+ });
+ }
+ }
+
+ if (prohibitAssign === "always") {
+ return {
+ "AssignmentExpression": testForConditionalAncestor
+ };
+ }
+
+ return {
+ "DoWhileStatement": testForAssign,
+ "ForStatement": testForAssign,
+ "IfStatement": testForAssign,
+ "WhileStatement": testForAssign
+ };
+
+};
+
+},{}],64:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of console object
+ * @author Nicholas C. Zakas
+ */
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "MemberExpression": function(node) {
+
+ if (node.object.name === "console") {
+ context.report(node, "Unexpected console statement.");
+ }
+
+ }
+ };
+
+};
+
+},{}],65:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use constant conditions
+ * @author Christian Schulz
+ */
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Checks if a node has a constant truthiness value.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {Bool} true when node's truthiness is constant
+ * @private
+ */
+ function isConstant(node) {
+ switch (node.type) {
+ case "Literal":
+ case "FunctionExpression":
+ case "ObjectExpression":
+ case "ArrayExpression":
+ return true;
+ case "UnaryExpression":
+ return isConstant(node.argument);
+ case "BinaryExpression":
+ case "LogicalExpression":
+ return isConstant(node.left) && isConstant(node.right);
+ case "AssignmentExpression":
+ return isConstant(node.right);
+ case "SequenceExpression":
+ return isConstant(node.expressions[node.expressions.length - 1]);
+ // no default
+ }
+ return false;
+ }
+
+ /**
+ * Reports when the given node contains a constant condition.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {void}
+ * @private
+ */
+ function checkConstantCondition(node) {
+ if (node.test && isConstant(node.test)) {
+ context.report(node, "Unexpected constant condition.");
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "ConditionalExpression": checkConstantCondition,
+ "IfStatement": checkConstantCondition,
+ "WhileStatement": checkConstantCondition,
+ "DoWhileStatement": checkConstantCondition,
+ "ForStatement": checkConstantCondition
+ };
+
+};
+
+},{}],66:[function(require,module,exports){
+/**
+ * @fileoverview Rule to forbid control charactes from regular expressions.
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+
+ function getRegExp(node) {
+
+ if (node.value instanceof RegExp) {
+ return node.value;
+ } else if (typeof node.value === "string") {
+
+ var parent = context.getAncestors().pop();
+ if ((parent.type === "NewExpression" || parent.type === "CallExpression") &&
+ parent.callee.type === "Identifier" && parent.callee.name === "RegExp") {
+
+ // there could be an invalid regular expression string
+ try {
+ return new RegExp(node.value);
+ } catch (ex) {
+ return null;
+ }
+
+ }
+ } else {
+ return null;
+ }
+
+ }
+
+
+
+ return {
+
+ "Literal": function(node) {
+
+ var computedValue,
+ regex = getRegExp(node);
+
+ if (regex) {
+ computedValue = regex.toString();
+ if (/[\x00-\x1f]/.test(computedValue)) {
+ context.report(node, "Unexpected control character in regular expression.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],67:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of a debugger statement
+ * @author Nicholas C. Zakas
+ */
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "DebuggerStatement": function(node) {
+ context.report(node, "Unexpected 'debugger' statement.");
+ }
+ };
+
+};
+
+},{}],68:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when deleting variables
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "UnaryExpression": function(node) {
+ if (node.operator === "delete" && node.argument.type === "Identifier") {
+ context.report(node, "Variables should not be deleted.");
+ }
+ }
+ };
+
+};
+
+},{}],69:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for ambiguous div operator in regexes
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ var token = context.getFirstToken(node);
+
+ if (token.type === "RegularExpression" && token.value[1] === "=") {
+ context.report(node, "A regular expression literal can be confused with '/='.");
+ }
+ }
+ };
+
+};
+
+},{}],70:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of duplicate keys in an object.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "ObjectExpression": function(node) {
+
+ // Object that will be a map of properties--safe because we will
+ // prefix all of the keys.
+ var nodeProps = {};
+
+ node.properties.forEach(function(property) {
+ var keyName = property.key.name || property.key.value;
+ var key = property.kind + "-" + keyName;
+
+ if (nodeProps[key]) {
+ context.report(node, "Duplicate key '{{key}}'.", { key: keyName });
+ } else {
+ nodeProps[key] = true;
+ }
+ });
+
+ }
+ };
+
+};
+
+},{}],71:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag `else` after a `return` in `if`
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Display the context report if rule is violated
+ *
+ * @param {Node} node The 'else' node
+ * @returns {void}
+ */
+ function displayReport(node) {
+ context.report(node, "Unexpected 'else' after 'return'.");
+ }
+
+ /**
+ * Check to see if the node is a ReturnStatement
+ *
+ * @param {Node} node The node being evaluated
+ * @returns {boolean} True if node is a return
+ */
+ function checkForReturn(node) {
+ return node.type === "ReturnStatement";
+ }
+
+ /**
+ * Naive return checking, does not iterate through the whole
+ * BlockStatement because we make the assumption that the ReturnStatement
+ * will be the last node in the body of the BlockStatement.
+ *
+ * @param {Node} node The consequent/alternate node
+ * @returns {boolean} True if it has a return
+ */
+ function naiveHasReturn(node) {
+ if (node.type === "BlockStatement") {
+ var body = node.body,
+ lastChildNode = body[body.length - 1];
+
+ return lastChildNode && checkForReturn(lastChildNode);
+ }
+ return checkForReturn(node);
+ }
+
+ /**
+ * Check to see if the node is valid for evaluation,
+ * meaning it has an else and not an else-if
+ *
+ * @param {Node} node The node being evaluated
+ * @returns {boolean} True if the node is valid
+ */
+ function hasElse(node) {
+ return node.alternate && node.consequent && node.alternate.type !== "IfStatement";
+ }
+
+ /**
+ * If the consequent is an IfStatement, check to see if it has an else
+ * and both its consequent and alternate path return, meaning this is
+ * a nested case of rule violation. If-Else not considered currently.
+ *
+ * @param {Node} node The consequent node
+ * @returns {boolean} True if this is a nested rule violation
+ */
+ function checkForIf(node) {
+ return node.type === "IfStatement" && hasElse(node) &&
+ naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent);
+ }
+
+ /**
+ * Check the consequent/body node to make sure it is not
+ * a ReturnStatement or an IfStatement that returns on both
+ * code paths. If it is, display the context report.
+ *
+ * @param {Node} node The consequent or body node
+ * @param {Node} alternate The alternate node
+ * @returns {void}
+ */
+ function checkForReturnOrIf(node, alternate) {
+ if (checkForReturn(node) || checkForIf(node)) {
+ displayReport(alternate);
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "IfStatement": function (node) {
+ // Don't bother finding a ReturnStatement, if there's no `else`
+ // or if the alternate is also an if (indicating an else if).
+ if (hasElse(node)) {
+ var consequent = node.consequent,
+ alternate = node.alternate;
+ // If we have a BlockStatement, check each consequent body node.
+ if (consequent.type === "BlockStatement") {
+ var body = consequent.body;
+ body.forEach(function (bodyNode) {
+ checkForReturnOrIf(bodyNode, alternate);
+ });
+ // If not a block statement, make sure the consequent isn't a ReturnStatement
+ // or an IfStatement with returns on both paths
+ } else {
+ checkForReturnOrIf(consequent, alternate);
+ }
+ }
+ }
+
+ };
+
+};
+
+},{}],72:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag the use of empty character classes in regular expressions
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/*
+plain-English description of the following regexp:
+0. `^` fix the match at the beginning of the string
+1. `\/`: the `/` that begins the regexp
+2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
+ 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
+ 2.1. `\\.`: an escape sequence
+ 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
+3. `\/` the `/` that ends the regexp
+4. `[gimy]*`: optional regexp flags
+5. `$`: fix the match at the end of the string
+*/
+var regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimy]*$/;
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ var token = context.getFirstToken(node);
+ if (token.type === "RegularExpression" && !regex.test(token.value)) {
+ context.report(node, "Empty class.");
+ }
+ }
+
+ };
+
+};
+
+},{}],73:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when label is not used for a loop or switch
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "LabeledStatement": function(node) {
+ if (node.body.type !== "ForStatement" && node.body.type !== "WhileStatement" && node.body.type !== "DoWhileStatement" && node.body.type !== "SwitchStatement" && node.body.type !== "ForInStatement") {
+ context.report(node, "Unexpected label {{l}}", {l: node.label.name});
+ }
+ }
+ };
+
+};
+
+},{}],74:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of an empty block statement
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "BlockStatement": function(node) {
+ var ancestors = context.getAncestors(),
+ parent = ancestors[ancestors.length - 1],
+ parentType = parent.type,
+ isFinallyBlock = (parentType === "TryStatement") && (parent.finalizer === node);
+
+ if (/FunctionExpression|FunctionDeclaration|CatchClause/.test(parentType) ||
+ (isFinallyBlock && !parent.handlers.length)) {
+ return;
+ }
+
+ if (node.body.length === 0) {
+ context.report(node, "Empty block statement.");
+ }
+ },
+
+ "SwitchStatement": function(node) {
+
+ if (typeof node.cases === "undefined" || node.cases.length === 0) {
+ context.report(node, "Empty switch statement.");
+ }
+ }
+ };
+
+};
+
+},{}],75:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag comparisons to null without a type-checking
+ * operator.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ return {
+
+ "BinaryExpression": function(node) {
+ var badOperator = node.operator === "==" || node.operator === "!=";
+
+ if (node.right.type === "Literal" && node.right.raw === "null" && badOperator ||
+ node.left.type === "Literal" && node.left.raw === "null" && badOperator) {
+ context.report(node, "Use ‘===’ to compare with ‘null’.");
+ }
+ }
+ };
+
+};
+
+},{}],76:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of eval() statement
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var IMPLIED_EVAL = /set(?:Timeout|Interval)/;
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Determines if a node represents a call to setTimeout/setInterval with
+ * a string argument.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} True if the node matches, false if not.
+ * @private
+ */
+ function isImpliedEval(node) {
+
+ var isMemberExpression = (node.callee.type === "MemberExpression"),
+ isIdentifier = (node.callee.type === "Identifier"),
+ isSetMethod = (isIdentifier && IMPLIED_EVAL.test(node.callee.name)) ||
+ (isMemberExpression && node.callee.object.name === "window" &&
+ IMPLIED_EVAL.test(node.callee.property.name)),
+ hasStringArgument = node.arguments.length && (typeof node.arguments[0].value === "string");
+
+ return isSetMethod && hasStringArgument;
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "CallExpression": function(node) {
+ if (node.callee.name === "eval") {
+ context.report(node, "eval can be harmful.");
+ } else if (isImpliedEval(node)) {
+ if (node.arguments.length && (typeof node.arguments[0].value === "string")) {
+ context.report(node, "Implied eval can be harmful. Pass a function instead of a string.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],77:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag assignment of the exception parameter
+ * @author Stephen Murray
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var inCatch = false,
+ exceptionName = null;
+
+ return {
+
+ "CatchClause": function(node) {
+ inCatch = true;
+ exceptionName = node.param.name;
+ },
+
+ "CatchClause:exit": function() {
+ inCatch = false;
+ exceptionName = null;
+ },
+
+ "AssignmentExpression": function(node) {
+
+ if (inCatch) {
+
+ if (node.left.name === exceptionName) {
+ context.report(node, "Do not assign to the exception parameter.");
+ }
+ }
+ }
+
+ };
+
+};
+
+},{}],78:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag adding properties to native object's prototypes.
+ * @author David Nelson
+ */
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var BUILTINS = [
+ "Object", "Function", "Array", "String", "Boolean", "Number", "Date",
+ "RegExp", "Error", "EvalError", "RangeError", "ReferenceError",
+ "SyntaxError", "TypeError", "URIError"
+];
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ // handle the Array.prototype.extra style case
+ "AssignmentExpression": function(node) {
+ var lhs = node.left, affectsProto;
+
+ if (lhs.type !== "MemberExpression" || lhs.object.type !== "MemberExpression") {
+ return;
+ }
+
+ affectsProto = lhs.object.computed ?
+ lhs.object.property.type === "Literal" && lhs.object.property.value === "prototype" :
+ lhs.object.property.name === "prototype";
+
+ if (!affectsProto) {
+ return;
+ }
+
+ BUILTINS.forEach(function(builtin) {
+ if (lhs.object.object.name === builtin) {
+ context.report(node, builtin + " prototype is read only, properties should not be added.");
+ }
+ });
+ },
+
+ // handle the Object.defineProperty(Array.prototype) case
+ "CallExpression": function(node) {
+
+ var callee = node.callee,
+ subject,
+ object;
+
+ // only worry about Object.defineProperty
+ if (callee.type === "MemberExpression" &&
+ callee.object.name === "Object" &&
+ callee.property.name === "defineProperty") {
+
+ // verify the object being added to is a native prototype
+ subject = node.arguments[0];
+ object = subject.object;
+
+ if (object &&
+ object.type === "Identifier" &&
+ (BUILTINS.indexOf(object.name) > -1) &&
+ subject.property.name === "prototype") {
+
+ context.report(node, object.name + " prototype is read only, properties should not be added.");
+ }
+ }
+
+ }
+ };
+
+};
+
+},{}],79:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag unnecessary bind calls
+ * @author Bence Dányi
+ * @copyright 2014 Bence Dányi. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var scope = [{
+ depth: -1,
+ found: 0
+ }];
+
+ /**
+ * Get the topmost scope
+ * @returns {Object} The topmost scope
+ */
+ function getTopScope() {
+ return scope[scope.length - 1];
+ }
+
+ /**
+ * Increment the depth of the top scope
+ * @returns {void}
+ */
+ function incrementScopeDepth() {
+ var top = getTopScope();
+ top.depth++;
+ }
+
+ /**
+ * Decrement the depth of the top scope
+ * @returns {void}
+ */
+ function decrementScopeDepth() {
+ var top = getTopScope();
+ top.depth--;
+ }
+
+ return {
+ "CallExpression": function(node) {
+ if (node.arguments.length === 1 &&
+ node.callee.type === "MemberExpression" &&
+ node.callee.property.name === "bind" &&
+ node.callee.object.type === "FunctionExpression") {
+ scope.push({
+ call: node,
+ depth: -1,
+ found: 0
+ });
+ }
+ },
+ "CallExpression:exit": function(node) {
+ var top = getTopScope();
+ if (top.call === node && top.found === 0) {
+ context.report(node, "The function binding is unnecessary.");
+ scope.pop();
+ }
+ },
+ "FunctionExpression": incrementScopeDepth,
+ "FunctionExpression:exit": decrementScopeDepth,
+ "FunctionDeclaration": incrementScopeDepth,
+ "FunctionDeclaration:exit": decrementScopeDepth,
+ "ThisExpression": function() {
+ var top = getTopScope();
+ if (top.depth === 0) {
+ top.found++;
+ }
+ }
+ };
+
+};
+
+},{}],80:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag unnecessary double negation in Boolean contexts
+ * @author Brandon Mills
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "UnaryExpression": function (node) {
+ var ancestors = context.getAncestors(),
+ parent = ancestors.pop(),
+ grandparent = ancestors.pop();
+
+ // Exit early if it's guaranteed not to match
+ if (node.operator !== "!" ||
+ parent.type !== "UnaryExpression" ||
+ parent.operator !== "!") {
+ return;
+ }
+
+ // if () ...
+ if (grandparent.type === "IfStatement") {
+ context.report(node, "Redundant double negation in an if statement condition.");
+
+ // do ... while ()
+ } else if (grandparent.type === "DoWhileStatement") {
+ context.report(node, "Redundant double negation in a do while loop condition.");
+
+ // while () ...
+ } else if (grandparent.type === "WhileStatement") {
+ context.report(node, "Redundant double negation in a while loop condition.");
+
+ // ? ... : ...
+ } else if ((grandparent.type === "ConditionalExpression" &&
+ parent === grandparent.test)) {
+ context.report(node, "Redundant double negation in a ternary condition.");
+
+ // for (...; ; ...) ...
+ } else if ((grandparent.type === "ForStatement" &&
+ parent === grandparent.test)) {
+ context.report(node, "Redundant double negation in a for loop condition.");
+
+ // !
+ } else if ((grandparent.type === "UnaryExpression" &&
+ grandparent.operator === "!")) {
+ context.report(node, "Redundant multiple negation.");
+
+ // Boolean()
+ } else if ((grandparent.type === "CallExpression" &&
+ grandparent.callee.type === "Identifier" &&
+ grandparent.callee.name === "Boolean")) {
+ context.report(node, "Redundant double negation in call to Boolean().");
+
+ // new Boolean()
+ } else if ((grandparent.type === "NewExpression" &&
+ grandparent.callee.type === "Identifier" &&
+ grandparent.callee.name === "Boolean")) {
+ context.report(node, "Redundant double negation in Boolean constructor call.");
+ }
+ }
+ };
+
+};
+
+},{}],81:[function(require,module,exports){
+/**
+ * @fileoverview Disallow parenthesesisng higher precedence subexpressions.
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ function isParenthesised(node) {
+ var previousToken = context.getTokenBefore(node),
+ nextToken = context.getTokenAfter(node);
+
+ return previousToken && nextToken &&
+ previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ function isParenthesisedTwice(node) {
+ var previousToken = context.getTokenBefore(node, 1),
+ nextToken = context.getTokenAfter(node, 1);
+
+ return isParenthesised(node) && previousToken && nextToken &&
+ previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ function precedence(node) {
+
+ switch (node.type) {
+ case "SequenceExpression":
+ return 0;
+
+ case "AssignmentExpression":
+ return 1;
+
+ case "ConditionalExpression":
+ return 3;
+
+ case "LogicalExpression":
+ switch (node.operator) {
+ case "||":
+ return 4;
+ case "&&":
+ return 5;
+ // no default
+ }
+
+ /* falls through */
+ case "BinaryExpression":
+ switch (node.operator) {
+ case "|":
+ return 6;
+ case "^":
+ return 7;
+ case "&":
+ return 8;
+ case "==":
+ case "!=":
+ case "===":
+ case "!==":
+ return 9;
+ case "<":
+ case "<=":
+ case ">":
+ case ">=":
+ case "in":
+ case "instanceof":
+ return 10;
+ case "<<":
+ case ">>":
+ case ">>>":
+ return 11;
+ case "+":
+ case "-":
+ return 12;
+ case "*":
+ case "/":
+ case "%":
+ return 13;
+ // no default
+ }
+ /* falls through */
+ case "UnaryExpression":
+ return 14;
+ case "UpdateExpression":
+ return 15;
+ case "CallExpression":
+ // IIFE is allowed to have parens in any position (#655)
+ if (node.callee.type === "FunctionExpression") {
+ return -1;
+ }
+ return 16;
+ case "NewExpression":
+ return 17;
+ // no default
+ }
+ return 18;
+ }
+
+ function report(node) {
+ context.report(node, "Gratuitous parentheses around expression.");
+ }
+
+ function dryUnaryUpdate(node) {
+ if (isParenthesised(node.argument) && precedence(node.argument) >= precedence(node)) {
+ report(node.argument);
+ }
+ }
+
+ function dryCallNew(node) {
+ if (isParenthesised(node.callee) && precedence(node.callee) >= precedence(node) &&
+ !(node.type === "CallExpression" && node.callee.type === "FunctionExpression")) {
+ report(node.callee);
+ }
+ if (node.arguments.length === 1) {
+ if (isParenthesisedTwice(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) {
+ report(node.arguments[0]);
+ }
+ } else {
+ [].forEach.call(node.arguments, function(arg) {
+ if (isParenthesised(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) {
+ report(arg);
+ }
+ });
+ }
+ }
+
+ function dryBinaryLogical(node) {
+ var prec = precedence(node);
+ if (isParenthesised(node.left) && precedence(node.left) >= prec) {
+ report(node.left);
+ }
+ if (isParenthesised(node.right) && precedence(node.right) > prec) {
+ report(node.right);
+ }
+ }
+
+ return {
+ "ArrayExpression": function(node) {
+ [].forEach.call(node.elements, function(e) {
+ if (e && isParenthesised(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) {
+ report(e);
+ }
+ });
+ },
+ "AssignmentExpression": function(node) {
+ if (isParenthesised(node.right) && precedence(node.right) >= precedence(node)) {
+ report(node.right);
+ }
+ },
+ "BinaryExpression": dryBinaryLogical,
+ "CallExpression": dryCallNew,
+ "ConditionalExpression": function(node) {
+ if (isParenthesised(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) {
+ report(node.test);
+ }
+ if (isParenthesised(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) {
+ report(node.consequent);
+ }
+ if (isParenthesised(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) {
+ report(node.alternate);
+ }
+ },
+ "DoWhileStatement": function(node) {
+ if (isParenthesisedTwice(node.test)) {
+ report(node.test);
+ }
+ },
+ "ExpressionStatement": function(node) {
+ var firstToken;
+ if (isParenthesised(node.expression)) {
+ firstToken = context.getFirstToken(node.expression);
+ if (firstToken.value !== "function" && firstToken.value !== "{") {
+ report(node.expression);
+ }
+ }
+ },
+ "ForInStatement": function(node) {
+ if (isParenthesised(node.right)) {
+ report(node.right);
+ }
+ },
+ "ForStatement": function(node) {
+ if (node.init && isParenthesised(node.init)) {
+ report(node.init);
+ }
+
+ if (node.test && isParenthesised(node.test)) {
+ report(node.test);
+ }
+
+ if (node.update && isParenthesised(node.update)) {
+ report(node.update);
+ }
+ },
+ "IfStatement": function(node) {
+ if (isParenthesisedTwice(node.test)) {
+ report(node.test);
+ }
+ },
+ "LogicalExpression": dryBinaryLogical,
+ "MemberExpression": function(node) {
+ if (
+ isParenthesised(node.object) &&
+ precedence(node.object) >= precedence(node) &&
+ (
+ node.computed ||
+ !(
+ (node.object.type === "Literal" &&
+ typeof node.object.value === "number" &&
+ /^[0-9]+$/.test(context.getFirstToken(node.object).value))
+ ||
+ // RegExp literal is allowed to have parens (#1589)
+ (node.object.type === "Literal" && node.object.regex)
+ )
+ )
+ ) {
+ report(node.object);
+ }
+ },
+ "NewExpression": dryCallNew,
+ "ObjectExpression": function(node) {
+ [].forEach.call(node.properties, function(e) {
+ var v = e.value;
+ if (v && isParenthesised(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) {
+ report(v);
+ }
+ });
+ },
+ "ReturnStatement": function(node) {
+ if (node.argument && isParenthesised(node.argument) &&
+ // RegExp literal is allowed to have parens (#1589)
+ !(node.argument.type === "Literal" && node.argument.regex)) {
+ report(node.argument);
+ }
+ },
+ "SequenceExpression": function(node) {
+ [].forEach.call(node.expressions, function(e) {
+ if (isParenthesised(e) && precedence(e) >= precedence(node)) {
+ report(e);
+ }
+ });
+ },
+ "SwitchCase": function(node) {
+ if (node.test && isParenthesised(node.test)) {
+ report(node.test);
+ }
+ },
+ "SwitchStatement": function(node) {
+ if (isParenthesisedTwice(node.discriminant)) {
+ report(node.discriminant);
+ }
+ },
+ "ThrowStatement": function(node) {
+ if (isParenthesised(node.argument)) {
+ report(node.argument);
+ }
+ },
+ "UnaryExpression": dryUnaryUpdate,
+ "UpdateExpression": dryUnaryUpdate,
+ "VariableDeclarator": function(node) {
+ if (node.init && isParenthesised(node.init) &&
+ precedence(node.init) >= precedence({type: "AssignmentExpression"}) &&
+ // RegExp literal is allowed to have parens (#1589)
+ !(node.init.type === "Literal" && node.init.regex)) {
+ report(node.init);
+ }
+ },
+ "WhileStatement": function(node) {
+ if (isParenthesisedTwice(node.test)) {
+ report(node.test);
+ }
+ },
+ "WithStatement": function(node) {
+ if (isParenthesisedTwice(node.object)) {
+ report(node.object);
+ }
+ }
+ };
+
+};
+
+},{}],82:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of unnecessary semicolons
+ * @author Nicholas C. Zakas
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "EmptyStatement": function(node) {
+ context.report(node, "Unnecessary semicolon.");
+ }
+ };
+
+};
+
+},{}],83:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag unnecessary strict directives.
+ * @author Ian Christian Myers
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ function directives(block) {
+ var ds = [], body = block.body, e, i, l;
+
+ for (i = 0, l = body.length; i < l; ++i) {
+ e = body[i];
+
+ if (
+ e.type === "ExpressionStatement" &&
+ e.expression.type === "Literal" &&
+ typeof e.expression.value === "string"
+ ) {
+ ds.push(e.expression);
+ } else {
+ break;
+ }
+ }
+ return ds;
+ }
+
+ function isStrict(directive) {
+ return directive.value === "use strict";
+ }
+
+ function checkForUnnecessaryUseStrict(node) {
+ var useStrictDirectives, scope, upper;
+ useStrictDirectives = directives(node).filter(isStrict);
+
+ switch (useStrictDirectives.length) {
+ case 0:
+ break;
+
+ case 1:
+ scope = context.getScope();
+ upper = scope.upper;
+
+ if (upper && upper.functionExpressionScope) {
+ upper = upper.upper;
+ }
+
+ if (upper && upper.isStrict) {
+ context.report(useStrictDirectives[0], "Unnecessary 'use strict'.");
+ }
+ break;
+
+ default:
+ context.report(useStrictDirectives[1], "Multiple 'use strict' directives.");
+ }
+ }
+
+ return {
+
+ "Program": checkForUnnecessaryUseStrict,
+
+ "FunctionExpression": function(node) {
+ checkForUnnecessaryUseStrict(node.body);
+ },
+
+ "FunctionDeclaration": function(node) {
+ checkForUnnecessaryUseStrict(node.body);
+ }
+ };
+
+};
+
+},{}],84:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag fall-through cases in switch statements.
+ * @author Matt DuVall
+ */
+"use strict";
+
+
+var FALLTHROUGH_COMMENT = /falls\sthrough/;
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var switches = [];
+
+ return {
+
+ "SwitchCase": function(node) {
+
+ var consequent = node.consequent,
+ switchData = switches[switches.length - 1],
+ i,
+ comments,
+ comment;
+
+ /*
+ * Some developers wrap case bodies in blocks, so if there is just one
+ * node and it's a block statement, check inside.
+ */
+ if (consequent.length === 1 && consequent[0].type === "BlockStatement") {
+ consequent = consequent[0];
+ }
+
+ // checking on previous case
+ if (!switchData.lastCaseClosed) {
+
+ // a fall through comment will be the last trailing comment of the last case
+ comments = context.getComments(switchData.lastCase).trailing;
+ comment = comments[comments.length - 1];
+
+ // unless the user doesn't like semicolons, in which case it's first leading comment of this case
+ if (!comment) {
+ comments = context.getComments(node).leading;
+ comment = comments[comments.length - 1];
+ }
+
+ // check for comment
+ if (!comment || !FALLTHROUGH_COMMENT.test(comment.value)) {
+
+ context.report(switchData.lastCase,
+ "Expected a \"break\" statement before \"{{code}}\".",
+ { code: node.test ? "case" : "default" });
+ }
+ }
+
+ // now dealing with the current case
+ switchData.lastCaseClosed = false;
+ switchData.lastCase = node;
+
+ // try to verify using statements - go backwards as a fast path for the search
+ if (consequent.length) {
+ for (i = consequent.length - 1; i >= 0; i--) {
+ if (/(?:Break|Continue|Return|Throw)Statement/.test(consequent[i].type)) {
+ switchData.lastCaseClosed = true;
+ break;
+ }
+ }
+ } else {
+ // the case statement has no statements, so it must logically fall through
+ switchData.lastCaseClosed = true;
+ }
+
+ /*
+ * Any warnings are triggered when the next SwitchCase occurs.
+ * There is no need to warn on the last SwitchCase, since it can't
+ * fall through to anything.
+ */
+ },
+
+ "SwitchStatement": function(node) {
+ switches.push({
+ node: node,
+ lastCaseClosed: true,
+ lastCase: null
+ });
+ },
+
+ "SwitchStatement:exit": function() {
+ switches.pop();
+ }
+ };
+
+};
+
+},{}],85:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal
+ * @author James Allardice
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "Literal": function(node) {
+
+ if (typeof node.value === "number") {
+ if (node.raw.indexOf(".") === 0) {
+ context.report(node, "A leading decimal point can be confused with a dot.");
+ }
+ if (node.raw.indexOf(".") === node.raw.length - 1) {
+ context.report(node, "A trailing decimal point can be confused with a dot.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],86:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of function declaration identifiers as variables.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /*
+ * Walk the scope chain looking for either a FunctionDeclaration or a
+ * VariableDeclaration with the same name as left-hand side of the
+ * AssignmentExpression. If we find the FunctionDeclaration first, then we
+ * warn, because a FunctionDeclaration is trying to become a Variable or a
+ * FunctionExpression. If we find a VariableDeclaration first, then we have
+ * a legitimate shadow variable.
+ */
+ function checkIfIdentifierIsFunction(scope, name) {
+ var variable,
+ def,
+ i,
+ j;
+
+ // Loop over all of the identifiers available in scope.
+ for (i = 0; i < scope.variables.length; i++) {
+ variable = scope.variables[i];
+
+ // For each identifier, see if it was defined in _this_ scope.
+ for (j = 0; j < variable.defs.length; j++) {
+ def = variable.defs[j];
+
+ // Identifier is a function and was declared in this scope
+ if (def.name.name === name && def.type === "FunctionName") {
+ return true;
+ }
+
+ // Identifier is a variable and was declared in this scope. This
+ // is a legitimate shadow variable.
+ if (def.name.name === name) {
+ return false;
+ }
+ }
+ }
+
+ // Check the upper scope.
+ if (scope.upper) {
+ return checkIfIdentifierIsFunction(scope.upper, name);
+ }
+
+ // We've reached the global scope and haven't found anything.
+ return false;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "AssignmentExpression": function(node) {
+ var scope = context.getScope(),
+ name = node.left.name;
+
+ if (checkIfIdentifierIsFunction(scope, name)) {
+ context.report(node, "'{{name}}' is a function.", { name: name });
+ }
+
+ }
+
+ };
+
+};
+
+},{}],87:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval
+ * @author James Allardice
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "CallExpression": function(node) {
+
+ if (node.callee.type === "Identifier") {
+ var callee = node.callee.name;
+
+ if (callee === "setTimeout" || callee === "setInterval") {
+ var argument = node.arguments[0];
+ if (argument && argument.type === "Literal" && typeof argument.value === "string") {
+ context.report(node, "Implied eval. Consider passing a function instead of a string.");
+ }
+ }
+ }
+ }
+ };
+
+};
+
+},{}],88:[function(require,module,exports){
+/**
+ * @fileoverview Enforces or disallows inline comments.
+ * @author Greg Cochard
+ * @copyright 2014 Greg Cochard. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ /**
+ * Will check that comments are not on lines starting with or ending with code
+ * @param {ASTNode} node The comment node to check
+ * @private
+ * @returns {void}
+ */
+ function testCodeAroundComment(node) {
+
+ // Get the whole line and cut it off at the start of the comment
+ var startLine = String(context.getSourceLines()[node.loc.start.line - 1]);
+ var endLine = String(context.getSourceLines()[node.loc.end.line - 1]);
+
+ var preamble = startLine.slice(0, node.loc.start.column).trim();
+
+ // Also check after the comment
+ var postamble = endLine.slice(node.loc.end.column).trim();
+
+ // Should be empty if there was only whitespace around the comment
+ if (preamble || postamble) {
+ context.report(node, "Unexpected comment inline with code.");
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "LineComment": testCodeAroundComment,
+ "BlockComment": testCodeAroundComment
+
+ };
+};
+
+},{}],89:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce declarations in program or function body root.
+ * @author Brandon Mills
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ /**
+ * Find the nearest Program or Function ancestor node.
+ * @returns {Object} Ancestor's type and distance from node.
+ */
+ function nearestBody() {
+ var ancestors = context.getAncestors(),
+ ancestor = ancestors.pop(),
+ generation = 1;
+
+ while (ancestor && ["Program", "FunctionDeclaration",
+ "FunctionExpression"].indexOf(ancestor.type) < 0) {
+ generation += 1;
+ ancestor = ancestors.pop();
+ }
+
+ return {
+ // Type of containing ancestor
+ type: ancestor.type,
+ // Separation between ancestor and node
+ distance: generation
+ };
+ }
+
+ /**
+ * Ensure that a given node is at a program or function body's root.
+ * @param {ASTNode} node Declaration node to check.
+ * @returns {void}
+ */
+ function check(node) {
+ var body = nearestBody(node),
+ valid = ((body.type === "Program" && body.distance === 1) ||
+ body.distance === 2);
+
+ if (!valid) {
+ context.report(node, "Move {{type}} declaration to {{body}} root.",
+ {
+ type: (node.type === "FunctionDeclaration" ?
+ "function" : "variable"),
+ body: (body.type === "Program" ?
+ "program" : "function body")
+ }
+ );
+ }
+ }
+
+ return {
+
+ "FunctionDeclaration": check,
+ "VariableDeclaration": function(node) {
+ if (context.options[0] === "both") {
+ check(node);
+ }
+ }
+
+ };
+
+};
+
+},{}],90:[function(require,module,exports){
+/**
+ * @fileoverview Validate strings passed to the RegExp constructor
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ function isString(node) {
+ return node && node.type === "Literal" && typeof node.value === "string";
+ }
+
+ function check(node) {
+ if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0])) {
+ try {
+ if (isString(node.arguments[1])) {
+ void new RegExp(node.arguments[0].value, node.arguments[1].value);
+ } else {
+ void new RegExp(node.arguments[0].value);
+ }
+ } catch(e) {
+ context.report(node, e.message);
+ }
+ }
+ }
+
+ return {
+ "CallExpression": check,
+ "NewExpression": check
+ };
+
+};
+
+},{}],91:[function(require,module,exports){
+/**
+ * @fileoverview Rule to disalow whitespace that is not a tab or space, whitespace inside strings and comments are allowed
+ * @author Jonathan Kingston
+ * @copyright 2014 Jonathan Kingston. All rights reserved.
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ var irregularWhitespace = /[\u0085\u00A0\ufeff\f\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000]+/mg;
+
+ // Module store of errors that we have found
+ var errors = [];
+
+ /**
+ * Removes errors that occur inside a string node
+ * @param {ASTNode} node to check for matching errors.
+ * @returns {void}
+ * @private
+ */
+ function removeStringError(node) {
+ var locStart = node.loc.start;
+ var locEnd = node.loc.end;
+
+ errors = errors.filter(function (error) {
+ var errorLoc = error[1];
+ if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) {
+ if (errorLoc.column >= locStart.column && errorLoc.column <= locEnd.column) {
+ return false;
+ }
+ }
+ return true;
+ });
+ }
+
+ /**
+ * Checks nodes for errors that we are choosing to ignore and calls the relevent methods to remove the errors
+ * @param {ASTNode} node to check for matching errors.
+ * @returns {void}
+ * @private
+ */
+ function removeInvalidNodeErrors(node) {
+ if (typeof node.value === "string") {
+ // If we have irregular characters remove them from the errors list
+ if (node.value.match(irregularWhitespace)) {
+ removeStringError(node);
+ }
+ }
+ }
+
+ return {
+ "Program": function (node) {
+ /**
+ * As we can easily fire warnings for all white space issues with all the source its simpler to fire them here
+ * This means we can check all the application code without having to worry about issues caused in the parser tokens
+ * When writing this code also evaluating per node was missing out connecting tokens in some cases
+ * We can later filter the errors when they are found to be not an issue in nodes we don't care about
+ */
+ var sourceLines = context.getSourceLines();
+
+ sourceLines.forEach(function (sourceLine, lineIndex) {
+ var location,
+ match = irregularWhitespace.exec(sourceLine);
+
+ if (match !== null) {
+ location = {
+ line: lineIndex + 1,
+ column: match.index
+ };
+
+ errors.push([node, location, "Irregular whitespace not allowed"]);
+ }
+ });
+ },
+ "Identifier": removeInvalidNodeErrors,
+ "Literal": removeInvalidNodeErrors,
+ "Statement": removeInvalidNodeErrors,
+ "Expression": removeInvalidNodeErrors,
+ "Program:exit": function () {
+
+ // If we have any errors remaining report on them
+ errors.forEach(function (error) {
+ context.report.apply(this, error);
+ });
+ }
+ };
+};
+
+},{}],92:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag usage of __iterator__ property
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "MemberExpression": function(node) {
+
+ if (node.property &&
+ (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) ||
+ (node.property.type === "Literal" && node.property.value === "__iterator__")) {
+ context.report(node, "Reserved name '__iterator__'.");
+ }
+ }
+ };
+
+};
+
+},{}],93:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag labels that are the same as an identifier
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ function findIdentifier(scope, identifier) {
+ var found = false;
+
+ scope.variables.forEach(function(variable) {
+ if (variable.name === identifier) {
+ found = true;
+ }
+ });
+
+ scope.references.forEach(function(reference) {
+ if (reference.identifier.name === identifier) {
+ found = true;
+ }
+ });
+
+ // If we have not found the identifier in this scope, check the parent
+ // scope.
+ if (scope.upper && !found) {
+ return findIdentifier(scope.upper, identifier);
+ }
+
+ return found;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "LabeledStatement": function(node) {
+
+ // Fetch the innermost scope.
+ var scope = context.getScope();
+
+ // Recursively find the identifier walking up the scope, starting
+ // with the innermost scope.
+ if (findIdentifier(scope, node.label.name)) {
+ context.report(node, "Found identifier with same name as label.");
+ }
+ }
+
+ };
+
+};
+
+},{}],94:[function(require,module,exports){
+/**
+ * @fileoverview Disallow Labeled Statements
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "LabeledStatement": function(node) {
+ context.report(node, "Unexpected labeled statement.");
+ },
+
+ "BreakStatement": function(node) {
+
+ if (node.label) {
+ context.report(node, "Unexpected label in break statement.");
+ }
+
+ },
+
+ "ContinueStatement": function(node) {
+
+ if (node.label) {
+ context.report(node, "Unexpected label in continue statement.");
+ }
+
+ }
+
+
+ };
+
+};
+
+},{}],95:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag blocks with no reason to exist
+ * @author Brandon Mills
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "BlockStatement": function (node) {
+ // Check for any occurrence of BlockStatement > BlockStatement or
+ // Program > BlockStatement
+ var parent = context.getAncestors().pop();
+ if (parent.type === "BlockStatement" || parent.type === "Program") {
+ context.report(node, "Block is nested inside another block.");
+ }
+ }
+ };
+
+};
+
+},{}],96:[function(require,module,exports){
+/**
+ * @fileoverview Rule to disallow if as the only statmenet in an else block
+ * @author Brandon Mills
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+ "IfStatement": function(node) {
+ var ancestors = context.getAncestors(),
+ parent = ancestors.pop(),
+ grandparent = ancestors.pop();
+
+ if (parent && parent.type === "BlockStatement" &&
+ parent.body.length === 1 && grandparent &&
+ grandparent.type === "IfStatement" &&
+ parent === grandparent.alternate) {
+ context.report(node, "Unexpected if as the only statement in an else block.");
+ }
+ }
+ };
+
+};
+
+},{}],97:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag creation of function inside a loop
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ function checkForLoops(node) {
+ var ancestors = context.getAncestors();
+
+ if (ancestors.some(function(ancestor) {
+ return ancestor.type === "ForStatement" || ancestor.type === "ForInStatement" ||
+ ancestor.type === "WhileStatement" || ancestor.type === "DoWhileStatement";
+ })) {
+ context.report(node, "Don't make functions within a loop");
+ }
+ }
+
+ return {
+ "FunctionExpression": checkForLoops,
+ "FunctionDeclaration": checkForLoops
+ };
+};
+
+},{}],98:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce grouped require statements for Node.JS
+ * @author Raphael Pigulla
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ /**
+ * Returns the list of built-in modules.
+ *
+ * @returns {string[]} An array of built-in Node.js modules.
+ */
+ function getBuiltinModules() {
+ // This list is generated using `require("repl")._builtinLibs.concat('repl').sort()`
+ // This particular list was generated using node v0.11.9
+ return [
+ "assert", "buffer", "child_process", "cluster", "crypto",
+ "dgram", "dns", "domain", "events", "fs", "http", "https",
+ "net", "os", "path", "punycode", "querystring", "readline",
+ "repl", "smalloc", "stream", "string_decoder", "tls", "tty",
+ "url", "util", "vm", "zlib"
+ ];
+ }
+
+ var BUILTIN_MODULES = getBuiltinModules();
+
+ var DECL_REQUIRE = "require",
+ DECL_UNINITIALIZED = "uninitialized",
+ DECL_OTHER = "other";
+
+ var REQ_CORE = "core",
+ REQ_FILE = "file",
+ REQ_MODULE = "module",
+ REQ_COMPUTED = "computed";
+
+ /**
+ * Determines the type of a declaration statement.
+ * @param {ASTNode} initExpression The init node of the VariableDeclarator.
+ * @returns {string} The type of declaration represented by the expression.
+ */
+ function getDeclarationType(initExpression) {
+ if (!initExpression) {
+ // "var x;"
+ return DECL_UNINITIALIZED;
+ }
+
+ if (initExpression.type === "CallExpression" &&
+ initExpression.callee.type === "Identifier" &&
+ initExpression.callee.name === "require"
+ ) {
+ // "var x = require('util');"
+ return DECL_REQUIRE;
+ } else if (initExpression.type === "MemberExpression") {
+ // "var x = require('glob').Glob;"
+ return getDeclarationType(initExpression.object);
+ }
+
+ // "var x = 42;"
+ return DECL_OTHER;
+ }
+
+ /**
+ * Determines the type of module that is loaded via require.
+ * @param {ASTNode} initExpression The init node of the VariableDeclarator.
+ * @returns {string} The module type.
+ */
+ function inferModuleType(initExpression) {
+ if (initExpression.type === "MemberExpression") {
+ // "var x = require('glob').Glob;"
+ return inferModuleType(initExpression.object);
+ } else if (initExpression.arguments.length === 0) {
+ // "var x = require();"
+ return REQ_COMPUTED;
+ }
+
+ var arg = initExpression.arguments[0];
+
+ if (arg.type !== "Literal" || typeof arg.value !== "string") {
+ // "var x = require(42);"
+ return REQ_COMPUTED;
+ }
+
+ if (BUILTIN_MODULES.indexOf(arg.value) !== -1) {
+ // "var fs = require('fs');"
+ return REQ_CORE;
+ } else if (/^\.{0,2}\//.test(arg.value)) {
+ // "var utils = require('./utils');"
+ return REQ_FILE;
+ } else {
+ // "var async = require('async');"
+ return REQ_MODULE;
+ }
+ }
+
+ /**
+ * Check if the list of variable declarations is mixed, i.e. whether it
+ * contains both require and other declarations.
+ * @param {ASTNode} declarations The list of VariableDeclarators.
+ * @returns {boolean} True if the declarations are mixed, false if not.
+ */
+ function isMixed(declarations) {
+ var contains = {};
+
+ declarations.forEach(function (declaration) {
+ var type = getDeclarationType(declaration.init);
+ contains[type] = true;
+ });
+
+ return !!(
+ contains[DECL_REQUIRE] &&
+ (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER])
+ );
+ }
+
+ /**
+ * Check if all require declarations in the given list are of the same
+ * type.
+ * @param {ASTNode} declarations The list of VariableDeclarators.
+ * @returns {boolean} True if the declarations are grouped, false if not.
+ */
+ function isGrouped(declarations) {
+ var found = {};
+
+ declarations.forEach(function (declaration) {
+ if (getDeclarationType(declaration.init) === DECL_REQUIRE) {
+ found[inferModuleType(declaration.init)] = true;
+ }
+ });
+
+ return Object.keys(found).length <= 1;
+ }
+
+
+ return {
+
+ "VariableDeclaration": function(node) {
+ var grouping = !!context.options[0];
+
+ if (isMixed(node.declarations)) {
+ context.report(
+ node,
+ "Do not mix 'require' and other declarations."
+ );
+ } else if (grouping && !isGrouped(node.declarations)) {
+ context.report(
+ node,
+ "Do not mix core, module, file and computed requires."
+ );
+ }
+ }
+ };
+
+};
+
+},{}],99:[function(require,module,exports){
+/**
+ * @fileoverview Disallow mixed spaces and tabs for indentation
+ * @author Jary Niebur
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2014 Jary Niebur. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var smartTabs;
+
+ switch (context.options[0]) {
+ case true: // Support old syntax, maybe add deprecation warning here
+ case "smart-tabs":
+ smartTabs = true;
+ break;
+ default:
+ smartTabs = false;
+ }
+
+ var COMMENT_START = /^\s*\/\*/,
+ MAYBE_COMMENT = /^\s*\*/;
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Program": function(node) {
+ /*
+ * At least one space followed by a tab
+ * or the reverse before non-tab/-space
+ * characters begin.
+ */
+ var regex = /^(?=[\t ]*(\t | \t))/,
+ match,
+ lines = context.getSourceLines();
+
+ if (smartTabs) {
+ /*
+ * At least one space followed by a tab
+ * before non-tab/-space characters begin.
+ */
+ regex = /^(?=[\t ]* \t)/;
+ }
+
+ lines.forEach(function(line, i) {
+ match = regex.exec(line);
+
+ if (match) {
+
+ if (!MAYBE_COMMENT.test(line) && !COMMENT_START.test(lines[i - 1])) {
+ context.report(node, { line: i + 1, column: match.index + 1 }, "Mixed spaces and tabs.");
+ }
+
+ }
+ });
+ }
+
+ };
+
+};
+
+},{}],100:[function(require,module,exports){
+/**
+ * @fileoverview Disallow use of multiple spaces.
+ * @author Vignesh Anand aka vegetableman.
+ * @copyright 2014 Vignesh Anand. All rights reserved.
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+var OPERATORS = {
+ "Punctuator": {
+ "*": true, "/": true, "%": true, "+": true, "-": true, "<<": true,
+ ">>": true, ">>>": true, "<": true, "<=": true, ">": true, ">=": true,
+ "==": true, "!=": true, "===": true, "!==": true, "&": true, "^": true,
+ "|": true, "&&": true, "||": true, "=": true, "+=": true, "-=": true,
+ "*=": true, "/=": true, "%=": true, "<<=": true, ">>=": true,
+ ">>>=": true, "&=": true, "^=": true, "|=": true, "?": true, ":": true,
+ ",": true
+ },
+ "Keyword": {
+ "in": true,
+ "instanceof": true
+ }
+};
+
+/**
+ * Determines whether a token is a binary operator.
+ * @param {Token} token The token.
+ * @returns {Boolean} Whether the token is a binary operator.
+ */
+function isOperator(token) {
+ var type = OPERATORS[token.type];
+ return (type && type[token.value]) || false;
+}
+
+/**
+ * Gets the index of the first element of an array that satisfies a predicate.
+ * Like Array.prototype.indexOf(), but with a predicate instead of equality.
+ * @param {Array} array An array to search.
+ * @param {Function} predicate A function returning true if its argument
+ * satisfies a condition.
+ * @returns {Number} The index of the first element that satisifies
+ * the predicate, or -1 if no elements match.
+ */
+function findIndex(array, predicate) {
+ for (var i = 0, l = array.length; i < l; i++) {
+ if (predicate(array[i])) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ /**
+ * Validates that two adjacent tokens are separated by less than two spaces.
+ * @param {Token} left Token on the left side.
+ * @param {Token} right Token on the right side.
+ * @returns {void}
+ */
+ function validate(left, right) {
+ var op;
+
+ if (
+ left.loc.end.line === right.loc.start.line &&
+ right.range[0] - left.range[1] > 1
+ ) {
+ op = isOperator(left) ? left : right;
+ context.report(op, "Multiple spaces found {{side}} '{{op}}'.", {
+ side: op === right ? "before" : "after",
+ op: op.value
+ });
+ }
+ }
+
+ /**
+ * Validates the spacing of two nodes with an operator between them.
+ * @param {ASTNode} left Node left of the operator.
+ * @param {ASTNode} right Node right of the operator.
+ * @returns {void}
+ */
+ function validateBetween(left, right) {
+ var tokens = context.getTokensBetween(left, right, 1),
+ operatorIndex = findIndex(tokens.slice(1, -1), isOperator) + 1,
+ op = tokens[operatorIndex];
+
+ validate(tokens[operatorIndex - 1], op);
+ validate(op, tokens[operatorIndex + 1]);
+ }
+
+ /**
+ * Report if there are multiple spaces on the expression.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ * @private
+ */
+ function checkExpression(node) {
+ validateBetween(node.left, node.right);
+ }
+
+ /**
+ * Report if there are multiple spaces around conditional ternary operators.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ * @private
+ */
+ function checkConditional(node) {
+ validateBetween(node.test, node.consequent);
+ validateBetween(node.consequent, node.alternate);
+ }
+
+ /**
+ * Report if there are multiple spaces around equal operator in variable declaration.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ * @private
+ */
+ function checkVar(node) {
+ if (node.init) {
+ validateBetween(node.id, node.init);
+ }
+ }
+
+ /**
+ * Generates a function to check object literals and other list-like nodes.
+ * @param {String} property Name of the node's collection property.
+ * @returns {Function} A function that checks spacing within list-like node.
+ * @private
+ */
+ function checkList(property) {
+ /**
+ * Report if there are multiple spaces around list of items in objects,
+ * function parameters, sequences and declarations.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ * @private
+ */
+ return function(node) {
+ var items = node[property];
+
+ for (var i = 0, l = items.length; i < l - 1; i++) {
+ validateBetween(items[i], items[i + 1]);
+ }
+ };
+ }
+
+ /**
+ * Checks arrays literals, allowing that some elements may be empty.
+ * @param {ASTNode} node An ArrayExpression.
+ * @returns {void}
+ * @private
+ */
+ function checkArray(node) {
+ var elements = node.elements,
+ elementIndex = 0,
+ tokens = context.getTokens(node),
+ tokenIndex = 0,
+ length = tokens.length,
+ dest;
+
+ // Check spacing at the beginning, around commas, and at the end
+ while (tokenIndex < length - 1) {
+ validate(tokens[tokenIndex], tokens[++tokenIndex]);
+
+ // Don't advance to the next element until both sides of the comma
+ // have been checked
+ if (tokens[tokenIndex].value !== ",") {
+ // Skip to just before the end of the array or the next comma
+ if (elements[elementIndex]) {
+ dest = elements[elementIndex].range[1];
+ // Move to the end of the element
+ while (tokens[tokenIndex].range[1] < dest) {
+ ++tokenIndex;
+ }
+ // Move past anything (like closing parens) between the end
+ // of the node and the following comma or end brace.
+ while (
+ tokenIndex + 1 < tokens.length &&
+ tokens[tokenIndex + 1].value !== ","
+ ) {
+ ++tokenIndex;
+ }
+ }
+ ++elementIndex;
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "AssignmentExpression": checkExpression,
+ "BinaryExpression": checkExpression,
+ "LogicalExpression": checkExpression,
+ "ConditionalExpression": checkConditional,
+ "VariableDeclarator": checkVar,
+ "ArrayExpression": checkArray,
+ "ObjectExpression": checkList("properties"),
+ "SequenceExpression": checkList("expressions"),
+ "FunctionExpression": checkList("params"),
+ "FunctionDeclaration": checkList("params"),
+ "VariableDeclaration": checkList("declarations")
+ };
+
+};
+
+},{}],101:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when using multiline strings
+ * @author Ilya Volodin
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2013 Ilya Volodin. All rights reserved.
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ /**
+ * Determines if a given node is part of JSX syntax.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} True if the node is a JSX node, false if not.
+ * @private
+ */
+ function isJSXElement(node) {
+ return node.type.indexOf("JSX") === 0;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Literal": function(node) {
+ var lineBreak = /\n/;
+
+ if (lineBreak.test(node.raw) && !isJSXElement(node.parent)) {
+ context.report(node, "Multiline support is limited to browsers supporting ES5 only.");
+ }
+ }
+ };
+
+};
+
+},{}],102:[function(require,module,exports){
+/**
+ * @fileoverview Disallows multiple blank lines.
+ * implementation adapted from the no-trailing-spaces rule.
+ * @author Greg Cochard
+ * @copyright 2014 Greg Cochard. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ // Use options.max or 2 as default
+ var numLines = 2;
+
+ if (context.options.length) {
+ numLines = context.options[0].max;
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Program": function checkBlankLines(node) {
+ var lines = context.getSourceLines(),
+ currentLocation = -1,
+ lastLocation,
+ blankCounter = 0,
+ location,
+ trimmedLines = lines.map(function(str) {
+ return str.trim();
+ });
+
+ // Aggregate and count blank lines
+ do {
+ lastLocation = currentLocation;
+ currentLocation = trimmedLines.indexOf("", currentLocation + 1);
+ if (lastLocation === currentLocation - 1) {
+ blankCounter++;
+ } else {
+ if (blankCounter >= numLines) {
+ location = {
+ line: lastLocation + 1,
+ column: lines[lastLocation].length
+ };
+ context.report(node, location, "Multiple blank lines not allowed.");
+ }
+
+ // Finally, reset the blank counter
+ blankCounter = 0;
+ }
+ } while (currentLocation !== -1);
+ }
+ };
+
+};
+
+},{}],103:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when re-assigning native objects
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var nativeObjects = ["Array", "Boolean", "Date", "decodeURI",
+ "decodeURIComponent", "encodeURI", "encodeURIComponent",
+ "Error", "eval", "EvalError", "Function", "isFinite",
+ "isNaN", "JSON", "Math", "Number", "Object", "parseInt",
+ "parseFloat", "RangeError", "ReferenceError", "RegExp",
+ "String", "SyntaxError", "TypeError", "URIError",
+ "Map", "NaN", "Set", "WeakMap", "Infinity", "undefined"];
+
+ return {
+
+ "AssignmentExpression": function(node) {
+ if (nativeObjects.indexOf(node.left.name) >= 0) {
+ context.report(node, node.left.name + " is a read-only native object.");
+ }
+ },
+
+ "VariableDeclarator": function(node) {
+ if (nativeObjects.indexOf(node.id.name) >= 0) {
+ context.report(node, "Redefinition of '{{nativeObject}}'.", { nativeObject: node.id.name });
+ }
+ }
+ };
+
+};
+
+},{}],104:[function(require,module,exports){
+/**
+ * @fileoverview A rule to disallow negated left operands of the `in` operator
+ * @author Michael Ficarra
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "BinaryExpression": function(node) {
+ if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") {
+ context.report(node, "The `in` expression's left operand is negated");
+ }
+ }
+ };
+
+};
+
+},{}],105:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag nested ternary expressions
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "ConditionalExpression": function(node) {
+ if (node.alternate.type === "ConditionalExpression" ||
+ node.consequent.type === "ConditionalExpression") {
+ context.report(node, "Do not nest ternary expressions");
+ }
+ }
+ };
+};
+
+},{}],106:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when using new Function
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "NewExpression": function(node) {
+ if (node.callee.name === "Function") {
+ context.report(node, "The Function constructor is eval.");
+ }
+ }
+ };
+
+};
+
+},{}],107:[function(require,module,exports){
+/**
+ * @fileoverview A rule to disallow calls to the Object constructor
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "NewExpression": function(node) {
+ if (node.callee.name === "Object") {
+ context.report(node, "The object literal notation {} is preferrable.");
+ }
+ }
+ };
+
+};
+
+},{}],108:[function(require,module,exports){
+/**
+ * @fileoverview Rule to disallow use of new operator with the `require` function
+ * @author Wil Moore III
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "NewExpression": function(node) {
+ if (node.callee.type === "Identifier" && node.callee.name === "require") {
+ context.report(node, "Unexpected use of new with require.");
+ }
+ }
+ };
+
+};
+
+},{}],109:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when using constructor for wrapper objects
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "NewExpression": function(node) {
+ var wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"];
+ if (wrapperObjects.indexOf(node.callee.name) > -1) {
+ context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name });
+ }
+ }
+ };
+
+};
+
+},{}],110:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag statements with function invocation preceded by
+ * "new" and not part of assignment
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "ExpressionStatement": function(node) {
+
+ if (node.expression.type === "NewExpression") {
+ context.report(node, "Do not use 'new' for side effects.");
+ }
+ }
+ };
+
+};
+
+},{}],111:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function
+ * @author James Allardice
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "CallExpression": function(node) {
+
+ if (node.callee.type === "Identifier") {
+ var name = node.callee.name;
+ if (name === "Math" || name === "JSON") {
+ context.report(node, "'{{name}}' is not a function.", { name: name });
+ }
+ }
+ }
+ };
+
+};
+
+},{}],112:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag octal escape sequences in string literals.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ if (typeof node.value !== "string") {
+ return;
+ }
+ var match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7])/),
+ octalDigit;
+
+ if (match) {
+ octalDigit = match[2];
+ context.report(node, "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.",
+ { octalDigit: octalDigit });
+ }
+ }
+
+ };
+
+};
+
+},{}],113:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when initializing octal literal
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) {
+ context.report(node, "Octal literals should not be used.");
+ }
+ }
+ };
+
+};
+
+},{}],114:[function(require,module,exports){
+/**
+ * @fileoverview Disallow string concatenation when using __dirname and __filename
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var MATCHER = /^__(?:dir|file)name$/;
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "BinaryExpression": function(node) {
+
+ var left = node.left,
+ right = node.right;
+
+ if (node.operator === "+" &&
+ ((left.type === "Identifier" && MATCHER.test(left.name)) ||
+ (right.type === "Identifier" && MATCHER.test(right.name)))
+ ) {
+
+ context.report(node, "Use path.join() or path.resolve() instead of + to create paths.");
+ }
+ }
+
+ };
+
+};
+
+},{}],115:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of unary increment and decrement operators.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "UpdateExpression": function(node) {
+ context.report(node, "Unary operator '" + node.operator + "' used.");
+ }
+
+ };
+
+};
+
+},{}],116:[function(require,module,exports){
+/**
+ * @fileoverview Disallow the use of process.env()
+ * @author Vignesh Anand
+ * @copyright 2014 Vignesh Anand. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "MemberExpression": function(node) {
+ var objectName = node.object.name,
+ propertyName = node.property.name;
+
+ if (objectName === "process" && !node.computed && propertyName && propertyName === "env") {
+ context.report(node, "Unexpected use of process.env.");
+ }
+
+ }
+
+ };
+
+};
+
+},{}],117:[function(require,module,exports){
+/**
+ * @fileoverview Disallow the use of process.exit()
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "CallExpression": function(node) {
+ var callee = node.callee;
+
+ if (callee.type === "MemberExpression" && callee.object.name === "process" &&
+ callee.property.name === "exit"
+ ) {
+ context.report(node, "Don't use process.exit(); throw an error instead.");
+ }
+ }
+
+ };
+
+};
+
+},{}],118:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag usage of __proto__ property
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "MemberExpression": function(node) {
+
+ if (node.property &&
+ (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) ||
+ (node.property.type === "Literal" && node.property.value === "__proto__")) {
+ context.report(node, "The '__proto__' property is deprecated.");
+ }
+ }
+ };
+
+};
+
+},{}],119:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when the same variable is declared more then once.
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ function findVariables() {
+ var scope = context.getScope();
+
+ scope.variables.forEach(function(variable) {
+ if (variable.identifiers && variable.identifiers.length > 1) {
+ variable.identifiers.sort(function(a, b) {
+ return a.range[1] - b.range[1];
+ });
+
+ for (var i = 1, l = variable.identifiers.length; i < l; i++) {
+ context.report(variable.identifiers[i], "{{a}} is already defined", {a: variable.name});
+ }
+ }
+ });
+ }
+
+ return {
+ "Program": findVariables,
+ "FunctionExpression": findVariables,
+ "FunctionDeclaration": findVariables
+ };
+};
+
+},{}],120:[function(require,module,exports){
+/**
+ * @fileoverview Rule to count multiple spaces in regular expressions
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ var token = context.getFirstToken(node),
+ nodeType = token.type,
+ nodeValue = token.value,
+ multipleSpacesRegex = /( {2,})+?/,
+ regexResults;
+
+ if (nodeType === "RegularExpression") {
+ regexResults = multipleSpacesRegex.exec(nodeValue);
+
+ if (regexResults !== null) {
+ context.report(node, "Spaces are hard to count. Use {" + regexResults[0].length + "}.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],121:[function(require,module,exports){
+/**
+ * @fileoverview Rule to disallow reserved words being used as keys
+ * @author Emil Bay
+ * @copyright 2014 Emil Bay. All rights reserved.
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var MESSAGE = "Reserved word '{{key}}' used as key.";
+
+ var reservedWords = [
+ "abstract",
+ "boolean", "break", "byte",
+ "case", "catch", "char", "class", "const", "continue",
+ "debugger", "default", "delete", "do", "double",
+ "else", "enum", "export", "extends",
+ "final", "finally", "float", "for", "function",
+ "goto",
+ "if", "implements", "import", "in", "instanceof", "int", "interface",
+ "long",
+ "native", "new",
+ "package", "private", "protected", "public",
+ "return",
+ "short", "static", "super", "switch", "synchronized",
+ "this", "throw", "throws", "transient", "try", "typeof",
+ "var", "void", "volatile",
+ "while", "with"
+ ];
+
+ return {
+
+ "ObjectExpression": function(node) {
+ node.properties.forEach(function(property) {
+
+ if (property.key.type === "Identifier") {
+ var keyName = property.key.name;
+
+ if (reservedWords.indexOf("" + keyName) !== -1) {
+ context.report(node, MESSAGE, { key: keyName });
+ }
+ }
+
+ });
+
+ }
+ };
+
+};
+
+},{}],122:[function(require,module,exports){
+/**
+ * @fileoverview Restrict usage of specified node modules.
+ * @author Christian Schulz
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+ // trim restricted module names
+ var restrictedModules = context.options;
+
+ // if no modules are restricted we don't need to check the CallExpressions
+ if (restrictedModules.length === 0) {
+ return {};
+ }
+
+ /**
+ * Function to check if a node is a string literal.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} If the node is a string literal.
+ */
+ function isString(node) {
+ return node && node.type === "Literal" && typeof node.value === "string";
+ }
+
+ /**
+ * Function to check if a node is a require call.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} If the node is a require call.
+ */
+ function isRequireCall(node) {
+ return node.callee.type === "Identifier" && node.callee.name === "require";
+ }
+
+ /**
+ * Function to check if a node has an argument that is an restricted module and return its name.
+ * @param {ASTNode} node The node to check
+ * @returns {undefined|String} restricted module name or undefined if node argument isn't restricted.
+ */
+ function getRestrictedModuleName(node) {
+ var moduleName;
+
+ // node has arguments and first argument is string
+ if (node.arguments.length && isString(node.arguments[0])) {
+ var argumentValue = node.arguments[0].value.trim();
+
+ // check if argument value is in restricted modules array
+ if (restrictedModules.indexOf(argumentValue) !== -1) {
+ moduleName = argumentValue;
+ }
+ }
+
+ return moduleName;
+ }
+
+ return {
+ "CallExpression": function (node) {
+ if (isRequireCall(node)) {
+ var restrictedModuleName = getRestrictedModuleName(node);
+
+ if (restrictedModuleName) {
+ context.report(node, "'{{moduleName}}' module is restricted from being used.", {
+ moduleName: restrictedModuleName
+ });
+ }
+ }
+ }
+ };
+};
+
+},{}],123:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when return statement contains assignment
+ * @author Ilya Volodin
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "ReturnStatement": function(node) {
+ if (node.argument && node.argument.type === "AssignmentExpression") {
+ context.report(node, "Return statement should not contain assignment.");
+ }
+ }
+ };
+
+};
+
+},{}],124:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when using javascript: urls
+ * @author Ilya Volodin
+ */
+/*jshint scripturl: true */
+/*eslint no-script-url: 0*/
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "Literal": function(node) {
+
+ var value;
+
+ if (node.value && typeof node.value === "string") {
+ value = node.value.toLowerCase();
+
+ if (value.indexOf("javascript:") === 0) {
+ context.report(node, "Script URL is a form of eval.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],125:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag comparison where left part is the same as the right
+ * part.
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ "use strict";
+
+ return {
+
+ "BinaryExpression": function(node) {
+ var operators = ["===", "==", "!==", "!=", ">", "<", ">=", "<="];
+ if (operators.indexOf(node.operator) > -1 &&
+ (node.left.type === "Identifier" && node.right.type === "Identifier" && node.left.name === node.right.name ||
+ node.left.type === "Literal" && node.right.type === "Literal" && node.left.value === node.right.value)) {
+ context.report(node, "Comparing to itself is potentially pointless.");
+ }
+ }
+ };
+
+};
+
+},{}],126:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of comma operator
+ * @author Brandon Mills
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ /**
+ * Parts of the grammar that are required to have parens.
+ */
+ var parenthesized = {
+ "DoWhileStatement": "test",
+ "IfStatement": "test",
+ "SwitchStatement": "discriminant",
+ "WhileStatement": "test",
+ "WithStatement": "object"
+
+ // Omitting CallExpression - commas are parsed as argument separators
+ // Omitting NewExpression - commas are parsed as argument separators
+ // Omitting ForInStatement - parts aren't individually parenthesised
+ // Omitting ForStatement - parts aren't individually parenthesised
+ };
+
+ /**
+ * Determines whether a node is required by the grammar to be wrapped in
+ * parens, e.g. the test of an if statement.
+ * @param {ASTNode} node - The AST node
+ * @returns {boolean} True if parens around node belong to parent node.
+ */
+ function requiresExtraParens(node) {
+ return node.parent && parenthesized[node.parent.type] != null &&
+ node === node.parent[parenthesized[node.parent.type]];
+ }
+
+ /**
+ * Check if a node is wrapped in parens.
+ * @param {ASTNode} node - The AST node
+ * @returns {boolean} True if the node has a paren on each side.
+ */
+ function isParenthesised(node) {
+ var previousToken = context.getTokenBefore(node),
+ nextToken = context.getTokenAfter(node);
+
+ return previousToken && nextToken &&
+ previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ /**
+ * Check if a node is wrapped in two levels of parens.
+ * @param {ASTNode} node - The AST node
+ * @returns {boolean} True if two parens surround the node on each side.
+ */
+ function isParenthesisedTwice(node) {
+ var previousToken = context.getTokenBefore(node, 1),
+ nextToken = context.getTokenAfter(node, 1);
+
+ return isParenthesised(node) && previousToken && nextToken &&
+ previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
+ nextToken.value === ")" && nextToken.range[0] >= node.range[1];
+ }
+
+ return {
+ "SequenceExpression": function(node) {
+ // Always allow sequences in for statement update
+ if (node.parent.type === "ForStatement" &&
+ (node === node.parent.init || node === node.parent.update)) {
+ return;
+ }
+
+ // Wrapping a sequence in extra parens indicates intent
+ if (requiresExtraParens(node)) {
+ if (isParenthesisedTwice(node)) {
+ return;
+ }
+ } else {
+ if (isParenthesised(node)) {
+ return;
+ }
+ }
+
+ context.report(node, "Unexpected use of comma operator.");
+ }
+ };
+
+};
+
+},{}],127:[function(require,module,exports){
+/**
+ * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1)
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var RESTRICTED = ["undefined", "NaN", "Infinity", "arguments", "eval"];
+
+ function checkForViolation(id) {
+ if (RESTRICTED.indexOf(id.name) > -1) {
+ context.report(id, "Shadowing of global property \"" + id.name + "\".");
+ }
+ }
+
+ return {
+ "VariableDeclarator": function(node) {
+ checkForViolation(node.id);
+ },
+ "FunctionExpression": function(node) {
+ if (node.id) {
+ checkForViolation(node.id);
+ }
+ [].map.call(node.params, checkForViolation);
+ },
+ "FunctionDeclaration": function(node) {
+ checkForViolation(node.id);
+ [].map.call(node.params, checkForViolation);
+ },
+ "CatchClause": function(node) {
+ checkForViolation(node.param);
+ }
+ };
+
+};
+
+},{}],128:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag on declaring variables already declared in the outer scope
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ /**
+ * Checks if a variable is contained in the list of given scope variables.
+ * @param {Object} variable The variable to check.
+ * @param {Array} scopeVars The scope variables to look for.
+ * @returns {boolean} Whether or not the variable is contains in the list of scope variables.
+ */
+ function isContainedInScopeVars(variable, scopeVars) {
+ return scopeVars.some(function (scopeVar) {
+ if (scopeVar.identifiers.length > 0) {
+ return variable.name === scopeVar.name;
+ }
+ return false;
+ });
+ }
+
+ /**
+ * Checks if the given variables are shadowed in the given scope.
+ * @param {Array} variables The variables to look for
+ * @param {Object} scope The scope to be checked.
+ * @returns {void}
+ */
+ function checkShadowsInScope(variables, scope) {
+ variables.forEach(function (variable) {
+ if (isContainedInScopeVars(variable, scope.variables)) {
+ context.report(variable.identifiers[0], "{{a}} is already declared in the upper scope.", {a: variable.name});
+ }
+ });
+ }
+
+ /**
+ * Checks the current context for shadowed variables.
+ * @returns {void}
+ */
+ function checkForShadows() {
+ var scope = context.getScope(),
+ variables = scope.variables;
+
+ // iterate through the array of variables and find duplicates with the upper scope
+ var upper = scope.upper;
+ while (upper) {
+ checkShadowsInScope(variables, upper);
+ upper = upper.upper;
+ }
+ }
+
+ return {
+ "FunctionDeclaration": checkForShadows,
+ "FunctionExpression": checkForShadows
+ };
+
+};
+
+},{}],129:[function(require,module,exports){
+/**
+ * @fileoverview Rule to require variables declared without whitespace before the lines semicolon
+ * @author Jonathan Kingston
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var semicolonWhitespace = /\s;$/;
+
+ return {
+ "VariableDeclaration": function(node) {
+ var source = context.getSource(node);
+ if (semicolonWhitespace.test(source)) {
+ context.report(node, "Variable declared with trailing whitespace before semicolon");
+ }
+ },
+ "ExpressionStatement": function(node) {
+ var source = context.getSource(node);
+ if (semicolonWhitespace.test(source)) {
+ context.report(node, "Expression called with trailing whitespace before semicolon");
+ }
+ }
+ };
+};
+
+},{}],130:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check that spaced function application
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ function detectOpenSpaces(node) {
+ var lastCalleeToken = context.getLastToken(node.callee);
+ var tokens = context.getTokens(node);
+ var i = tokens.indexOf(lastCalleeToken), l = tokens.length;
+ while (i < l && tokens[i].value !== "(") {
+ ++i;
+ }
+ if (i >= l) {
+ return;
+ }
+ // look for a space between the callee and the open paren
+ if (tokens[i - 1].range[1] !== tokens[i].range[0]) {
+ context.report(node, "Unexpected space between function name and paren.");
+ }
+ }
+
+ return {
+ "CallExpression": detectOpenSpaces,
+ "NewExpression": detectOpenSpaces
+ };
+
+};
+
+},{}],131:[function(require,module,exports){
+/**
+ * @fileoverview Disallow sparse arrays
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "ArrayExpression": function(node) {
+
+ var emptySpot = node.elements.indexOf(null) > -1;
+
+ if (emptySpot) {
+ context.report(node, "Unexpected comma in middle of array.");
+ }
+ }
+
+ };
+
+};
+
+},{}],132:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for properties whose identifier ends with the string Sync
+ * @author Matt DuVall
+ */
+
+/*jshint node:true*/
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "MemberExpression": function(node) {
+ var propertyName = node.property.name,
+ syncRegex = /.*Sync$/;
+
+ if (syncRegex.exec(propertyName) !== null) {
+ context.report(node, "Unexpected sync method: '" + propertyName + "'.");
+ }
+ }
+ };
+
+};
+
+},{}],133:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of ternary operators.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "ConditionalExpression": function(node) {
+ context.report(node, "Ternary operator used.");
+ }
+
+ };
+
+};
+
+},{}],134:[function(require,module,exports){
+/**
+ * @fileoverview Disallow trailing spaces at the end of lines.
+ * @author Nodeca Team
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var TRAILER = "[ \t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+$";
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Program": function checkTrailingSpaces(node) {
+
+ // Let's hack. Since Esprima does not return whitespace nodes,
+ // fetch the source code and do black magic via regexps.
+
+ var src = context.getSource(),
+ re = new RegExp(TRAILER, "mg"),
+ match, lines, location;
+
+ while ((match = re.exec(src)) !== null) {
+ lines = src.slice(0, re.lastIndex).split(/\r?\n/g);
+
+ location = {
+ line: lines.length,
+ column: lines[lines.length - 1].length - match[0].length + 1
+ };
+
+ // Passing node is a bit dirty, because message data will contain
+ // big text in `source`. But... who cares :) ?
+ // One more kludge will not make worse the bloody wizardry of this plugin.
+ context.report(node, location, "Trailing spaces not allowed.");
+ }
+ }
+
+ };
+};
+
+},{}],135:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when initializing to undefined
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "VariableDeclarator": function(node) {
+ var name = node.id.name;
+ var init = node.init && node.init.name;
+
+ if (init === "undefined") {
+ context.report(node, "It's not necessary to initialize '{{name}}' to undefined.", { name: name });
+ }
+ }
+ };
+
+};
+
+},{}],136:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag references to undeclared variables.
+ * @author Mark Macdonald
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+function isImplicitGlobal(variable) {
+ return variable.defs.every(function(def) {
+ return def.type === "ImplicitGlobalVariable";
+ });
+}
+
+/**
+ * Gets the declared variable, defined in `scope`, that `ref` refers to.
+ * @param {Scope} scope The scope in which to search.
+ * @param {Reference} ref The reference to find in the scope.
+ * @returns {Variable} The variable, or null if ref refers to an undeclared variable.
+ */
+function getDeclaredGlobalVariable(scope, ref) {
+ var declaredGlobal = null;
+ scope.variables.some(function(variable) {
+ if (variable.name === ref.identifier.name) {
+ // If it's an implicit global, it must have a `writeable` field (indicating it was declared)
+ if (!isImplicitGlobal(variable) || {}.hasOwnProperty.call(variable, "writeable")) {
+ declaredGlobal = variable;
+ return true;
+ }
+ }
+ return false;
+ });
+ return declaredGlobal;
+}
+
+/**
+ * Checks if the given node is the argument of a typeof operator.
+ * @param {ASTNode} node The AST node being checked.
+ * @returns {boolean} Whether or not the node is the argument of a typeof operator.
+ */
+function hasTypeOfOperator(node) {
+ var parent = node.parent;
+ return parent.type === "UnaryExpression" && parent.operator === "typeof";
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "Program:exit": function(/*node*/) {
+
+ var globalScope = context.getScope();
+
+ globalScope.through.forEach(function(ref) {
+ var variable = getDeclaredGlobalVariable(globalScope, ref),
+ name = ref.identifier.name;
+
+ if (hasTypeOfOperator(ref.identifier)) {
+ return;
+ }
+
+ if (!variable) {
+ context.report(ref.identifier, "'{{name}}' is not defined.", { name: name });
+ } else if (ref.isWrite() && variable.writeable === false) {
+ context.report(ref.identifier, "'{{name}}' is read only.", { name: name });
+ }
+ });
+ }
+ };
+
+};
+
+},{}],137:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag references to the undefined variable.
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+
+ "Identifier": function(node) {
+ if (node.name === "undefined") {
+ var parent = context.getAncestors().pop();
+ if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) {
+ context.report(node, "Unexpected use of undefined.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],138:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag trailing underscores in variable declarations.
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //-------------------------------------------------------------------------
+ // Helpers
+ //-------------------------------------------------------------------------
+
+ function hasTrailingUnderscore(identifier) {
+ var len = identifier.length;
+
+ return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_");
+ }
+
+ function isSpecialCaseIdentifierForMemberExpression(identifier) {
+ return identifier === "__proto__";
+ }
+
+ function isSpecialCaseIdentifierInVariableExpression(identifier) {
+ // Checks for the underscore library usage here
+ return identifier === "_";
+ }
+
+ function checkForTrailingUnderscoreInFunctionDeclaration(node) {
+ var identifier = node.id.name;
+
+ if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier)) {
+ context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
+ }
+ }
+
+ function checkForTrailingUnderscoreInVariableExpression(node) {
+ var identifier = node.id.name;
+
+ if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) &&
+ !isSpecialCaseIdentifierInVariableExpression(identifier)) {
+ context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
+ }
+ }
+
+ function checkForTrailingUnderscoreInMemberExpression(node) {
+ var identifier = node.property.name;
+
+ if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) &&
+ !isSpecialCaseIdentifierForMemberExpression(identifier)) {
+ context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "FunctionDeclaration": checkForTrailingUnderscoreInFunctionDeclaration,
+ "VariableDeclarator": checkForTrailingUnderscoreInVariableExpression,
+ "MemberExpression": checkForTrailingUnderscoreInMemberExpression
+ };
+
+};
+
+},{}],139:[function(require,module,exports){
+/**
+ * @fileoverview Checks for unreachable code due to return, throws, break, and continue.
+ * @author Joel Feenstra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+
+function report(context, node, unreachableType) {
+ var keyword;
+ switch (unreachableType) {
+ case "BreakStatement":
+ keyword = "break";
+ break;
+ case "ContinueStatement":
+ keyword = "continue";
+ break;
+ case "ReturnStatement":
+ keyword = "return";
+ break;
+ case "ThrowStatement":
+ keyword = "throw";
+ break;
+ default:
+ return;
+ }
+ context.report(node, "Found unexpected statement after a {{type}}.", { type: keyword });
+}
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ /**
+ * Checks if a node is an exception for no-unreachable because of variable/function hoisting
+ * @param {ASTNode} node The AST node to check.
+ * @returns {boolean} if the node doesn't trigger unreachable
+ * @private
+ */
+ function isUnreachableAllowed(node) {
+ return node.type === "FunctionDeclaration" ||
+ node.type === "VariableDeclaration" &&
+ node.declarations.every(function(declaration) {
+ return declaration.type === "VariableDeclarator" && declaration.init === null;
+ });
+ }
+
+ /*
+ * Verifies that the given node is the last node or followed exclusively by
+ * hoisted declarations
+ * @param {ASTNode} node Node that should be the last node
+ * @returns {void}
+ * @private
+ */
+ function checkNode(node) {
+ var parent = context.getAncestors().pop();
+ var field, i, sibling;
+
+ switch (parent.type) {
+ case "SwitchCase":
+ field = "consequent";
+ break;
+ case "Program":
+ case "BlockStatement":
+ field = "body";
+ break;
+ default:
+ return;
+ }
+
+ for (i = parent[field].length - 1; i >= 0; i--) {
+ sibling = parent[field][i];
+ if (sibling === node) {
+ return; // Found the last reachable statement, all done
+ }
+
+ if (!isUnreachableAllowed(sibling)) {
+ report(context, sibling, node.type);
+ }
+ }
+ }
+
+ return {
+ "ReturnStatement": checkNode,
+ "ThrowStatement": checkNode,
+ "ContinueStatement": checkNode,
+ "BreakStatement": checkNode
+ };
+
+};
+
+},{}],140:[function(require,module,exports){
+/**
+ * @fileoverview Flag expressions in statement position that do not side effect
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ /**
+ * @param {ASTNode} node - any node
+ * @returns {Boolean} whether the given node structurally represents a directive
+ */
+ function looksLikeDirective(node) {
+ return node.type === "ExpressionStatement" &&
+ node.expression.type === "Literal" && typeof node.expression.value === "string";
+ }
+
+ /**
+ * @param {Function} predicate - ([a] -> Boolean) the function used to make the determination
+ * @param {a[]} list - the input list
+ * @returns {a[]} the leading sequence of members in the given list that pass the given predicate
+ */
+ function takeWhile(predicate, list) {
+ for (var i = 0, l = list.length; i < l; ++i) {
+ if (!predicate(list[i])) {
+ break;
+ }
+ }
+ return [].slice.call(list, 0, i);
+ }
+
+ /**
+ * @param {ASTNode} node - a Program or BlockStatement node
+ * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body
+ */
+ function directives(node) {
+ return takeWhile(looksLikeDirective, node.body);
+ }
+
+ /**
+ * @param {ASTNode} node - any node
+ * @param {ASTNode[]} ancestors - the given node's ancestors
+ * @returns {Boolean} whether the given node is considered a directive in its current position
+ */
+ function isDirective(node, ancestors) {
+ var parent = ancestors[ancestors.length - 1],
+ grandparent = ancestors[ancestors.length - 2];
+ return (parent.type === "Program" || parent.type === "BlockStatement" && (grandparent.type === "FunctionExpression" || grandparent.type === "FunctionDeclaration")) &&
+ directives(parent).indexOf(node) >= 0;
+ }
+
+ return {
+ "ExpressionStatement": function(node) {
+
+ var type = node.expression.type,
+ ancestors = context.getAncestors();
+
+ if (
+ !/^(?:Assignment|Call|New|Update)Expression$/.test(type) &&
+ (type !== "UnaryExpression" || ["delete", "void"].indexOf(node.expression.operator) < 0) &&
+ !isDirective(node, ancestors)
+ ) {
+ context.report(node, "Expected an assignment or function call and instead saw an expression.");
+ }
+ }
+ };
+
+};
+
+},{}],141:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag declared but unused variables
+ * @author Ilya Volodin
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var config = {
+ vars: "all",
+ args: "after-used"
+ };
+
+ if (context.options[0]) {
+ if (typeof context.options[0] === "string") {
+ config.vars = context.options[0];
+ } else {
+ config.vars = context.options[0].vars || config.vars;
+ config.args = context.options[0].args || config.args;
+ }
+ }
+
+ var MESSAGE = "{{name}} is defined but never used";
+
+ /**
+ * @param {Reference} ref - an escope Reference
+ * @returns {Boolean} whether the given reference represents a read operation
+ */
+ function isReadRef(ref) {
+ return ref.isRead();
+ }
+
+ /**
+ * @param {Scope} scope - an escope Scope object
+ * @returns {Variable[]} most of the local variables with no read references
+ */
+ function unusedLocals(scope) {
+ var unused = [];
+ var variables = scope.variables;
+ if (scope.type !== "global") {
+ for (var i = 0, l = variables.length; i < l; ++i) {
+
+ // skip function expression names
+ if (scope.functionExpressionScope || variables[i].eslintJSXUsed) {
+ continue;
+ }
+ // skip implicit "arguments" variable
+ if (scope.type === "function" && variables[i].name === "arguments" && variables[i].identifiers.length === 0) {
+ continue;
+ }
+ var type = variables[i].defs[0].type;
+ // skip catch variables
+ if (type === "CatchClause") {
+ continue;
+ }
+ // if "args" option is "none", skip any parameter
+ if (config.args === "none" && type === "Parameter") {
+ continue;
+ }
+ // if "args" option is "after-used", skip all but the last parameter
+ if (config.args === "after-used" && type === "Parameter" && variables[i].defs[0].index < variables[i].defs[0].node.params.length - 1) {
+ continue;
+ }
+ if (variables[i].references.filter(isReadRef).length === 0) {
+ unused.push(variables[i]);
+ }
+ }
+ }
+ return [].concat.apply(unused, [].map.call(scope.childScopes, unusedLocals));
+ }
+
+ return {
+ "Program:exit": function(programNode) {
+ var globalScope = context.getScope();
+ var unused = unusedLocals(globalScope);
+ var i, l;
+
+ // determine unused globals
+ if (config.vars === "all") {
+ var unresolvedRefs = globalScope.through.filter(isReadRef).map(function(ref) {
+ return ref.identifier.name;
+ });
+ for (i = 0, l = globalScope.variables.length; i < l; ++i) {
+ if (unresolvedRefs.indexOf(globalScope.variables[i].name) < 0) {
+ unused.push(globalScope.variables[i]);
+ }
+ }
+ }
+
+ for (i = 0, l = unused.length; i < l; ++i) {
+ if (unused[i].eslintExplicitGlobal) {
+ context.report(programNode, MESSAGE, unused[i]);
+ } else if (unused[i].defs.length > 0) {
+ context.report(unused[i].identifiers[0], MESSAGE, unused[i]);
+ }
+ }
+ },
+
+ "JSXIdentifier": function(node) {
+ var scope = context.getScope(),
+ variables = scope.variables,
+ i,
+ len;
+
+ // mark JSXIdentifiers with a special flag
+ for (i = 0, len = variables.length; i < len; i++) {
+ if (variables[i].name === node.name) {
+ variables[i].eslintJSXUsed = true;
+ break;
+ }
+ }
+ }
+ };
+
+};
+
+},{}],142:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of variables before they are defined
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+var NO_FUNC = "nofunc";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ function findDeclaration(name, scope) {
+ // try searching in the current scope first
+ for (var i = 0, l = scope.variables.length; i < l; i++) {
+ if (scope.variables[i].name === name) {
+ return scope.variables[i];
+ }
+ }
+ // check if there's upper scope and call recursivly till we find the variable
+ if (scope.upper) {
+ return findDeclaration(name, scope.upper);
+ }
+ }
+
+ function findVariables() {
+ var scope = context.getScope();
+ var typeOption = context.options[0];
+
+ function checkLocationAndReport(reference, declaration) {
+ if (typeOption !== NO_FUNC || declaration.defs[0].type !== "FunctionName") {
+ if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) {
+ context.report(reference.identifier, "{{a}} was used before it was defined", {a: reference.identifier.name});
+ }
+ }
+ }
+
+ scope.references.forEach(function(reference) {
+ // if the reference is resolved check for declaration location
+ // if not, it could be function invocation, try to find manually
+ if (reference.resolved && reference.resolved.identifiers.length > 0) {
+ checkLocationAndReport(reference, reference.resolved);
+ } else {
+ var declaration = findDeclaration(reference.identifier.name, scope);
+ // if there're no identifiers, this is a global environment variable
+ if (declaration && declaration.identifiers.length !== 0) {
+ checkLocationAndReport(reference, declaration);
+ }
+ }
+ });
+ }
+
+ return {
+ "Program": findVariables,
+ "FunctionExpression": findVariables,
+ "FunctionDeclaration": findVariables
+ };
+};
+
+},{}],143:[function(require,module,exports){
+/**
+ * @fileoverview Rule to check for the usage of var.
+ * @author Jamund Ferguson
+ * @copyright 2014 Jamund Ferguson. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ return {
+ "VariableDeclaration": function (node) {
+ if (node.kind === "var") {
+ context.report(node, "Unexpected var, use let or const instead.");
+ }
+ }
+
+ };
+
+};
+
+},{}],144:[function(require,module,exports){
+/**
+ * @fileoverview Rule to disallow use of void operator.
+ * @author Mike Sidorov
+ * @copyright 2014 Mike Sidorov. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "UnaryExpression": function(node) {
+ if (node.operator === "void") {
+ context.report(node, "Expected 'undefined' and instead saw 'void'.");
+ }
+ }
+ };
+
+};
+
+},{}],145:[function(require,module,exports){
+/**
+ * @fileoverview Rule that warns about used warning comments
+ * @author Alexander Schmidt
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+ "use strict";
+
+ var configuration = context.options[0] || {},
+ warningTerms = configuration.terms || ["todo", "fixme", "xxx"],
+ location = configuration.location || "start";
+
+ /**
+ * Prepares a specified comment for being checked.
+ * @param {String} comment The comment to prepare.
+ * @returns {String} The specified comment prepared for being checked.
+ */
+ function prepareCommentForChecking(comment) {
+ var commentToCheck;
+
+ commentToCheck = comment.toLowerCase();
+ commentToCheck = commentToCheck.trim();
+
+ return commentToCheck;
+ }
+
+ /**
+ * Checks if the specified comment starts with a specified term.
+ * @param {String} commentToCheck The comment to check.
+ * @param {String} lowerCaseTerm The term to search for.
+ * @returns {Boolean} True if the comment started with the specified term, else false.
+ */
+ function commentStartsWithTerm(commentToCheck, lowerCaseTerm) {
+ return commentToCheck.indexOf(lowerCaseTerm) === 0;
+ }
+
+ /**
+ * Checks if the specified comment contains a specified term at any location.
+ * @param {String} commentToCheck The comment to check.
+ * @param {String} lowerCaseTerm The term to search for.
+ * @returns {Boolean} True if the term was contained in the comment, else false.
+ */
+ function commentContainsTerm(commentToCheck, lowerCaseTerm) {
+ return commentToCheck.indexOf(lowerCaseTerm) !== -1;
+ }
+
+
+ /**
+ * Checks the specified comment for matches of the configured warning terms and returns the matches.
+ * @param {String} comment The comment which is checked.
+ * @returns {Array} All matched warning terms for this comment.
+ */
+ function commentContainsWarningTerm(comment) {
+ var matches = [];
+
+ warningTerms.forEach(function (term) {
+ var lowerCaseTerm = term.toLowerCase(),
+ commentToCheck = prepareCommentForChecking(comment);
+
+ if (location === "start") {
+ if (commentStartsWithTerm(commentToCheck, lowerCaseTerm)) {
+ matches.push(term);
+ }
+ } else if (location === "anywhere") {
+ if (commentContainsTerm(commentToCheck, lowerCaseTerm)) {
+ matches.push(term);
+ }
+ }
+ });
+
+ return matches;
+ }
+
+ /**
+ * Checks the specified node for matching warning comments and reports them.
+ * @param {ASTNode} node The AST node being checked.
+ * @returns {void} undefined.
+ */
+ function checkComment(node) {
+ var matches = commentContainsWarningTerm(node.value);
+
+ matches.forEach(function (matchedTerm) {
+ context.report(node, "Unexpected " + matchedTerm + " comment.");
+ });
+ }
+
+ return {
+ "BlockComment": checkComment,
+ "LineComment": checkComment
+ };
+};
+
+},{}],146:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of with statement
+ * @author Nicholas C. Zakas
+ */
+
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "WithStatement": function(node) {
+ context.report(node, "Unexpected use of 'with' statement.");
+ }
+ };
+
+};
+
+},{}],147:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag wrapping non-iife in parens
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "FunctionExpression": function(node) {
+ var ancestors = context.getAncestors(),
+ previousToken, nextToken;
+
+ if (!/CallExpression|NewExpression/.test(ancestors.pop().type)) {
+ previousToken = context.getTokenBefore(node);
+ nextToken = context.getTokenAfter(node);
+ if (previousToken.value === "(" && nextToken.value === ")") {
+ context.report(node, "Wrapping non-IIFE function literals in parens is unnecessary.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],148:[function(require,module,exports){
+/**
+ * @fileoverview A rule to ensure the use of a single variable declaration.
+ * @author Ian Christian Myers
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ var functionStack = [];
+
+ function startFunction() {
+ functionStack.push(false);
+ }
+
+ function endFunction() {
+ functionStack.pop();
+ }
+
+ function checkDeclarations(node) {
+ if (functionStack[functionStack.length - 1]) {
+ context.report(node, "Combine this with the previous 'var' statement.");
+ } else {
+ functionStack[functionStack.length - 1] = true;
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "Program": startFunction,
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression": startFunction,
+
+ "VariableDeclaration": checkDeclarations,
+
+ "Program:exit": endFunction,
+ "FunctionDeclaration:exit": endFunction,
+ "FunctionExpression:exit": endFunction
+ };
+
+};
+
+},{}],149:[function(require,module,exports){
+/**
+ * @fileoverview Rule to replace assignment expressions with operator assignment
+ * @author Brandon Mills
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/**
+ * Checks whether an operator is commutative and has an operator assignment
+ * shorthand form.
+ * @param {string} operator Operator to check.
+ * @returns {boolean} True if the operator is commutative and has a
+ * shorthand form.
+ */
+function isCommutativeOperatorWithShorthand(operator) {
+ return ["*", "&", "^", "|"].indexOf(operator) >= 0;
+}
+
+/**
+ * Checks whether an operator is not commuatative and has an operator assignment
+ * shorthand form.
+ * @param {string} operator Operator to check.
+ * @returns {boolean} True if the operator is not commuatative and has
+ * a shorthand form.
+ */
+function isNonCommutativeOperatorWithShorthand(operator) {
+ return ["+", "-", "/", "%", "<<", ">>", ">>>"].indexOf(operator) >= 0;
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+/**
+ * Checks whether two expressions reference the same value. For example:
+ * a = a
+ * a.b = a.b
+ * a[0] = a[0]
+ * a['b'] = a['b']
+ * @param {ASTNode} a Left side of the comparison.
+ * @param {ASTNode} b Right side of the comparison.
+ * @returns {boolean} True if both sides match and reference the same value.
+ */
+function same(a, b) {
+ if (a.type !== b.type) {
+ return false;
+ }
+
+ switch (a.type) {
+ case "Identifier":
+ return a.name === b.name;
+ case "Literal":
+ return a.value === b.value;
+ case "MemberExpression":
+ // x[0] = x[0]
+ // x[y] = x[y]
+ // x.y = x.y
+ return same(a.object, b.object) && same(a.property, b.property);
+ default:
+ return false;
+ }
+}
+
+module.exports = function(context) {
+
+ /**
+ * Ensures that an assignment uses the shorthand form where possible.
+ * @param {ASTNode} node An AssignmentExpression node.
+ * @returns {void}
+ */
+ function verify(node) {
+ var expr, left, operator;
+
+ if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
+ return;
+ }
+
+ left = node.left;
+ expr = node.right;
+ operator = expr.operator;
+
+ if (isCommutativeOperatorWithShorthand(operator)) {
+ if (same(left, expr.left) || same(left, expr.right)) {
+ context.report(node, "Assignment can be replaced with operator assignment.");
+ }
+ } else if (isNonCommutativeOperatorWithShorthand(operator)) {
+ if (same(left, expr.left)) {
+ context.report(node, "Assignment can be replaced with operator assignment.");
+ }
+ }
+ }
+
+ /**
+ * Warns if an assignment expression uses operator assignment shorthand.
+ * @param {ASTNode} node An AssignmentExpression node.
+ * @returns {void}
+ */
+ function prohibit(node) {
+ if (node.operator !== "=") {
+ context.report(node, "Unexpected operator assignment shorthand.");
+ }
+ }
+
+ return {
+ "AssignmentExpression": context.options[0] !== "never" ? verify : prohibit
+ };
+
+};
+
+},{}],150:[function(require,module,exports){
+/**
+ * @fileoverview A rule to ensure blank lines within blocks.
+ * @author Mathias Schreck
+ * @copyright 2014 Mathias Schreck. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+ var requirePadding = context.options[0] !== "never";
+
+ /**
+ * Checks if the given non empty block node has a blank line before its first child node.
+ * @param {ASTNode} node The AST node of a BlockStatement.
+ * @returns {boolean} Whether or not the block starts with a blank line.
+ */
+ function isNonEmptyBlockTopPadded(node) {
+ var blockStart = node.loc.start.line,
+ first = node.body[0],
+ firstLine = first.loc.start.line,
+ expectedFirstLine = blockStart + 2,
+ leadingComments = context.getComments(first).leading;
+
+ if (leadingComments.length > 0) {
+ firstLine = leadingComments[0].loc.start.line;
+ }
+
+ return expectedFirstLine <= firstLine;
+ }
+
+ /**
+ * Checks if the given non empty block node has a blank line after its last child node.
+ * @param {ASTNode} node The AST node of a BlockStatement.
+ * @returns {boolean} Whether or not the block ends with a blank line.
+ */
+ function isNonEmptyBlockBottomPadded(node) {
+ var blockEnd = node.loc.end.line,
+ last = node.body[node.body.length - 1],
+ lastLine = last.loc.end.line,
+ expectedLastLine = blockEnd - 2,
+ trailingComments = context.getComments(last).trailing;
+
+ if (trailingComments.length > 0) {
+ lastLine = trailingComments[trailingComments.length - 1].loc.end.line;
+ }
+
+ return lastLine <= expectedLastLine;
+ }
+
+ /**
+ * Checks if the given non empty block node starts AND ends with a blank line.
+ * @param {ASTNode} node The AST node of a BlockStatement.
+ * @returns {boolean} Whether or not the block starts and ends with a blank line.
+ */
+ function isNonEmptyBlockPadded(node) {
+ return isNonEmptyBlockTopPadded(node) && isNonEmptyBlockBottomPadded(node);
+ }
+
+ /**
+ * Checks if the given non empty block node starts OR ends with a blank line.
+ * @param {ASTNode} node The AST node of a BlockStatement.
+ * @returns {boolean} Whether or not the block starts and ends with a blank line.
+ */
+ function hasNonEmptyBlockExtraPadding(node) {
+ return isNonEmptyBlockTopPadded(node) || isNonEmptyBlockBottomPadded(node);
+ }
+
+ /**
+ * Checks the given BlockStatement node to be padded if the block is not empty.
+ * @param {ASTNode} node The AST node of a BlockStatement.
+ * @returns {void} undefined.
+ */
+ function checkPadding(node) {
+ if (node.body.length > 0) {
+ if (requirePadding) {
+ if (!isNonEmptyBlockPadded(node)) {
+ context.report(node, "Block must be padded by blank lines.");
+ }
+ } else {
+ if (hasNonEmptyBlockExtraPadding(node)) {
+ context.report(node, "Block must not be padded by blank lines.");
+ }
+ }
+ }
+ }
+
+ return {
+ "BlockStatement": checkPadding
+ };
+
+};
+
+},{}],151:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag non-quoted property names in object literals.
+ * @author Mathias Bynens
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var espree = require("espree");
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var MODE = context.options[0];
+
+ /**
+ * Ensures that a property's key is quoted only when necessary
+ * @param {ASTNode} node Property AST node
+ * @returns {void}
+ */
+ function asNeeded(node) {
+ var key = node.key,
+ tokens;
+
+ if (key.type === "Literal" && typeof key.value === "string") {
+ try {
+ tokens = espree.tokenize(key.value);
+ } catch (e) {
+ return;
+ }
+
+ if (tokens.length === 1 &&
+ (["Identifier", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 ||
+ (tokens[0].type === "Numeric" && "" + +tokens[0].value === tokens[0].value))
+ ) {
+ context.report(node, "Unnecessarily quoted property `{{value}}` found.", key);
+ }
+ }
+ }
+
+ /**
+ * Ensures that a property's key is quoted
+ * @param {ASTNode} node Property AST node
+ * @returns {void}
+ */
+ function always(node) {
+ var key = node.key;
+
+ if (!(key.type === "Literal" && typeof key.value === "string")) {
+ context.report(node, "Unquoted property `{{key}}` found.", {
+ key: key.name || key.value
+ });
+ }
+ }
+
+ return {
+ "Property": MODE === "as-needed" ? asNeeded : always
+ };
+
+};
+
+},{"espree":13}],152:[function(require,module,exports){
+/**
+ * @fileoverview A rule to choose between single and double quote marks
+ * @author Matt DuVall , Brandon Payton
+ */
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+var QUOTE_SETTINGS = {
+ "double": {
+ quote: "\"",
+ alternateQuote: "'",
+ description: "doublequote"
+ },
+ "single": {
+ quote: "'",
+ alternateQuote: "\"",
+ description: "singlequote"
+ }
+};
+
+var AVOID_ESCAPE = "avoid-escape";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ /**
+ * Validate that a string passed in is surrounded by the specified character
+ * @param {string} val The text to check.
+ * @param {string} character The character to see if it's surrounded by.
+ * @returns {boolean} True if the text is surrounded by the character, false if not.
+ * @private
+ */
+ function isSurroundedBy(val, character) {
+ return val[0] === character && val[val.length - 1] === character;
+ }
+
+ /**
+ * Determines if a given node is part of JSX syntax.
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} True if the node is a JSX node, false if not.
+ * @private
+ */
+ function isJSXElement(node) {
+ return node.type.indexOf("JSX") === 0;
+ }
+
+ return {
+
+ "Literal": function(node) {
+ var val = node.value,
+ rawVal = node.raw,
+ quoteOption = context.options[0],
+ settings = QUOTE_SETTINGS[quoteOption],
+ avoidEscape = context.options[1] === AVOID_ESCAPE,
+ isValid;
+
+ if (settings && typeof val === "string") {
+ isValid = isJSXElement(node.parent) || isSurroundedBy(rawVal, settings.quote);
+
+ if (!isValid && avoidEscape) {
+ isValid = isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
+ }
+
+ if (!isValid) {
+ context.report(node, "Strings must use " + settings.description + ".");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],153:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag use of parseInt without a radix argument
+ * @author James Allardice
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+ "CallExpression": function(node) {
+
+ var radix;
+
+ if (node.callee.name === "parseInt") {
+
+ if (node.arguments.length < 2) {
+ context.report(node, "Missing radix parameter.");
+ } else {
+
+ radix = node.arguments[1];
+
+ // don't allow non-numeric literals or undefined
+ if ((radix.type === "Literal" && typeof radix.value !== "number") ||
+ (radix.type === "Identifier" && radix.name === "undefined")
+ ) {
+ context.report(node, "Invalid radix parameter.");
+ }
+ }
+
+ }
+ }
+ };
+
+};
+
+},{}],154:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag missing semicolons.
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+module.exports = function(context) {
+
+ var OPT_OUT_PATTERN = /[\[\(\/\+\-]/;
+
+ var always = context.options[0] !== "never";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Check if a semicolon is unnecessary, only true if:
+ * - next token is on a new line and is not one of the opt-out tokens
+ * - next token is a valid statement divider
+ * @param {Token} lastToken last token of current node.
+ * @param {Token} nextToken next token after current node.
+ * @returns {boolean} whether the semicolon is unnecessary.
+ */
+ function isUnnecessarySemicolon(lastToken, nextToken) {
+
+ var lastTokenLine = lastToken.loc.end.line,
+ nextTokenLine = nextToken && nextToken.loc.start.line,
+ isOptOutToken = nextToken && OPT_OUT_PATTERN.test(nextToken.value),
+ isDivider = nextToken && (nextToken.value === "}" || nextToken.value === ";");
+
+ return (lastTokenLine !== nextTokenLine && !isOptOutToken) || isDivider;
+ }
+
+ /**
+ * Checks a node to see if it's followed by a semicolon.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ */
+ function checkForSemicolon(node) {
+ var lastToken = context.getLastToken(node),
+ nextToken = context.getTokenAfter(node);
+
+ if (always) {
+ if (lastToken.type !== "Punctuator" || lastToken.value !== ";") {
+ context.report(node, lastToken.loc.end, "Missing semicolon.");
+ }
+ } else {
+ if (lastToken.type === "Punctuator" &&
+ lastToken.value === ";" &&
+ isUnnecessarySemicolon(lastToken, nextToken)
+ ) {
+ context.report(node, node.loc.end, "Extra semicolon.");
+ }
+ }
+ }
+
+ /**
+ * Checks to see if there's a semicolon after a variable declaration.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ */
+ function checkForSemicolonForVariableDeclaration(node) {
+
+ var ancestors = context.getAncestors(),
+ parentIndex = ancestors.length - 1,
+ parent = ancestors[parentIndex];
+
+ if ((parent.type !== "ForStatement" || parent.init !== node) &&
+ (parent.type !== "ForInStatement" || parent.left !== node)
+ ) {
+ checkForSemicolon(node);
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "VariableDeclaration": checkForSemicolonForVariableDeclaration,
+ "ExpressionStatement": checkForSemicolon,
+ "ReturnStatement": checkForSemicolon,
+ "DebuggerStatement": checkForSemicolon,
+ "BreakStatement": checkForSemicolon,
+ "ContinueStatement": checkForSemicolon,
+ "EmptyStatement": function (node) {
+ var lastToken, nextToken;
+
+ if (!always) {
+ lastToken = context.getLastToken(node);
+ nextToken = context.getTokenAfter(node) || context.getLastToken(node);
+
+ if (isUnnecessarySemicolon(lastToken, nextToken)) {
+ context.report(node, "Extra semicolon.");
+ }
+ }
+
+
+ }
+ };
+
+};
+
+},{}],155:[function(require,module,exports){
+/**
+ * @fileoverview Rule to require sorting of variables within a single Variable Declaration block
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ var configuration = context.options[0] || {},
+ ignoreCase = configuration.ignoreCase || false;
+
+ return {
+ "VariableDeclaration": function(node) {
+ node.declarations.reduce(function(memo, decl) {
+ var lastVariableName = memo.id.name,
+ currenVariableName = decl.id.name;
+
+ if (ignoreCase) {
+ lastVariableName = lastVariableName.toLowerCase();
+ currenVariableName = currenVariableName.toLowerCase();
+ }
+
+ if (currenVariableName < lastVariableName) {
+ context.report(decl, "Variables within the same declaration block should be sorted alphabetically");
+ return memo;
+ } else {
+ return decl;
+ }
+ }, node.declarations[0]);
+ }
+ };
+};
+
+},{}],156:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce consistent spacing after function names
+ * @author Roberto Vidal
+ * @copyright 2014 Roberto Vidal. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var requiresSpace = context.options[0] === "always";
+
+ /**
+ * Reports if the give named function node has the correct spacing after its name
+ *
+ * @param {ASTNode} node The node to which the potential problem belongs.
+ * @returns {void}
+ */
+ function check(node) {
+ var tokens = context.getFirstTokens(node, 3),
+ hasSpace = tokens[1].range[1] < tokens[2].range[0];
+
+ if (hasSpace !== requiresSpace) {
+ context.report(node, "Function name \"{{name}}\" must {{not}}be followed by whitespace.", {
+ name: node.id.name,
+ not: requiresSpace ? "" : "not "
+ });
+ }
+ }
+
+ return {
+ "FunctionDeclaration": check,
+ "FunctionExpression": function (node) {
+ if (node.id) {
+ check(node);
+ }
+ }
+ };
+
+};
+
+},{}],157:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce the number of spaces after certain keywords
+ * @author Nick Fisher
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ // unless the first option is `"never"`, then a space is required
+ var requiresSpace = context.options[0] !== "never",
+ config = context.options[1] || { checkFunctionKeyword: false };
+
+ /**
+ * Check if the separation of two adjacent tokens meets the spacing rules, and report a problem if not.
+ *
+ * @param {ASTNode} node The node to which the potential problem belongs.
+ * @param {Token} left The first token.
+ * @param {Token} right The second token
+ * @returns {void}
+ */
+ function checkTokens(node, left, right) {
+ var hasSpace = left.range[1] < right.range[0],
+ value = left.value;
+
+ if (hasSpace !== requiresSpace) {
+ context.report(node, "Keyword \"{{value}}\" must {{not}}be followed by whitespace.", {
+ value: value,
+ not: requiresSpace ? "" : "not "
+ });
+ }
+ }
+
+ /**
+ * Check if the given node (`if`, `for`, `while`, etc), has the correct spacing after it.
+ * @param {ASTNode} node The node to check.
+ * @returns {void}
+ */
+ function check(node) {
+ var tokens = context.getFirstTokens(node, 2);
+ checkTokens(node, tokens[0], tokens[1]);
+ }
+
+ return {
+ "IfStatement": function (node) {
+ check(node);
+ // check the `else`
+ if (node.alternate && node.alternate.type !== "IfStatement") {
+ checkTokens(node.alternate, context.getTokenBefore(node.alternate), context.getFirstToken(node.alternate));
+ }
+ },
+ "ForStatement": check,
+ "ForOfStatement": check,
+ "ForInStatement": check,
+ "WhileStatement": check,
+ "DoWhileStatement": function (node) {
+ check(node);
+ // check the `while`
+ var whileTokens = context.getTokensBefore(node.test, 2);
+ checkTokens(node, whileTokens[0], whileTokens[1]);
+ },
+ "SwitchStatement": check,
+ "TryStatement": function (node) {
+ check(node);
+ // check the `finally`
+ if (node.finalizer) {
+ checkTokens(node.finalizer, context.getTokenBefore(node.finalizer), context.getFirstToken(node.finalizer));
+ }
+ },
+ "CatchStatement": check,
+ "WithStatement": check,
+ "FunctionExpression": function (node) {
+ if (config.checkFunctionKeyword) {
+ check(node);
+ }
+ }
+ };
+};
+
+},{}],158:[function(require,module,exports){
+/**
+ * @fileoverview A rule to ensure whitespace before blocks.
+ * @author Mathias Schreck
+ * @copyright 2014 Mathias Schreck. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+ var requireSpace = context.options[0] !== "never";
+
+ /**
+ * Determines whether two adjacent tokens are have whitespace between them.
+ * @param {Object} left - The left token object.
+ * @param {Object} right - The right token object.
+ * @returns {boolean} Whether or not there is space between the tokens.
+ */
+ function isSpaced(left, right) {
+ return left.range[1] < right.range[0];
+ }
+
+ /**
+ * Determines whether two adjacent tokens are on the same line.
+ * @param {Object} left - The left token object.
+ * @param {Object} right - The right token object.
+ * @returns {boolean} Whether or not the tokens are on the same line.
+ */
+ function isSameLine(left, right) {
+ return left.loc.start.line === right.loc.start.line;
+ }
+
+ /**
+ * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line.
+ * @param {ASTNode|Token} node The AST node of a BlockStatement.
+ * @returns {void} undefined.
+ */
+ function checkPrecedingSpace(node) {
+ var precedingToken = context.getTokenBefore(node),
+ hasSpace;
+
+ if (precedingToken && isSameLine(precedingToken, node)) {
+ hasSpace = isSpaced(precedingToken, node);
+
+ if (requireSpace) {
+ if (!hasSpace) {
+ context.report(node, "Missing space before opening brace.");
+ }
+ } else {
+ if (hasSpace) {
+ context.report(node, "Unexpected space before opening brace.");
+ }
+ }
+ }
+ }
+
+ /**
+ * Checks if the CaseBlock of an given SwitchStatement node has a preceding space.
+ * @param {ASTNode} node The node of a SwitchStatement.
+ * @returns {void} undefined.
+ */
+ function checkSpaceBeforeCaseBlock(node) {
+ var cases = node.cases,
+ firstCase,
+ openingBrace;
+
+ if (cases.length > 0) {
+ firstCase = cases[0];
+ openingBrace = context.getTokenBefore(firstCase);
+ } else {
+ openingBrace = context.getLastToken(node, 1);
+ }
+
+ checkPrecedingSpace(openingBrace);
+ }
+
+ return {
+ "BlockStatement": checkPrecedingSpace,
+ "SwitchStatement": checkSpaceBeforeCaseBlock
+ };
+
+};
+
+},{}],159:[function(require,module,exports){
+/**
+ * @fileoverview Disallows or enforces spaces inside of brackets.
+ * @author Ian Christian Myers
+ * @copyright 2014 Brandyn Bennett. All rights reserved.
+ * @copyright 2014 Michael Ficarra. No rights reserved.
+ * @copyright 2014 Vignesh Anand. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ var spaced = context.options[0] === "always";
+
+ /**
+ * Determines whether an option is set, relative to the spacing option.
+ * If spaced is "always", then check whether option is set to false.
+ * If spaced is "never", then check whether option is set to true.
+ * @param {Object} option - The option to exclude.
+ * @returns {boolean} Whether or not the property is excluded.
+ */
+ function isOptionSet(option) {
+ return context.options[1] != null ? context.options[1][option] === !spaced : false;
+ }
+
+ var options = {
+ spaced: spaced,
+ singleElementException: isOptionSet("singleValue"),
+ objectsInArraysException: isOptionSet("objectsInArrays"),
+ arraysInArraysException: isOptionSet("arraysInArrays"),
+ arraysInObjectsException: isOptionSet("arraysInObjects"),
+ objectsInObjectsException: isOptionSet("objectsInObjects"),
+ propertyNameException: isOptionSet("propertyName")
+ };
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Determines whether two adjacent tokens are have whitespace between them.
+ * @param {Object} left - The left token object.
+ * @param {Object} right - The right token object.
+ * @returns {boolean} Whether or not there is space between the tokens.
+ */
+ function isSpaced(left, right) {
+ return left.range[1] < right.range[0];
+ }
+
+ /**
+ * Determines whether two adjacent tokens are on the same line.
+ * @param {Object} left - The left token object.
+ * @param {Object} right - The right token object.
+ * @returns {boolean} Whether or not the tokens are on the same line.
+ */
+ function isSameLine(left, right) {
+ return left.loc.start.line === right.loc.start.line;
+ }
+
+ /**
+ * Reports that there shouldn't be a space after the first token
+ * @param {ASTNode} node - The node to report in the event of an error.
+ * @param {Token} token - The token to use for the report.
+ * @returns {void}
+ */
+ function reportNoBeginningSpace(node, token) {
+ context.report(node, token.loc.start,
+ "There should be no space after '" + token.value + "'");
+ }
+
+ /**
+ * Reports that there shouldn't be a space before the last token
+ * @param {ASTNode} node - The node to report in the event of an error.
+ * @param {Token} token - The token to use for the report.
+ * @returns {void}
+ */
+ function reportNoEndingSpace(node, token) {
+ context.report(node, token.loc.start,
+ "There should be no space before '" + token.value + "'");
+ }
+
+ /**
+ * Reports that there should be a space after the first token
+ * @param {ASTNode} node - The node to report in the event of an error.
+ * @param {Token} token - The token to use for the report.
+ * @returns {void}
+ */
+ function reportRequiredBeginningSpace(node, token) {
+ context.report(node, token.loc.start,
+ "A space is required after '" + token.value + "'");
+ }
+
+ /**
+ * Reports that there should be a space before the last token
+ * @param {ASTNode} node - The node to report in the event of an error.
+ * @param {Token} token - The token to use for the report.
+ * @returns {void}
+ */
+ function reportRequiredEndingSpace(node, token) {
+ context.report(node, token.loc.start,
+ "A space is required before '" + token.value + "'");
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ MemberExpression: function(node) {
+ if (!node.computed) {
+ return;
+ }
+
+ var property = node.property,
+ before = context.getTokenBefore(property),
+ first = context.getFirstToken(property),
+ last = context.getLastToken(property),
+ after = context.getTokenAfter(property);
+
+ var propertyNameMustBeSpaced = options.propertyNameException ?
+ !options.spaced : options.spaced;
+
+ if (isSameLine(before, first)) {
+ if (propertyNameMustBeSpaced) {
+ if (!isSpaced(before, first) && isSameLine(before, first)) {
+ reportRequiredBeginningSpace(node, before);
+ }
+ } else {
+ if (isSpaced(before, first)) {
+ reportNoBeginningSpace(node, before);
+ }
+ }
+ }
+
+ if (isSameLine(last, after)) {
+ if (propertyNameMustBeSpaced) {
+ if (!isSpaced(last, after) && isSameLine(last, after)) {
+ reportRequiredEndingSpace(node, after);
+ }
+ } else {
+ if (isSpaced(last, after)) {
+ reportNoEndingSpace(node, after);
+ }
+ }
+ }
+ },
+
+ ArrayExpression: function(node) {
+ if (node.elements.length === 0) {
+ return;
+ }
+
+ var first = context.getFirstToken(node),
+ second = context.getFirstToken(node, 1),
+ penultimate = context.getLastToken(node, 1),
+ last = context.getLastToken(node);
+
+ var openingBracketMustBeSpaced =
+ options.objectsInArraysException && second.value === "{" ||
+ options.arraysInArraysException && second.value === "[" ||
+ options.singleElementException && node.elements.length === 1
+ ? !options.spaced : options.spaced;
+
+ var closingBracketMustBeSpaced =
+ options.objectsInArraysException && penultimate.value === "}" ||
+ options.arraysInArraysException && penultimate.value === "]" ||
+ options.singleElementException && node.elements.length === 1
+ ? !options.spaced : options.spaced;
+
+ if (isSameLine(first, second)) {
+ if (openingBracketMustBeSpaced && !isSpaced(first, second)) {
+ reportRequiredBeginningSpace(node, first);
+ }
+ if (!openingBracketMustBeSpaced && isSpaced(first, second)) {
+ reportNoBeginningSpace(node, first);
+ }
+ }
+
+ if (isSameLine(penultimate, last)) {
+ if (closingBracketMustBeSpaced && !isSpaced(penultimate, last)) {
+ reportRequiredEndingSpace(node, last);
+ }
+ if (!closingBracketMustBeSpaced && isSpaced(penultimate, last)) {
+ reportNoEndingSpace(node, last);
+ }
+ }
+ },
+
+ ObjectExpression: function(node) {
+ if (node.properties.length === 0) {
+ return;
+ }
+
+ var first = context.getFirstToken(node),
+ second = context.getFirstToken(node, 1),
+ penultimate = context.getLastToken(node, 1),
+ last = context.getLastToken(node);
+
+ var closingCurlyBraceMustBeSpaced =
+ options.arraysInObjectsException && penultimate.value === "]" ||
+ options.objectsInObjectsException && penultimate.value === "}"
+ ? !options.spaced : options.spaced;
+
+ if (isSameLine(first, second)) {
+ if (options.spaced && !isSpaced(first, second)) {
+ reportRequiredBeginningSpace(node, first);
+ }
+ if (!options.spaced && isSpaced(first, second)) {
+ reportNoBeginningSpace(node, first);
+ }
+ }
+
+ if (isSameLine(penultimate, last)) {
+ if (closingCurlyBraceMustBeSpaced && !isSpaced(penultimate, last)) {
+ reportRequiredEndingSpace(node, last);
+ }
+ if (!closingCurlyBraceMustBeSpaced && isSpaced(penultimate, last)) {
+ reportNoEndingSpace(node, last);
+ }
+ }
+ }
+
+ };
+
+};
+
+},{}],160:[function(require,module,exports){
+/**
+ * @fileoverview Disallows or enforces spaces inside of parentheses.
+ * @author Jonathan Rajavuori
+ * @copyright 2014 David Clark. All rights reserved.
+ * @copyright 2014 Jonathan Rajavuori. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var MISSING_SPACE_MESSAGE = "There must be a space inside this paren.",
+ REJECTED_SPACE_MESSAGE = "There should be no spaces inside this paren.",
+ exceptionsArray = (context.options.length === 2) ? context.options[1].exceptions : [],
+ options = {},
+ rejectedSpaceRegExp,
+ missingSpaceRegExp,
+ spaceChecks;
+
+ if (exceptionsArray && exceptionsArray.length) {
+ options.braceException = exceptionsArray.indexOf("{}") !== -1 || false;
+ options.bracketException = exceptionsArray.indexOf("[]") !== -1 || false;
+ options.parenException = exceptionsArray.indexOf("()") !== -1 || false;
+ options.empty = exceptionsArray.indexOf("empty") !== -1 || false;
+ }
+
+ /**
+ * Used with the `never` option to produce, given the exception options,
+ * two regular expressions to check for missing and rejected spaces.
+ * @param {Object} opts The exception options
+ * @returns {Object} `missingSpace` and `rejectedSpace` regular expressions
+ * @private
+ */
+ function getNeverChecks(opts) {
+ var missingSpaceOpeners = [],
+ missingSpaceClosers = [],
+ rejectedSpaceOpeners = [" ", "\\n", "\\r"],
+ rejectedSpaceClosers = [" ", "\\n", "\\r"],
+ missingSpaceCheck,
+ rejectedSpaceCheck;
+
+ // Populate openers and closers
+ if (opts.braceException) {
+ missingSpaceOpeners.push("\\{");
+ missingSpaceClosers.push("\\}");
+ rejectedSpaceOpeners.push("\\{");
+ rejectedSpaceClosers.push("\\}");
+ }
+ if (opts.bracketException) {
+ missingSpaceOpeners.push("\\[");
+ missingSpaceClosers.push("\\]");
+ rejectedSpaceOpeners.push("\\[");
+ rejectedSpaceClosers.push("\\]");
+ }
+ if (opts.parenException) {
+ missingSpaceOpeners.push("\\(");
+ missingSpaceClosers.push("\\)");
+ rejectedSpaceOpeners.push("\\(");
+ rejectedSpaceClosers.push("\\)");
+ }
+ if (opts.empty) {
+ missingSpaceOpeners.push("\\)");
+ missingSpaceClosers.push("\\(");
+ rejectedSpaceOpeners.push("\\)");
+ rejectedSpaceClosers.push("\\(");
+ }
+
+ if (missingSpaceOpeners.length) {
+ missingSpaceCheck = "\\((" + missingSpaceOpeners.join("|") + ")";
+ if (missingSpaceClosers.length) {
+ missingSpaceCheck += "|";
+ }
+ }
+ if (missingSpaceClosers.length) {
+ missingSpaceCheck += "(" + missingSpaceClosers.join("|") + ")\\)";
+ }
+
+ // compose the rejected regexp
+ rejectedSpaceCheck = "\\( +[^" + rejectedSpaceOpeners.join("") + "]";
+ rejectedSpaceCheck += "|[^" + rejectedSpaceClosers.join("") + "] +\\)";
+
+ return {
+ // e.g. \((\{)|(\})\) --- where {} is an exception
+ missingSpace: missingSpaceCheck || ".^",
+ // e.g. \( +[^ \n\r\{]|[^ \n\r\}] +\) --- where {} is an exception
+ rejectedSpace: rejectedSpaceCheck
+ };
+ }
+
+ /**
+ * Used with the `always` option to produce, given the exception options,
+ * two regular expressions to check for missing and rejected spaces.
+ * @param {Object} opts The exception options
+ * @returns {Object} `missingSpace` and `rejectedSpace` regular expressions
+ * @private
+ */
+ function getAlwaysChecks(opts) {
+ var missingSpaceOpeners = [" ", "\\)", "\\r", "\\n"],
+ missingSpaceClosers = [" ", "\\(", "\\r", "\\n"],
+ rejectedSpaceOpeners = [],
+ rejectedSpaceClosers = [],
+ missingSpaceCheck,
+ rejectedSpaceCheck;
+
+ // Populate openers and closers
+ if (opts.braceException) {
+ missingSpaceOpeners.push("\\{");
+ missingSpaceClosers.push("\\}");
+ rejectedSpaceOpeners.push(" \\{");
+ rejectedSpaceClosers.push("\\} ");
+ }
+ if (opts.bracketException) {
+ missingSpaceOpeners.push("\\[");
+ missingSpaceClosers.push("\\]");
+ rejectedSpaceOpeners.push(" \\[");
+ rejectedSpaceClosers.push("\\] ");
+ }
+ if (opts.parenException) {
+ missingSpaceOpeners.push("\\(");
+ missingSpaceClosers.push("\\)");
+ rejectedSpaceOpeners.push(" \\(");
+ rejectedSpaceClosers.push("\\) ");
+ }
+ if (opts.empty) {
+ rejectedSpaceOpeners.push(" \\)");
+ rejectedSpaceClosers.push("\\( ");
+ }
+
+ // compose the allowed regexp
+ missingSpaceCheck = "\\([^" + missingSpaceOpeners.join("") + "]";
+ missingSpaceCheck += "|[^" + missingSpaceClosers.join("") + "]\\)";
+
+ // compose the rejected regexp
+ if (rejectedSpaceOpeners.length) {
+ rejectedSpaceCheck = "\\((" + rejectedSpaceOpeners.join("|") + ")";
+ if (rejectedSpaceClosers.length) {
+ rejectedSpaceCheck += "|";
+ }
+ }
+ if (rejectedSpaceClosers.length) {
+ rejectedSpaceCheck += "(" + rejectedSpaceClosers.join("|") + ")\\)";
+ }
+
+ return {
+ // e.g. \([^ \)\r\n\{]|[^ \(\r\n\}]\) --- where {} is an exception
+ missingSpace: missingSpaceCheck,
+ // e.g. \(( \{})|(\} )\) --- where {} is an excpetion
+ rejectedSpace: rejectedSpaceCheck || ".^"
+ };
+ }
+
+ spaceChecks = (context.options[0] === "always") ? getAlwaysChecks(options) : getNeverChecks(options);
+ missingSpaceRegExp = new RegExp(spaceChecks.missingSpace, "mg");
+ rejectedSpaceRegExp = new RegExp(spaceChecks.rejectedSpace, "mg");
+
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ var skipRanges = [];
+
+ /**
+ * Adds the range of a node to the set to be skipped when checking parens
+ * @param {ASTNode} node The node to skip
+ * @returns {void}
+ * @private
+ */
+ function addSkipRange(node) {
+ skipRanges.push(node.range);
+ }
+
+ /**
+ * Sorts the skipRanges array. Must be called before shouldSkip
+ * @returns {void}
+ * @private
+ */
+ function sortSkipRanges() {
+ skipRanges.sort(function (a, b) {
+ return a[0] - b[0];
+ });
+ }
+
+ /**
+ * Checks if a certain position in the source should be skipped
+ * @param {Number} pos The 0-based index in the source
+ * @returns {boolean} whether the position should be skipped
+ * @private
+ */
+ function shouldSkip(pos) {
+ var i, len, range;
+ for (i = 0, len = skipRanges.length; i < len; i += 1) {
+ range = skipRanges[i];
+ if (pos < range[0]) {
+ break;
+ } else if (pos < range[1]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "Program:exit": function checkParenSpaces(node) {
+
+ var nextMatch,
+ nextLine,
+ column,
+ line = 1,
+ source = context.getSource(),
+ pos = 0;
+
+ function checkMatch(match, message) {
+ if (source.charAt(match.index) !== "(") {
+ // Matched a closing paren pattern
+ match.index += 1;
+ }
+
+ if (!shouldSkip(match.index)) {
+ while ((nextLine = source.indexOf("\n", pos)) !== -1 && nextLine < match.index) {
+ pos = nextLine + 1;
+ line += 1;
+ }
+ column = match.index - pos;
+
+ context.report(node, { line: line, column: column }, message);
+ }
+ }
+
+ sortSkipRanges();
+
+ while ((nextMatch = rejectedSpaceRegExp.exec(source)) !== null) {
+ checkMatch(nextMatch, REJECTED_SPACE_MESSAGE);
+ }
+
+ while ((nextMatch = missingSpaceRegExp.exec(source)) !== null) {
+ checkMatch(nextMatch, MISSING_SPACE_MESSAGE);
+ }
+
+ },
+
+
+ // These nodes can contain parentheses that this rule doesn't care about
+
+ LineComment: addSkipRange,
+
+ BlockComment: addSkipRange,
+
+ Literal: addSkipRange
+
+ };
+
+};
+
+},{}],161:[function(require,module,exports){
+/**
+ * @fileoverview Require spaces around infix operators
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var OPERATORS = [
+ "*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", "<=", ">", ">=", "in",
+ "instanceof", "==", "!=", "===", "!==", "&", "^", "|", "&&", "||", "=",
+ "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=", "|=",
+ "?", ":", ","
+ ];
+
+ function isSpaced(left, right) {
+ var op, tokens = context.getTokensBetween(left, right, 1);
+ for (var i = 1, l = tokens.length - 1; i < l; ++i) {
+ op = tokens[i];
+ if (
+ op.type === "Punctuator" &&
+ OPERATORS.indexOf(op.value) >= 0 &&
+ (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0])
+ ) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ function report(node) {
+ context.report(node, "Infix operators must be spaced.");
+ }
+
+ function checkBinary(node) {
+ if (!isSpaced(node.left, node.right)) {
+ report(node);
+ }
+ }
+
+ function checkConditional(node) {
+ if (!isSpaced(node.test, node.consequent) || !isSpaced(node.consequent, node.alternate)) {
+ report(node);
+ }
+ }
+
+ function checkVar(node) {
+ if (node.init && !isSpaced(node.id, node.init)) {
+ report(node);
+ }
+ }
+
+ return {
+ "AssignmentExpression": checkBinary,
+ "BinaryExpression": checkBinary,
+ "LogicalExpression": checkBinary,
+ "ConditionalExpression": checkConditional,
+ "VariableDeclarator": checkVar
+ };
+
+};
+
+},{}],162:[function(require,module,exports){
+/**
+ * @fileoverview Require spaces following return, throw, and case
+ * @author Michael Ficarra
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ function check(node) {
+ var tokens = context.getFirstTokens(node, 2),
+ value = tokens[0].value;
+
+ if (tokens[0].range[1] >= tokens[1].range[0]) {
+ context.report(node, "Keyword \"" + value + "\" must be followed by whitespace.");
+ }
+ }
+
+ return {
+ "ReturnStatement": function(node) {
+ if (node.argument) {
+ check(node);
+ }
+ },
+ "SwitchCase": function(node) {
+ if (node.test) {
+ check(node);
+ }
+ },
+ "ThrowStatement": check
+ };
+
+};
+
+},{}],163:[function(require,module,exports){
+/**
+ * @fileoverview This rule shoud require or disallow spaces before or after unary operations.
+ * @author Marcin Kumorek
+ * @copyright 2014 Marcin Kumorek. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+ var options = context.options && Array.isArray(context.options) && context.options[0] || { words: true, nonwords: false };
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Check if the parent unary operator is "!" in order to know if it's "!!" convert to Boolean or just "!" negation
+ * @param {ASTnode} node AST node
+ * @returns {boolean} Whether or not the parent is unary "!" operator
+ */
+ function isParentUnaryBangExpression(node) {
+ return node && node.parent && node.parent.type === "UnaryExpression" && node.parent.operator === "!";
+ }
+
+ /**
+ * Checks if the type is a unary word expression
+ * @param {string} type value of AST token
+ * @returns {boolean} Whether the word is in the list of known words
+ */
+ function isWordExpression(type) {
+ return ["delete", "new", "typeof", "void"].indexOf(type) !== -1;
+ }
+
+ /**
+ * Check if the node's child argument is an "ObjectExpression"
+ * @param {ASTnode} node AST node
+ * @returns {boolean} Whether or not the argument's type is "ObjectExpression"
+ */
+ function isArgumentObjectExpression(node) {
+ return node.argument && node.argument.type && node.argument.type === "ObjectExpression";
+ }
+
+ /**
+ * Check Unary Word Operators for spaces after the word operator
+ * @param {ASTnode} node AST node
+ * @param {object} firstToken first token from the AST node
+ * @param {object} secondToken second token from the AST node
+ * @returns {void}
+ */
+ function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken) {
+ if (options.words) {
+ if (secondToken.range[0] === firstToken.range[1]) {
+ context.report(node, "Unary word operator \"" + firstToken.value + "\" must be followed by whitespace.");
+ }
+ }
+
+ if (!options.words && isArgumentObjectExpression(node)) {
+ if (secondToken.range[0] > firstToken.range[1]) {
+ context.report(node, "Unexpected space after unary word operator \"" + firstToken.value + "\".");
+ }
+ }
+ }
+
+ /**
+ * Checks UnaryExpression, UpdateExpression and NewExpression for spaces before and after the operator
+ * @param {ASTnode} node AST node
+ * @returns {void}
+ */
+ function checkForSpaces(node) {
+ var tokens = context.getFirstTokens(node, 2),
+ firstToken = tokens[0],
+ secondToken = tokens[1];
+
+ if (isWordExpression(firstToken.value)) {
+ checkUnaryWordOperatorForSpaces(node, firstToken, secondToken);
+ return void 0;
+ }
+
+ if (options.nonwords) {
+ if (node.prefix) {
+ if (isParentUnaryBangExpression(node)) {
+ return void 0;
+ }
+ if (firstToken.range[1] === secondToken.range[0]) {
+ context.report(node, "Unary operator \"" + firstToken.value + "\" must be followed by whitespace.");
+ }
+ } else {
+ if (firstToken.range[1] === secondToken.range[0]) {
+ context.report(node, "Space is required before unary expressions \"" + secondToken.value + "\".");
+ }
+ }
+ } else {
+ if (node.prefix) {
+ if (secondToken.range[0] > firstToken.range[1]) {
+ context.report(node, "Unexpected space after unary operator \"" + firstToken.value + "\".");
+ }
+ } else {
+ if (secondToken.range[0] > firstToken.range[1]) {
+ context.report(node, "Unexpected space before unary operator \"" + secondToken.value + "\".");
+ }
+ }
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "UnaryExpression": checkForSpaces,
+ "UpdateExpression": checkForSpaces,
+ "NewExpression": checkForSpaces
+ };
+
+};
+
+},{}],164:[function(require,module,exports){
+/**
+ * @fileoverview Enforces or disallows a space beginning a single-line comment.
+ * @author Greg Cochard
+ * @copyright 2014 Greg Cochard. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ // Unless the first option is never, require a space
+ var requireSpace = context.options[0] !== "never";
+
+ // Default to match anything, so all will fail if there are no exceptions
+ var exceptionMatcher = new RegExp(" ");
+
+ // Grab the exceptions array and build a RegExp matcher for it
+ var hasExceptions = context.options.length === 2;
+ var unescapedExceptions = hasExceptions ? context.options[1].exceptions : [];
+ var exceptions;
+
+ if (unescapedExceptions.length) {
+ exceptions = unescapedExceptions.map(function(s) {
+ return s.replace(/([.*+?${}()|\^\[\]\/\\])/g, "\\$1");
+ });
+ exceptionMatcher = new RegExp("(^(" + exceptions.join(")+$)|(^(") + ")+$)");
+ }
+
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "LineComment": function checkCommentForSpace(node) {
+
+ if (requireSpace) {
+
+ // If length is zero, ignore it
+ if (node.value.length === 0) {
+ return;
+ }
+
+ // Space expected and not found
+ if (node.value.indexOf(" ") !== 0) {
+
+ /*
+ * Do two tests; one for space starting the line,
+ * and one for a comment comprised only of exceptions
+ */
+ if (hasExceptions && !exceptionMatcher.test(node.value)) {
+ context.report(node, "Expected exception block or space after // in comment.");
+ } else if (!hasExceptions) {
+ context.report(node, "Expected space after // in comment.");
+ }
+ }
+
+ } else {
+
+ if (node.value.indexOf(" ") === 0) {
+ context.report(node, "Unexpected space after // in comment.");
+ }
+ }
+ }
+
+ };
+};
+
+},{}],165:[function(require,module,exports){
+/**
+ * @fileoverview Rule to ensure code is running in strict mode.
+ * @author Nicholas C. Zakas
+ * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var scopes = [];
+
+ /**
+ * Determines if a given node is "use strict".
+ * @param {ASTNode} node The node to check.
+ * @returns {boolean} True if the node is a strict pragma, false if not.
+ * @void
+ */
+ function isStrictPragma(node) {
+ return (node && node.type === "ExpressionStatement" &&
+ node.expression.value === "use strict");
+ }
+
+ /**
+ * When you enter a scope, push the strict value from the previous scope
+ * onto the stack.
+ * @param {ASTNode} node The AST node being checked.
+ * @returns {void}
+ * @private
+ */
+ function enterScope(node) {
+
+ var isStrict = false,
+ isProgram = (node.type === "Program"),
+ isParentGlobal = scopes.length === 1,
+ isParentStrict = scopes.length ? scopes[scopes.length - 1] : false;
+
+ // look for the "use strict" pragma
+ if (isProgram) {
+ isStrict = isStrictPragma(node.body[0]) || isParentStrict;
+ } else {
+ isStrict = isStrictPragma(node.body.body[0]) || isParentStrict;
+ }
+
+ scopes.push(isStrict);
+
+ // never warn if the parent is strict or the function is strict
+ if (!isParentStrict && !isStrict && isParentGlobal) {
+ context.report(node, "Missing \"use strict\" statement.");
+ }
+ }
+
+ /**
+ * When you exit a scope, pop off the top scope and see if it's true or
+ * false.
+ * @returns {void}
+ * @private
+ */
+ function exitScope() {
+ scopes.pop();
+ }
+
+ return {
+
+ "Program": enterScope,
+ "FunctionDeclaration": enterScope,
+ "FunctionExpression": enterScope,
+
+ "Program:exit": exitScope,
+ "FunctionDeclaration:exit": exitScope,
+ "FunctionExpression:exit": exitScope
+ };
+
+};
+
+},{}],166:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag comparisons to the value NaN
+ * @author James Allardice
+ * @copyright 2014 Jordan Harband. All rights reserved.
+ * @copyright 2013 James Allardice. All rights reserved.
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+
+ "use strict";
+
+ return {
+ "BinaryExpression": function (node) {
+ if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) {
+ context.report(node, "Use the isNaN function to compare with NaN.");
+ }
+ }
+ };
+
+};
+
+},{}],167:[function(require,module,exports){
+/**
+ * @fileoverview Validates JSDoc comments are syntactically correct
+ * @author Nicholas C. Zakas
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var doctrine = require("doctrine");
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var options = context.options[0] || {},
+ prefer = options.prefer || {},
+
+ // these both default to true, so you have to explicitly make them false
+ requireReturn = options.requireReturn === false ? false : true,
+ requireParamDescription = options.requireParamDescription === false ? false : true;
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ // Using a stack to store if a function returns or not (handling nested functions)
+ var fns = [];
+
+ /**
+ * When parsing a new function, store it in our function stack.
+ * @returns {void}
+ * @private
+ */
+ function startFunction() {
+ fns.push({returnPresent: false});
+ }
+
+ /**
+ * Indicate that return has been found in the current function.
+ * @param {ASTNode} node The return node.
+ * @returns {void}
+ * @private
+ */
+ function addReturn(node) {
+ var functionState = fns[fns.length - 1];
+
+ if (functionState && node.argument !== null) {
+ functionState.returnPresent = true;
+ }
+ }
+
+ /**
+ * Validate the JSDoc node and output warnings if anything is wrong.
+ * @param {ASTNode} node The AST node to check.
+ * @returns {void}
+ * @private
+ */
+ function checkJSDoc(node) {
+ var jsdocNode = context.getJSDocComment(node),
+ functionData = fns.pop(),
+ hasReturns = false,
+ hasConstructor = false,
+ params = Object.create(null),
+ jsdoc;
+
+ // make sure only to validate JSDoc comments
+ if (jsdocNode) {
+
+ try {
+ jsdoc = doctrine.parse(jsdocNode.value, {
+ strict: true,
+ unwrap: true,
+ sloppy: true
+ });
+ } catch (ex) {
+
+ if (/braces/i.test(ex.message)) {
+ context.report(jsdocNode, "JSDoc type missing brace.");
+ } else {
+ context.report(jsdocNode, "JSDoc syntax error.");
+ }
+
+ return;
+ }
+
+ jsdoc.tags.forEach(function(tag) {
+
+ switch (tag.title) {
+
+ case "param":
+ if (!tag.type) {
+ context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name });
+ }
+
+ if (!tag.description && requireParamDescription) {
+ context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name });
+ }
+
+ if (params[tag.name]) {
+ context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name });
+ } else if (tag.name.indexOf(".") === -1) {
+ params[tag.name] = 1;
+ }
+ break;
+
+ case "return":
+ case "returns":
+ hasReturns = true;
+
+ if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") {
+ context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement.");
+ } else {
+ if (!tag.type) {
+ context.report(jsdocNode, "Missing JSDoc return type.");
+ }
+
+ if (tag.type.name !== "void" && !tag.description) {
+ context.report(jsdocNode, "Missing JSDoc return description.");
+ }
+ }
+
+ break;
+
+ case "constructor":
+ case "class":
+ hasConstructor = true;
+ break;
+
+ // no default
+ }
+
+ // check tag preferences
+ if (prefer.hasOwnProperty(tag.title)) {
+ context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] });
+ }
+
+ });
+
+ // check for functions missing @returns
+ if (!hasReturns && !hasConstructor) {
+ if (requireReturn || functionData.returnPresent) {
+ context.report(jsdocNode, "Missing JSDoc @returns for function.");
+ }
+ }
+
+ // check the parameters
+ var jsdocParams = Object.keys(params);
+
+ node.params.forEach(function(param, i) {
+ var name = param.name;
+
+ if (jsdocParams[i] && (name !== jsdocParams[i])) {
+ context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", {
+ name: name,
+ jsdocName: jsdocParams[i]
+ });
+ } else if (!params[name]) {
+ context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", {
+ name: name
+ });
+ }
+ });
+
+ }
+
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "FunctionExpression": startFunction,
+ "FunctionDeclaration": startFunction,
+ "FunctionExpression:exit": checkJSDoc,
+ "FunctionDeclaration:exit": checkJSDoc,
+ "ReturnStatement": addReturn
+ };
+
+};
+
+},{"doctrine":5}],168:[function(require,module,exports){
+/**
+ * @fileoverview Ensures that the results of typeof are compared against a valid string
+ * @author Ian Christian Myers
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ var VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"],
+ OPERATORS = ["==", "===", "!=", "!=="];
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+
+ "UnaryExpression": function (node) {
+ var parent, sibling;
+
+ if (node.operator === "typeof") {
+ parent = context.getAncestors().pop();
+
+ if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) {
+ sibling = parent.left === node ? parent.right : parent.left;
+
+ if (sibling.type === "Literal" && VALID_TYPES.indexOf(sibling.value) === -1) {
+ context.report(sibling, "Invalid typeof comparison value");
+ }
+ }
+ }
+ }
+
+ };
+
+};
+
+},{}],169:[function(require,module,exports){
+/**
+ * @fileoverview Rule to enforce var declarations are only at the top of a function.
+ * @author Danny Fritz
+ * @author Gyandeep Singh
+ * @copyright 2014 Danny Fritz. All rights reserved.
+ * @copyright 2014 Gyandeep Singh. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+ var errorMessage = "All \"var\" declarations must be at the top of the function scope.";
+
+ //--------------------------------------------------------------------------
+ // Helpers
+ //--------------------------------------------------------------------------
+
+ /**
+ * @param {ASTNode} node - any node
+ * @returns {Boolean} whether the given node structurally represents a directive
+ */
+ function looksLikeDirective(node) {
+ return node.type === "ExpressionStatement" &&
+ node.expression.type === "Literal" && typeof node.expression.value === "string";
+ }
+
+ /**
+ * Checks whether this variable is on top of the block body
+ * @param {ASTNode} node - The node to check
+ * @param {ASTNode[]} statements - collection of ASTNodes for the parent node block
+ * @returns {Boolean} True if var is on top otherwise false
+ */
+ function isVarOnTop(node, statements) {
+ var i = 0, l = statements.length;
+
+ // skip over directives
+ for (; i < l; ++i) {
+ if (!looksLikeDirective(statements[i])) {
+ break;
+ }
+ }
+
+ for (; i < l; ++i) {
+ if (statements[i].type !== "VariableDeclaration") {
+ return false;
+ }
+ if (statements[i] === node) {
+ return true;
+ }
+ }
+ }
+
+ /**
+ * Checks whether variable is on top at the global level
+ * @param {ASTNode} node - The node to check
+ * @param {ASTNode} parent - Parent of the node
+ * @returns {void}
+ */
+ function globalVarCheck(node, parent) {
+ if (!isVarOnTop(node, parent.body)) {
+ context.report(node, errorMessage);
+ }
+ }
+
+ /**
+ * Checks whether variable is on top at functional block scope level
+ * @param {ASTNode} node - The node to check
+ * @param {ASTNode} parent - Parent of the node
+ * @param {ASTNode} grandParent - Parent of the node's parent
+ * @returns {void}
+ */
+ function blockScopeVarCheck(node, parent, grandParent) {
+ if (!((grandParent.type === "FunctionDeclaration"
+ || grandParent.type === "FunctionExpression")
+ && parent.type === "BlockStatement"
+ && isVarOnTop(node, parent.body))) {
+ context.report(node, errorMessage);
+ }
+ }
+
+ //--------------------------------------------------------------------------
+ // Public API
+ //--------------------------------------------------------------------------
+
+ return {
+ "VariableDeclaration": function (node) {
+ var ancestors = context.getAncestors();
+ var parent = ancestors.pop();
+ var grandParent = ancestors.pop();
+
+ if (node.kind === "var") {// check variable is `var` type and not `let` or `const`
+ if (parent.type === "Program") {// That means its a global variable
+ globalVarCheck(node, parent);
+ } else {
+ blockScopeVarCheck(node, parent, grandParent);
+ }
+ }
+ }
+ };
+
+};
+
+},{}],170:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when IIFE is not wrapped in parens
+ * @author Ilya Volodin
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+ var style = context.options[0] || "outside";
+
+ function wrapped(node) {
+ var previousToken = context.getTokenBefore(node),
+ nextToken = context.getTokenAfter(node);
+ return previousToken && previousToken.value === "(" &&
+ nextToken && nextToken.value === ")";
+ }
+
+ return {
+
+ "CallExpression": function(node) {
+ if (node.callee.type === "FunctionExpression") {
+ var callExpressionWrapped = wrapped(node),
+ functionExpressionWrapped = wrapped(node.callee);
+
+ if (!callExpressionWrapped && !functionExpressionWrapped) {
+ context.report(node, "Wrap an immediate function invocation in parentheses.");
+ } else if (style === "inside" && !functionExpressionWrapped) {
+ context.report(node, "Wrap only the function expression in parens.");
+ } else if (style === "outside" && !callExpressionWrapped) {
+ context.report(node, "Move the invocation into the parens that contain the function.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],171:[function(require,module,exports){
+/**
+ * @fileoverview Rule to flag when regex literals are not wrapped in parens
+ * @author Matt DuVall
+ */
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function(context) {
+
+ "use strict";
+
+ return {
+
+ "Literal": function(node) {
+ var token = context.getFirstToken(node),
+ nodeType = token.type,
+ source,
+ grandparent,
+ ancestors;
+
+ if (nodeType === "RegularExpression") {
+ source = context.getTokenBefore(node);
+ ancestors = context.getAncestors();
+ grandparent = ancestors[ancestors.length - 1];
+
+ if (grandparent.type === "MemberExpression" && grandparent.object === node &&
+ (!source || source.value !== "(")) {
+ context.report(node, "Wrap the regexp literal in parens to disambiguate the slash.");
+ }
+ }
+ }
+ };
+
+};
+
+},{}],172:[function(require,module,exports){
+/**
+ * @fileoverview Rule to require or disallow yoda comparisons
+ * @author Nicholas C. Zakas
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//--------------------------------------------------------------------------
+// Helpers
+//--------------------------------------------------------------------------
+
+/**
+ * Determines whether an operator is a comparison operator.
+ * @param {String} operator The operator to check.
+ * @returns {boolean} Whether or not it is a comparison operator.
+ */
+function isComparisonOperator(operator) {
+ return (/^(==|===|!=|!==|<|>|<=|>=)$/).test(operator);
+}
+
+/**
+ * Determines whether an operator is one used in a range test.
+ * Allowed operators are `<` and `<=`.
+ * @param {String} operator The operator to check.
+ * @returns {boolean} Whether the operator is used in range tests.
+ */
+function isRangeTestOperator(operator) {
+ return ["<", "<="].indexOf(operator) >= 0;
+}
+
+/**
+ * Determines whether a non-Literal node is a negative number that should be
+ * treated as if it were a single Literal node.
+ * @param {ASTNode} node Node to test.
+ * @returns {boolean} True if the node is a negative number that looks like a
+ * real literal and should be treated as such.
+ */
+function looksLikeLiteral(node) {
+ return (node.type === "UnaryExpression" &&
+ node.operator === "-" &&
+ node.prefix &&
+ node.argument.type === "Literal" &&
+ typeof node.argument.value === "number");
+}
+
+/**
+ * Attempts to derive a Literal node from nodes that are treated like literals.
+ * @param {ASTNode} node Node to normalize.
+ * @returns {ASTNode} The original node if the node is already a Literal, or a
+ * normalized Literal node with the negative number as the
+ * value if the node represents a negative number literal,
+ * otherwise null if the node cannot be converted to a
+ * normalized literal.
+ */
+function getNormalizedLiteral(node) {
+ if (node.type === "Literal") {
+ return node;
+ }
+
+ if (looksLikeLiteral(node)) {
+ return {
+ type: "Literal",
+ value: -node.argument.value,
+ raw: "-" + node.argument.value
+ };
+ }
+
+ return null;
+}
+
+/**
+ * Checks whether two expressions reference the same value. For example:
+ * a = a
+ * a.b = a.b
+ * a[0] = a[0]
+ * a['b'] = a['b']
+ * @param {ASTNode} a Left side of the comparison.
+ * @param {ASTNode} b Right side of the comparison.
+ * @returns {boolean} True if both sides match and reference the same value.
+ */
+function same(a, b) {
+ if (a.type !== b.type) {
+ return false;
+ }
+
+ switch (a.type) {
+ case "Identifier":
+ return a.name === b.name;
+ case "Literal":
+ return a.value === b.value;
+ case "MemberExpression":
+ // x[0] = x[0]
+ // x[y] = x[y]
+ // x.y = x.y
+ return same(a.object, b.object) && same(a.property, b.property);
+ default:
+ return false;
+ }
+}
+
+//------------------------------------------------------------------------------
+// Rule Definition
+//------------------------------------------------------------------------------
+
+module.exports = function (context) {
+
+ // Default to "never" (!always) if no option
+ var always = (context.options[0] === "always");
+ var exceptRange = (context.options[1] && context.options[1].exceptRange);
+
+ /**
+ * Determines whether node represents a range test.
+ * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside"
+ * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and
+ * both operators must be `<` or `<=`. Finally, the literal on the left side
+ * must be less than or equal to the literal on the right side so that the
+ * test makes any sense.
+ * @param {ASTNode} node LogicalExpression node to test.
+ * @returns {Boolean} Whether node is a range test.
+ */
+ function isRangeTest(node) {
+ var left = node.left,
+ right = node.right;
+
+ /**
+ * Determines whether node is of the form `0 <= x && x < 1`.
+ * @returns {Boolean} Whether node is a "between" range test.
+ */
+ function isBetweenTest() {
+ var leftLiteral, rightLiteral;
+
+ return (node.operator === "&&" &&
+ (leftLiteral = getNormalizedLiteral(left.left)) &&
+ (rightLiteral = getNormalizedLiteral(right.right)) &&
+ leftLiteral.value <= rightLiteral.value &&
+ same(left.right, right.left));
+ }
+
+ /**
+ * Determines whether node is of the form `x < 0 || 1 <= x`.
+ * @returns {Boolean} Whether node is an "outside" range test.
+ */
+ function isOutsideTest() {
+ var leftLiteral, rightLiteral;
+
+ return (node.operator === "||" &&
+ (leftLiteral = getNormalizedLiteral(left.right)) &&
+ (rightLiteral = getNormalizedLiteral(right.left)) &&
+ leftLiteral.value <= rightLiteral.value &&
+ same(left.left, right.right));
+ }
+
+ /**
+ * Determines whether node is wrapped in parentheses.
+ * @returns {Boolean} Whether node is preceded immediately by an open
+ * paren token and followed immediately by a close
+ * paren token.
+ */
+ function isParenWrapped() {
+ var tokenBefore, tokenAfter;
+
+ return ((tokenBefore = context.getTokenBefore(node)) &&
+ tokenBefore.value === "(" &&
+ (tokenAfter = context.getTokenAfter(node)) &&
+ tokenAfter.value === ")");
+ }
+
+ return (node.type === "LogicalExpression" &&
+ left.type === "BinaryExpression" &&
+ right.type === "BinaryExpression" &&
+ isRangeTestOperator(left.operator) &&
+ isRangeTestOperator(right.operator) &&
+ (isBetweenTest() || isOutsideTest()) &&
+ isParenWrapped());
+ }
+
+ //--------------------------------------------------------------------------
+ // Public
+ //--------------------------------------------------------------------------
+
+ return {
+ "BinaryExpression": always ? function(node) {
+
+ // Comparisons must always be yoda-style: if ("blue" === color)
+ if (
+ (node.right.type === "Literal" || looksLikeLiteral(node.right)) &&
+ isComparisonOperator(node.operator) &&
+ !(exceptRange && isRangeTest(context.getAncestors().pop()))
+ ) {
+ context.report(node, "Expected literal to be on the left side of " + node.operator + ".");
+ }
+
+ } : function(node) {
+
+ // Comparisons must never be yoda-style (default)
+ if (
+ (node.left.type === "Literal" || looksLikeLiteral(node.left)) &&
+ isComparisonOperator(node.operator) &&
+ !(exceptRange && isRangeTest(context.getAncestors().pop()))
+ ) {
+ context.report(node, "Expected literal to be on the right side of " + node.operator + ".");
+ }
+
+ }
+ };
+
+};
+
+},{}],173:[function(require,module,exports){
+(function (process){
+/**
+ * @fileoverview Tracks performance of individual rules.
+ * @author Brandon Mills
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/* istanbul ignore next */
+function alignLeft(str, len, ch) {
+ return str + new Array(len - str.length + 1).join(ch || " ");
+}
+
+/* istanbul ignore next */
+function alignRight(str, len, ch) {
+ return new Array(len - str.length + 1).join(ch || " ") + str;
+}
+
+//------------------------------------------------------------------------------
+// Module definition
+//------------------------------------------------------------------------------
+
+var enabled = !!process.env.TIMING;
+
+var HEADERS = ["Rule", "Time (ms)", "Relative"];
+var ALIGN = [alignLeft, alignRight, alignRight];
+
+/* istanbul ignore next */
+function display(data) {
+ var total = 0;
+ var rows = Object.keys(data)
+ .map(function(key) {
+ var time = data[key];
+ total += time;
+ return [key, time];
+ })
+ .sort(function(a, b) {
+ return b[1] - a[1];
+ })
+ .slice(0, 10);
+
+ rows.forEach(function(row) {
+ row.push((row[1] * 100 / total).toFixed(1) + "%");
+ row[1] = row[1].toFixed(3);
+ });
+
+ rows.unshift(HEADERS);
+
+ var widths = [];
+ rows.forEach(function(row) {
+ var len = row.length, i, n;
+ for (i = 0; i < len; i++) {
+ n = row[i].length;
+ if (!widths[i] || n > widths[i]) {
+ widths[i] = n;
+ }
+ }
+ });
+
+ var table = rows.map(function(row) {
+ return row.map(function(cell, index) {
+ return ALIGN[index](cell, widths[index]);
+ }).join(" | ");
+ });
+ table.splice(1, 0, widths.map(function(w, index) {
+ if (index !== 0 && index !== widths.length - 1) {
+ w++;
+ }
+
+ return ALIGN[index](":", w + 1, "-");
+ }).join("|"));
+
+ console.log(table.join("\n"));
+}
+
+/* istanbul ignore next */
+module.exports = (function() {
+
+ var data = Object.create(null);
+
+ function time(key, fn) {
+ if (typeof data[key] === "undefined") {
+ data[key] = 0;
+ }
+
+ return function() {
+ var t = process.hrtime();
+ fn.apply(null, Array.prototype.slice.call(arguments));
+ t = process.hrtime(t);
+ data[key] += t[0] * 1e3 + t[1] / 1e6;
+ };
+ }
+
+ if (enabled) {
+ process.on("exit", function() {
+ display(data);
+ });
+ }
+
+ return {
+ time: time,
+ enabled: enabled
+ };
+
+}());
+
+}).call(this,require('_process'))
+},{"_process":4}],174:[function(require,module,exports){
+/**
+ * @fileoverview Object to handle access and retrieval of tokens.
+ * @author Brandon Mills
+ * @copyright 2014 Nicholas C. Zakas. All rights reserved.
+ * @copyright 2014 Brandon Mills. All rights reserved.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Implementation
+//------------------------------------------------------------------------------
+
+module.exports = function(tokens) {
+ var api = {},
+ starts = Object.create(null),
+ ends = Object.create(null),
+ index, length, range;
+
+ /**
+ * Gets tokens in a given interval.
+ * @param {int} start Inclusive index of the first token. 0 if negative.
+ * @param {int} end Exclusive index of the last token.
+ * @returns {[Token]} Tokens in the interval.
+ */
+ function get(start, end) {
+ var result = [],
+ i;
+
+ for (i = Math.max(0, start); i < end && i < length; i++) {
+ result.push(tokens[i]);
+ }
+
+ return result;
+ }
+
+ /**
+ * Gets the index in the tokens array of the last token belonging to a node.
+ * Usually a node ends exactly at a token, but due to ASI, sometimes a
+ * node's range extends beyond its last token.
+ * @param {ASTNode} node The node for which to find the last token's index.
+ * @returns {int} Index in the tokens array of the node's last token.
+ */
+ function lastTokenIndex(node) {
+ var end = node.range[1],
+ cursor = ends[end];
+
+ // If the node extends beyond its last token, get the token before the
+ // next token
+ if (typeof cursor === "undefined") {
+ cursor = starts[end] - 1;
+ }
+
+ // If there isn't a next token, the desired token is the last one in the
+ // array
+ if (isNaN(cursor)) {
+ cursor = length - 1;
+ }
+
+ return cursor;
+ }
+
+ // Map tokens' start and end range to the index in the tokens array
+ for (index = 0, length = tokens.length; index < length; index++) {
+ range = tokens[index].range;
+ starts[range[0]] = index;
+ ends[range[1]] = index;
+ }
+
+ /**
+ * Gets a number of tokens that precede a given node's tokens in the token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [beforeCount=0] The number of tokens before the node to retrieve.
+ * @returns {[Token]} Array of objects representing tokens.
+ */
+ api.getTokensBefore = function(node, beforeCount) {
+ var first = starts[node.range[0]];
+ return get(first - (beforeCount || 0), first);
+ };
+
+ /**
+ * Gets the token that precedes a given node's tokens in the token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [skip=0] A number of tokens to skip before the given node.
+ * @returns {Token} An object representing the token.
+ */
+ api.getTokenBefore = function(node, skip) {
+ return tokens[starts[node.range[0]] - (skip || 0) - 1];
+ };
+
+ /**
+ * Gets a number of tokens that precede a given node's tokens in the token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [afterCount=0] The number of tokens after the node to retrieve.
+ * @returns {[Token]} Array of objects representing tokens.
+ */
+ api.getTokensAfter = function(node, afterCount) {
+ var start = lastTokenIndex(node) + 1;
+ return get(start, start + (afterCount || 0));
+ };
+
+ /**
+ * Gets the token that follows a given node's tokens in the token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [skip=0] A number of tokens to skip after the given node.
+ * @returns {Token} An object representing the token.
+ */
+ api.getTokenAfter = function(node, skip) {
+ return tokens[lastTokenIndex(node) + (skip || 0) + 1];
+ };
+
+ /**
+ * Gets all tokens that are related to the given node.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [beforeCount=0] The number of tokens before the node to retrieve.
+ * @param {int} [afterCount=0] The number of tokens after the node to retrieve.
+ * @returns {[Token]} Array of objects representing tokens.
+ */
+ api.getTokens = function(node, beforeCount, afterCount) {
+ return get(
+ starts[node.range[0]] - (beforeCount || 0),
+ lastTokenIndex(node) + (afterCount || 0) + 1
+ );
+ };
+
+ /**
+ * Gets the first `count` tokens of the given node's token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [count=0] The number of tokens of the node to retrieve.
+ * @returns {[Token]} Array of objects representing tokens.
+ */
+ api.getFirstTokens = function(node, count) {
+ var first = starts[node.range[0]];
+ return get(
+ first,
+ Math.min(lastTokenIndex(node) + 1, first + (count || 0))
+ );
+ };
+
+ /**
+ * Gets the first token of the given node's token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [skip=0] A number of tokens to skip.
+ * @returns {Token} An object representing the token.
+ */
+ api.getFirstToken = function(node, skip) {
+ return tokens[starts[node.range[0]] + (skip || 0)];
+ };
+
+ /**
+ * Gets the last `count` tokens of the given node.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [count=0] The number of tokens of the node to retrieve.
+ * @returns {[Token]} Array of objects representing tokens.
+ */
+ api.getLastTokens = function(node, count) {
+ var last = lastTokenIndex(node) + 1;
+ return get(Math.max(starts[node.range[0]], last - (count || 0)), last);
+ };
+
+ /**
+ * Gets the last token of the given node's token stream.
+ * @param {ASTNode} node The AST node.
+ * @param {int} [skip=0] A number of tokens to skip.
+ * @returns {Token} An object representing the token.
+ */
+ api.getLastToken = function(node, skip) {
+ return tokens[lastTokenIndex(node) - (skip || 0)];
+ };
+
+ /**
+ * Gets all of the tokens between two non-overlapping nodes.
+ * @param {ASTNode} left Node before the desired token range.
+ * @param {ASTNode} right Node after the desired token range.
+ * @param {int} [padding=0] Number of extra tokens on either side of center.
+ * @returns {Token[]} Tokens between left and right plus padding.
+ */
+ api.getTokensBetween = function(left, right, padding) {
+ padding = padding || 0;
+ return get(
+ lastTokenIndex(left) + 1 - padding,
+ starts[right.range[0]] + padding
+ );
+ };
+
+ return api;
+};
+
+},{}],175:[function(require,module,exports){
+/**
+ * @fileoverview Common utilities.
+ */
+"use strict";
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+var PLUGIN_NAME_PREFIX = "eslint-plugin-";
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+/**
+ * Merges two objects together and assigns the result to the initial object. Can be used for shallow cloning.
+ * @param {Object} target of the cloning operation
+ * @param {Object} source object
+ * @returns {void}
+ */
+exports.mixin = function(target, source) {
+ Object.keys(source).forEach(function(key) {
+ target[key] = source[key];
+ });
+};
+
+/**
+ * Merges two config objects. This will not only add missing keys, but will also modify values to match.
+ * @param {Object} base config object
+ * @param {Object} custom config object. Overrides in this config object will take priority over base.
+ * @returns {Object} merged config object.
+ */
+exports.mergeConfigs = function mergeConfigs(base, custom) {
+
+ Object.keys(custom).forEach(function (key) {
+ var property = custom[key];
+
+ if (key === "plugins") {
+ if (!base[key]) {
+ base[key] = [];
+ }
+
+ property.forEach(function (plugin) {
+ // skip duplicates
+ if (base[key].indexOf(plugin) === -1) {
+ base[key].push(plugin);
+ }
+ });
+ return;
+ }
+
+ if (Array.isArray(base[key]) && !Array.isArray(property) && typeof property === "number") {
+ // assume that we are just overriding first attribute
+ base[key][0] = custom[key];
+ return;
+ }
+
+ if (typeof property === "object" && !Array.isArray(property)) {
+ // base[key] might not exist, so be careful with recursion here
+ base[key] = mergeConfigs(base[key] || {}, custom[key]);
+ } else {
+ base[key] = custom[key];
+ }
+ });
+
+ return base;
+};
+
+/**
+ * Removes the prefix `eslint-plugin-` from a plugin name.
+ * @param {string} pluginName The name of the plugin which may has the prefix.
+ * @returns {string} The name of the plugin without prefix.
+ */
+exports.removePluginPrefix = function removePluginPrefix(pluginName) {
+ var nameWithoutPrefix;
+
+ if (pluginName.indexOf(PLUGIN_NAME_PREFIX) === 0) {
+ nameWithoutPrefix = pluginName.substring(PLUGIN_NAME_PREFIX.length);
+ } else {
+ nameWithoutPrefix = pluginName;
+ }
+
+ return nameWithoutPrefix;
+};
+
+exports.PLUGIN_NAME_PREFIX = PLUGIN_NAME_PREFIX;
+
+},{}],176:[function(require,module,exports){
+/**
+ * @fileoverview Node mapping for JSX nodes to feed to estraverse
+ * @author Nicholas C. Zakas
+ * @copyright 2015 Nicholas C. Zakas. All rights reserved.
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+var estraverse = require("estraverse");
+
+//------------------------------------------------------------------------------
+// Setup
+//------------------------------------------------------------------------------
+
+var nodeTypes = {
+ JSXIdentifier: [],
+ JSXNamespacedName: ["namespace", "name"],
+ JSXMemberExpression: ["object", "property"],
+ JSXEmptyExpression: [],
+ JSXExpressionContainer: ["expression"],
+ JSXElement: ["openingElement", "closingElement", "children"],
+ JSXClosingElement: ["name"],
+ JSXOpeningElement: ["name", "attributes"],
+ JSXAttribute: ["name", "value"],
+ JSXSpreadAttribute: ["argument"],
+ JSXText: null
+};
+
+// add node types to estraverse
+Object.keys(nodeTypes).forEach(function(nodeType) {
+ estraverse.Syntax[nodeType] = nodeType;
+ estraverse.VisitorKeys[nodeType] = nodeTypes[nodeType];
+});
+
+//------------------------------------------------------------------------------
+// Public
+//------------------------------------------------------------------------------
+
+module.exports = estraverse;
+
+},{"estraverse":22}]},{},[26])(26)
+});
\ No newline at end of file
diff --git a/eval.js b/eval.js
new file mode 100644
index 00000000..9b358866
--- /dev/null
+++ b/eval.js
@@ -0,0 +1,183 @@
+var char_position = function(src, line_number, col_number){
+// line_number is 1 based. as are chrome error messages
+// col_number is 1 based. as are chrome error messages
+// result is 0 based.
+// beware codemirror has line and char positions being 0 based, and its index 0 based as well
+// assume src linefeeds are just 1 char ie \n
+// and make that newline char be the last char on the line, not the first char of the next line.
+ var cur_line = 1
+ var cur_col = 0
+ var prev_char = null
+ for (var i = 0; i < src.length; i++){
+ var char = src.charAt(i)
+ if (prev_char == '\n'){
+ cur_line = cur_line + 1
+ cur_col = 1
+ }
+ else {
+ cur_col += 1
+ }
+ if ((cur_line == line_number) && (cur_col == col_number)){
+ return i;
+ }
+ prev_char = char
+ }
+ return false
+}
+
+
+
+
+var in_ui = function(){ return true } //todo search and remove all calls
+function post_to_sandbox(message_obj){ //todo remove all calls
+ sandbox_iframe_id.contentWindow.postMessage(message_obj, '*');
+}
+
+function post_to_ui(message_obj){ //todo remove all calls
+ window.parent.postMessage(message_obj, "*")
+}
+
+var prefix_to_evaled_src = "try{" //referenced in eval code AND in error handler way below
+
+function fix_code_to_be_evaled(src){
+ let slash_slash_pos = src.lastIndexOf("//")
+ let newline_pos = src.lastIndexOf("\n")
+ if (slash_slash_pos > newline_pos) { //src is ending with a slash-slash comment but no newline on end.
+ return src + "\n" //without this I get an error
+ }
+ else { return src }
+}
+
+//part 1 of 3.
+function eval_js_part1(){
+ var src = Editor.get_javascript("auto") //if no selection get whole buffer, else get just the selection
+ //we do NOT want to pass to eval part 2 a trimmed string as getting its char
+ //offsets into the editor buffer correct is important.
+ if (src.trim() == ""){
+ open_doc(learning_js_doc_id)
+ out("There is no JavaScript to execute. See Learning JavaScript " +
+ "in the Documentation pane for help.",
+ "red")
+ }
+ else{
+ eval_js_part2(src)
+ }
+}
+
+//part 2 of 3 is in eval.js, window.addEventListener('message' under the message name of "eval"
+function eval_js_part2 (command){
+ //var command = event.data.command; //might be whole editor buffer or just the selection.
+ //command = trim_string_for_eval(command) //cuts trailing whitespace and // comments only. but buggy
+ command = fix_code_to_be_evaled(command)
+ var suffix_to_evaled_src = ""
+ if (command.startsWith("{")) { prefix_to_evaled_src = "try{("; suffix_to_evaled_src = ")" } //parens fixes broken js eval of src like "{a:2, b:3}"
+ else { prefix_to_evaled_src = "try{" //no parens, normal case
+ suffix_to_evaled_src = ""
+ }
+ //full_dexter_url = event.data.full_dexter_url
+ var result = {command: command}
+
+ try {//note doing try_command = "var val927; try{val927 = " + command ...fails because evaling
+ //"var f1 = function f2(){...}" will bind f1 to the fn but NOT f2!!! what a piece of shit js is.
+ //AND wrapping parens around src of "{a:2, b:3}" works but wrapping parens around a "function f1()..." doesn't get f1 bound to the fn.
+ var try_command = prefix_to_evaled_src + command + suffix_to_evaled_src + "} catch(err){error_message_start_and_end_pos(err)}"
+ //if try succeeds, it returns its last val, else catch hits and it returns its last val
+ //if I dont' do this trick with val927, I get an error when evaling "{a:2, b:3}
+ //I can't figure out whether try is supposed to return the val of its last exp or not from the js spec.
+ let start_time = Date.now()
+ var value = window.eval(try_command) //window.eval evals in "global scope" meaning that, unlike plain eval,
+ //if I click on EVAL button with window.eval for defining a fn,
+ //then a 2nd click on EVAL for calling it, it will work.
+ //also works with var foo = 2, and foo in separate eval clicks.
+ //also I think this global eval will not see var bindings for the
+ //lex vars in this eventListener, ie name, result, etc. which is good.
+ result.duration = Date.now() - start_time
+ if (value === null){ //calling null.error_type will error so do this first.
+ result.value_string = stringify_value(value)
+ }
+ else if ((typeof(value) == "object") && value.error_type){
+ result = value
+ //result.command = command
+ result.starting_index = char_position(command, result.line_no, result.char_no)
+ var command_starting_with_starting_index = command.substring(result.starting_index)
+ result.ending_index = command_starting_with_starting_index.match(/\W|$/).index + result.starting_index
+
+ }
+ else{
+ result.value_string = stringify_value(value)
+ //result.command = command
+ }
+ }
+ catch(err) { //probably a syntax error. Can't get starting_index so won't be able to highlight offending code
+ result.error_type = err.name
+ result.full_error_message = err.stack
+ result.error_message = err.message
+ }
+ /*event.source.postMessage({ //send result to the UI side
+ name: "eval_result",
+ result: result,
+ },
+ event.origin)*/
+ eval_js_part3(result)
+}
+
+// in UI.
+function eval_js_part3(result){
+ var string_to_print
+ var start_of_selection = 0
+ if (Editor.is_selection()){
+ start_of_selection = Editor.selection_start()
+ }
+ if (result.error_type){
+ string_to_print = result.error_type + ": " + result.error_message
+ if (result.starting_index != undefined) { //beware, starting_index might == 0 which is false to IF
+ var cm_pos = myCodeMirror.doc.posFromIndex(start_of_selection + result.starting_index)
+ string_to_print += " At line: " + (cm_pos.line + 1) + ", char: " + (cm_pos.ch + 1)
+ }
+ out_eval_result(string_to_print, "red")
+ }
+ else if (result.value_string == '"dont_print"') {}
+ else {
+ string_to_print = result.value_string + " " + result.duration + " ms"
+ out_eval_result(string_to_print)
+ }
+ //highlight erroring source code if possible. If result.starting_index == undefined, that means no error.
+ if (result.starting_index && (result.starting_index != 0)){ //we've got an error
+ //beware starting_index might be 0 which IF treats as false
+ if (result.ending_index == undefined){
+ result.ending_index = result.starting_index + 1
+ }
+ Editor.select_javascript(start_of_selection + result.starting_index, start_of_selection + result.ending_index)
+ }
+}
+
+//doesn't really need to return result as this side_effects result
+//src evaled which might not be the whole editor buffer if there's a selection
+function error_message_start_and_end_pos(err){
+ var error_result = {}
+ var full_mess = err.stack
+ error_result.full_error_message = full_mess
+ error_result.error_type = err.name
+ error_result.error_message = err.message
+ if (error_result.error_type == "SyntaxError"){ //Syntax errors don't contain line number info.
+ return error_result
+ }
+ else {
+ try {
+ var comma_split_part = full_mess.split(",")[1]
+ var colon_splits = comma_split_part.split(":")
+ var line_no = parseInt(colon_splits[1])
+ var char_part = colon_splits[2]
+ var paren_splits = char_part.split(")")
+ var char_no = parseInt(paren_splits[0])
+ if (line_no == 1){ //because of the "try{" that I wrap command in.
+ char_no = char_no - prefix_to_evaled_src.length //7 due to the prefix evaled, ie "try{("
+ }
+ error_result.line_no = line_no
+ error_result.char_no = char_no
+ return error_result
+ }
+ catch(e){return error_result} //because might be some weird format of err.stack
+ //that I can't parse, so just bail.
+ }
+}
diff --git a/eventemitter2.min.js b/eventemitter2.min.js
new file mode 100644
index 00000000..61a328db
--- /dev/null
+++ b/eventemitter2.min.js
@@ -0,0 +1 @@
+!function(e){function r(){this._events={};if(this._conf){i.call(this,this._conf)}}function i(e){if(e){this._conf=e;e.delimiter&&(this.delimiter=e.delimiter);e.maxListeners&&(this._events.maxListeners=e.maxListeners);e.wildcard&&(this.wildcard=e.wildcard);e.newListener&&(this.newListener=e.newListener);if(this.wildcard){this.listenerTree={}}}}function s(e){this._events={};this.newListener=false;i.call(this,e)}function o(e,t,n,r){if(!n){return[]}var i=[],s,u,a,f,l,c,h,p=t.length,d=t[r],v=t[r+1];if(r===p&&n._listeners){if(typeof n._listeners==="function"){e&&e.push(n._listeners);return[n]}else{for(s=0,u=n._listeners.length;s0&&o._listeners.length>a){o._listeners.warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",o._listeners.length);console.trace()}}}return true}u=e.shift()}return true}var t=Array.isArray?Array.isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"};var n=10;s.prototype.delimiter=".";s.prototype.setMaxListeners=function(e){this._events||r.call(this);this._events.maxListeners=e;if(!this._conf)this._conf={};this._conf.maxListeners=e};s.prototype.event="";s.prototype.once=function(e,t){this.many(e,1,t);return this};s.prototype.many=function(e,t,n){function i(){if(--t===0){r.off(e,i)}n.apply(this,arguments)}var r=this;if(typeof n!=="function"){throw new Error("many only accepts instances of Function")}i._origin=n;this.on(e,i);return r};s.prototype.emit=function(){this._events||r.call(this);var e=arguments[0];if(e==="newListener"&&!this.newListener){if(!this._events.newListener){return false}}if(this._all){var t=arguments.length;var n=new Array(t-1);for(var i=1;i1)switch(arguments.length){case 2:s.call(this,arguments[1]);break;case 3:s.call(this,arguments[1],arguments[2]);break;default:var t=arguments.length;var n=new Array(t-1);for(var i=1;i0||!!this._all}else{return!!this._all}};s.prototype.on=function(e,i){if(typeof e==="function"){this.onAny(e);return this}if(typeof i!=="function"){throw new Error("on only accepts instances of Function")}this._events||r.call(this);this.emit("newListener",e,i);if(this.wildcard){u.call(this,e,i);return this}if(!this._events[e]){this._events[e]=i}else if(typeof this._events[e]==="function"){this._events[e]=[this._events[e],i]}else if(t(this._events[e])){this._events[e].push(i);if(!this._events[e].warned){var s=n;if(typeof this._events.maxListeners!=="undefined"){s=this._events.maxListeners}if(s>0&&this._events[e].length>s){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);console.trace()}}}return this};s.prototype.onAny=function(e){if(typeof e!=="function"){throw new Error("onAny only accepts instances of Function")}if(!this._all){this._all=[]}this._all.push(e);return this};s.prototype.addListener=s.prototype.on;s.prototype.off=function(e,n){if(typeof n!=="function"){throw new Error("removeListener only takes instances of Function")}var r,i=[];if(this.wildcard){var s=typeof e==="string"?e.split(this.delimiter):e.slice();i=o.call(this,null,s,this.listenerTree,0)}else{if(!this._events[e])return this;r=this._events[e];i.push({_listeners:r})}for(var u=0;u0){r=this._all;for(t=0,n=r.length;t
+
+
+
+ Dexter Development Environment
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Dexte Development Environment
+Create software to control the Dexter robot
+
+
+
+
+
+
+ JavaScript
+
+
+
File▼
+
+
New
+
Open...
+
Insert file...
+
Save
+
Save As...
+
+
+
Edit▼
+
+
Undo ⌘z
+
Redo
+
Find...
+
Replace...
+
Fold All
+
Unfold All
+
Select call alt-click
+
Select All Ctrl-A/⌘A
+
Right click menu has more ops.
+
+
+
Learn JS▼
+
+
Help
+
JavaScript Example
+
Debugging, etc.
+
+
Help
+
console.log(...)
+
debugger
+
Comment out selection
+
Comment to end of line
+
+
+
true & false
+
+
true
+
false
+
and
+
or
+
not
+
+
+
Math
+
+
Arithmetic Example
+
plus
+
minus
+
times
+
divide
+
Pi
+
(...)
+
+
+
Comparisons
+
+
Compare Example
+
less than
+
less or equal
+
equal
+
more or equal
+
more than
+
not equal
+
+
+
Strings
+
+
literal string with "
+
literal string with '
+
multi-lined string
+
add strings
+
+
length
+
get a character
+
get characters
+
split string
+
string equal
+
startsWith
+
endsWith
+
replace
+
+
+
Arrays
+
+
make literal array
+
length
+
get an element
+
set an element
+
push an element
+
+
+
+
Date
+
+
new Date day month year
+
new Date and time
+
new Date by ms
+
Date.now()
+
Date valueOf()
+
Date toString()
+
new Duration("01:14:05")
+
new Duration(ms)
+
new Dur(h,m,s,ms)
+
Dur.milliseconds
+
+
+
+
Variables
+
+
Example
+
Initialize variable
+
Set variable value
+
+
+
JavaScript Objects
+
+
Example
+
Cheat Sheet
+
+
+
+
Control Flow
+
+
if (single-armed)
+
if (multi-armed)
+
for (# of times)
+
for each array elt
+
try {catch errors}
+
dde_error
+
setTimeout
+
+
+
Functions
+
+
Example
+
named function def
+
anonymous fn def
+
return (from fn)
+
+
+
+
+
+
Insert▼
+
+
Print to output
+
+
out(...)
+
out(...)
+
out(...)
+
+
+
Editor.insert
+
show_window
+
+
Simple Message
+
Window Options
+
Buttons
+
Menu
+
Many Inputs
+
onchange calls
+
svg
+
+
Close all
+
+
+
show_web_page(...)
+
get_page
+
Sound
+
+
beep()
+
beep with options
+
beeps(3)
+
speak()
+
speak with options
+
recognize_speech
+
+
+
Inspect root object
+
Train Dexter
+
Build Application
+
+
+
Series▼
+
+
Help
+
Navigation
+
+
Next item →
+
Prev item ←
+
Next series ↓
+
Prev series ↑
+
+
+
Punctuation
+
Boolean
+
Number
+
+
integer
+
float
+
arithmetic
+
comparison
+
math
+
trigonometry
+
number misc
+
number constant
+
+
+
Assignment
+
Strings & Arrays
+
+
literal string
+
string
+
array
+
forEach
+
+
+
Date
+
+
hours:mins:secs
+
time
+
3 letter month
+
full month
+
date
+
+
+
Object System
+
Control Flow
+
+
if
+
for
+
try
+
+
+
Function
+
+
Output
+
+
output functions
+
color name
+
color rgb
+
+
+
Window
+
File
+
Job
+
+
job name
+
+
+
Robot
+
+
Help
+
instruction
+
robot config
+
robot status label
+
robot subclass
+
robot name
+
Dexter constant
+
serial port
+
+
+
Test Suite
+
+
+
Jobs▼
+
+
Help
+
Show robot status
+
Show report
+
Stop all jobs
+
Clear stopped jobs
+
+
+ Real time sim
+
+
Insert Example
+
+
1. Simplest
+
2. Dexter & Fns
+
3. Generators
+
4. Multiple Jobs
+
5. User Input
+
6. Human Instrs
+
7. Enter Instruction
+
8. Async Fns
+
9. Serial Port
+
+
+
+
+
Test▼
+
+
Help
+
Insert Example
+
Navigation
+
+
Run & sel next →
+
Select next Sh-→
+
Prev item ←
+
Down item ↓
+
Up Item ↑
+
+
+
Show suite stats
+
Find TestSuites
+
+
Insert all
+
Run all TestSuites
+
Selection to test
+
+
+
+
+
font size:
+
+
+ ROS url:
+
+
+
+
+
+ Output shell:
+
+
+
+
Ops▼
+
+
ROS Info
+
+
ping
+
cat /etc/hosts
+
rosversion -d
+
roswtf
+
printenv | grep ROS
+
rqt_graph
+
+
+
ROS Lists
+
+
rosmsg list
+
rosnode list
+
rospack list
+
rosparam list
+
rosservice list
+
rostopic list
+
+
+
User Commands
+
+
+
+
+
+
+
+
+
+
Save onEval
+
+
+
+
+
+
+
+
+
+
+ Doc
+
+
+
+
+
+
+
+
+
+ Sim
+
+
+ Pause
+
+
+
+
+
+
+
+
+
+
+
+
+
Header
+
Content
+
+
+
+
+
\ No newline at end of file
diff --git a/instruction.js b/instruction.js
new file mode 100644
index 00000000..fd8b913e
--- /dev/null
+++ b/instruction.js
@@ -0,0 +1,1399 @@
+/**
+ * Created by Fry on 3/5/16.
+ */
+
+var Instruction = class Instruction {
+ toString(){
+ return "{instanceof: " + stringify_value_aux(this.constructor) + "}"
+ }
+ static is_instruction_array(obj){
+ //since we're making the instruction arrays by our fn calls, ie Job.move,
+ //the user isn't making up the arrays, so we assume all arrays that start
+ //with a first elt of a string or length 1 are legitimate. But
+ //we COULD check that the first char is legal and
+ //the length and types of the rest of the elts matched what that op-let needs.
+ if (Array.isArray(obj) && (obj.length > 0)){
+ var first_elt = obj[Instruction.INSTRUCTION_TYPE]
+ if ((typeof(first_elt) == "string") && (first_elt.length == 1)){
+ return true
+ }
+ }
+ return false
+ }
+ //not a good name. really it means, obj is a non-empty array that isn't an instruction array.
+ //so could have an array of fns or other elts that might go on a do list.
+ static is_instructions_array(obj){
+ return Array.isArray(obj) &&
+ (obj.length > 0) &&
+ !Instruction.is_instruction_array(obj)
+ //Instruction.is_instruction_array(obj[0]) ||
+ // Instruction.is_control_instruction(obj[0]) //permit a control instruction in here. thus "is_instructions_array" no longer a good name
+ //)
+ }
+
+ static is_control_instruction(obj){
+ return obj instanceof Instruction.Control
+ }
+ static instruction_color(ins){
+ if(Instruction.is_instruction_array(ins)) { return "#FFFFFF" }
+ else if (Instruction.is_control_instruction(ins)) {
+ if(ins.constructor.name.startsWith("human")) { return "#ffb3d1" } //pink
+ else { return "#e6b3ff" } //lavender
+ }
+ else if (is_generator_function(ins)) { return "#ccffcc" } //green
+ else if (is_iterator(ins)) { return "#aaffaa" } //lighter green
+ else if (typeof(ins) == "function") { return "#b3e6ff" } //blue
+ else if (ins == "debugger") { return "red" }
+ else if (ins == null) { return "#aaaaaa" }
+ else if (Array.isArray(ins)) { return "#aaaaaa" }
+ else { shouldnt("Instruction.instruction_color got unknown instruction type: " + ins) }
+ }
+ static text_for_do_list_item(ins){
+ if(Instruction.is_instruction_array(ins)) {
+ let text = JSON.stringify(ins) //we want 1 line here, not the multi-lines that stringify_value(ins) puts out
+ return "" + text + ""
+ }
+ else if (Instruction.is_control_instruction(ins)) {
+ let name = ins.constructor.name
+ let props = ""
+ for(let prop_name of Object.keys(ins)){
+ props += "" + prop_name + ": " + ins[prop_name] + "; "
+ }
+ return name + " with " + props
+ }
+ else if (is_generator_function(ins)) {
+ return "generator function " + ins.toString().substring(0, 70)
+ }
+ else if (is_iterator(ins)){
+ return "iterator " + ins.toString().substring(0, 70)
+ }
+ else if (typeof(ins) == "function") { return ins.toString().substring(0, 80) }
+ else if (ins == "debugger") { return '"debugger"' }
+ else if (ins == null) { return 'null' }
+ else if (Array.isArray(ins)) { return stringify_value(ins) }
+ else { shouldnt("Instruction.text_for_do_list_item got unknown instruction type: " + ins) }
+ }
+ static text_for_do_list_item_for_stepper(ins){
+ if(Instruction.is_instruction_array(ins)) {
+ let text = JSON.stringify(ins.slice(4)) //we want 1 line here, not the multi-lines that stringify_value(ins) puts out
+ return "" + text + ""
+ }
+ else if (Instruction.is_control_instruction(ins)) {
+ let name = ins.constructor.name
+ let props = ""
+ for(let prop_name of Object.keys(ins)){
+ props += "" + prop_name + ": " + ins[prop_name] + "; "
+ }
+ return name + " with " + props
+ }
+ else if (is_generator_function(ins)) {
+ return "generator function " + ins.toString().substring(0, 70)
+ }
+ else if (is_iterator(ins)){
+ return "iterator " + ins.toString().substring(0, 70)
+ }
+ else if (typeof(ins) == "function") { return ins.toString().substring(0, 80) }
+ else if (ins == "debugger") { return '"debugger"' }
+ else if (ins == null) { return 'null' }
+ else if (Array.isArray(ins)) { return stringify_value(ins) }
+ else { shouldnt("Instruction.text_for_do_list_item_for_stepper got unknown instruction type: " + ins) }
+ }
+}
+
+Instruction.labels = [
+"JOB_ID", // 0
+"INSTRUCTION_ID", // 1
+"START_TIME", // 2
+"STOP_TIME", // 3 //END_TIME is better in this context BUT stop_time, stop_reason is used in Jobs and I wanted to be consistent with that.
+"INSTRUCTION_TYPE" // 4
+] // and after those come the arguments to the instruction.
+
+//user might call this at top level in a do_list so make it's name short.
+function make_ins(instruction_type, ...args){
+ let result = new Array(Instruction.INSTRUCTION_TYPE)
+ result.push(instruction_type)
+ if (args.length === 0) { return result } //avoids generating the garbage that concat with an arg of an empty list would for this common case, ie for "g" ahd "h" instructions
+ else { return result.concat(args) }
+ return result.concat(args)
+}
+
+for (let i = 0; i < Instruction.labels.length; i++){
+ Instruction[Instruction.labels[i]] = i
+}
+
+//return an array of the instruction args
+Instruction.args = function(ins_array){
+ return ins_array.slice(Instruction.INSTRUCTION_TYPE + 1)
+}
+//now Instruction.INSTRUCTION_TYPE == 4, and some_ins_array[Instruction.INSTRUCTION_TYPE] will return the oplet
+//make_ins("a", 1, 2, 3, 4, 5) works
+//make_ins("a", ...[1, 2, 3, 4, 5]) works
+
+Instruction.Control = class Control extends Instruction{
+ do_item(job_instance){
+ job_instance.stop_for_reason("errored",
+ "do_next_item got unrecognized control instruction: " +
+ this)
+ job_instance.do_next_item()
+ }
+}
+
+Instruction.Control.error = class error extends Instruction.Control{
+ constructor (reason) {
+ super()
+ this.reason = reason
+ }
+ do_item (job_instance){
+ job_instance.stop_for_reason("errored", "Job: " + job_instance.name + " errored with: " + this.reason)
+ //job_instance.set_up_next_do(0) //no, get out faster, we errored.
+ job_instance.do_next_item()
+ }
+ toString(){
+ return "error: " + this.reason
+ }
+}
+
+Instruction.Control.go_to = class go_to extends Instruction.Control{
+ constructor (instruction_location) {
+ super()
+ if (instruction_location === undefined){
+ dde_error("go_to has not been passed an instruction_location.")
+ }
+ this.instruction_location = instruction_location
+ }
+ do_item (job_instance){
+ let id = job_instance.instruction_location_to_id(this.instruction_location)
+ if (id == job_instance.program_counter){
+ dde_error("In job." + job_instance.name +
+ " with a go_to instruction whose instruction_location: " + this.instruction_location +
+ " points to id: " + id +
+ " that is the same as this go_to instruction," +
+ " which would cause an infinite loop.")
+
+ }
+ else {
+ job_instance.program_counter = id
+ job_instance.set_up_next_do(0)
+ }
+ }
+ toString(){ return this.instruction_location }
+}
+
+Instruction.Control.grab_robot_status = class grab_robot_status extends Instruction.Control{
+ constructor (user_data_variable, //a string
+ start_index = Serial.DATA0, //integer
+ end_index=null) //if integer and same as starting field
+ //makes a vector of the starting_field value,
+ //otherwise makes array of the starting field THROUGH
+ //ending field. OR can be the string "end" meaning
+ //grab through the end of the array
+ {
+ super()
+ this.user_data_variable = user_data_variable
+ this.start_index = start_index
+ this.end_index = end_index
+ }
+ do_item (job_instance){
+ let rs = job_instance.robot.robot_status
+ let val
+ if (this.start_index == "data_array") {
+ this.start_index = Serial.DATA0
+ this.end_index = "end"
+ }
+ //set val
+ if (this.starting_field == "all") { val = rs }
+ else if (this.end_index) {
+ if (this.end_index === "end") { this.end_index = rs.length - 1 }
+ else if (this.start_index > this.end_index ) {
+ dde_error("instruction: grab_robot_status passed end_index: " + this.end_index +
+ " that is less than start_index: " + this.start_index)
+ }
+ else { val = rs.slice(this.start_index, this.end_index + 1) }
+ }
+ else { val = rs[this.start_index] } //the one case that val is not an array
+ job_instance.user_data[this.user_data_variable] = val
+ job_instance.set_up_next_do(1)
+ }
+ toString(){
+ return "grab_robot_status: " + this.user_data_variable
+ }
+}
+
+Instruction.Control.human_task = class human_task extends Instruction.Control{
+ constructor ({task="", dependent_job_names=[],
+ title, //don't give this default of "" because we reserve that for when you want NO title.
+ //without passing this, or passing "undefined", you get a smart default including the job name and "Human Task"
+ x=200, y=200, width=400, height=400, background_color = "rgb(238, 238, 238)"}={}) {
+ super()
+ this.task = task
+ this.dependent_job_names = dependent_job_names
+ this.title = title
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+ do_item (job_instance){
+ var hidden = '' +
+ ""
+ var buttons = '
'
+ if (this.title === undefined){
+ this.title = "Job: " + job_instance.name + ", Human Task"
+ if (job_instance.robot instanceof Human){
+ this.title = job_instance.name + " task for: " + job_instance.robot.name
+ }
+ }
+ else if (this.title == "") { this.title = "" }
+ show_window({content: this.task + "" + buttons + hidden,
+ callback: human_task_handler,
+ title: this.title,
+ x: this.x,
+ y: this.y,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color
+ })
+ }
+}
+
+var human_task_handler = function(vals){
+ var job_instance = Job[vals.job_name]
+ if (vals.clicked_button_value != "Done"){
+ job_instance.stop_for_reason("interrupted", "In human_task, user stopped this job.")
+ var dep_job_names = JSON.parse(vals.dependent_job_names) //If the user did not pass in a dependent_job_names arg when
+ //creating the human_job, dep_job_names will now be [] so the below if hits but
+ //the for loop has nothing to loop over so nothing will be done.
+ if (dep_job_names && Array.isArray(dep_job_names)){
+ for (let j_name of dep_job_names){
+ var j_inst = Job[j_name]
+ if (!j_inst.stop_reason){ //if j_inst is still going, stop it.
+ j_inst.stop_for_reason("interrupted", "In human_task, user stopped this job which is dependent on job: " + job_instance.name)
+ j_inst.set_up_next_do(1)
+ }
+ }
+ }
+ }
+ job_instance.set_up_next_do(1) //even for the case where we're stopping the job,
+ //this lets the do_next_item handle finishing the job properly
+}
+
+Instruction.Control.human_enter_choice = class human_enter_choice extends Instruction.Control{
+ constructor ({task="", user_data_variable_name="choice", choices=[], dependent_job_names=[],
+ show_choices_as_buttons=false, one_button_per_line=false,
+ title, x=200, y=200, width=400, height=400, background_color="rgb(238, 238, 238)"}={}) {
+ super()
+ this.task = task
+ this.user_data_variable_name = user_data_variable_name
+ this.choices = choices
+ this.show_choices_as_buttons = show_choices_as_buttons
+ this.one_button_per_line = one_button_per_line
+ this.dependent_job_names = dependent_job_names
+ this.title = title
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+ do_item (job_instance){
+ var hidden = "" +
+ "" +
+ ""
+ let select = ""
+ let buttons
+ if (this.show_choices_as_buttons){
+ for (var item of this.choices){
+ select += " "
+ if (this.one_button_per_line) { select += " " }
+ }
+ buttons = '
'
+ }
+ else { //show as menu items,the default because we can have more of them.
+ select = "
"
+ buttons = '
'
+ }
+ if (this.title === undefined){
+ this.title = "Job: " + job_instance.name + ", Human Task"
+ if (job_instance.robot instanceof Human){
+ this.title = job_instance.name + " task for: " + job_instance.robot.name
+ }
+ }
+ else if (this.title == "") { this.title = "" }
+ show_window({content: this.task + " " + select + " " + buttons + hidden,
+ callback: human_enter_choice_handler,
+ title: this.title,
+ x: this.x,
+ y: this.y,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color})
+ }
+}
+
+var human_enter_choice_handler = function(vals){
+ var job_instance = Job[vals.job_name]
+ if(vals.clicked_button_value == "Submit") { //means the choices are in a menu, not individual buttons
+ job_instance.user_data[vals.user_data_variable_name] = vals.choice
+ }
+ else if (vals.clicked_button_value == "Stop this & dependent jobs"){
+ job_instance.stop_for_reason("interrupted", "In human_task, user stopped this job.")
+ var dep_job_names = JSON.parse(vals.dependent_job_names) //If the user did not pass in a dependent_job_names arg when
+ //creating the human_job, dep_job_names will now be [] so the below if hits but
+ //the for loop has nothing to loop over so nothing will be done.
+ if (dep_job_names && Array.isArray(dep_job_names)){
+ for (let j_name of dep_job_names){
+ var j_inst = Job[j_name]
+ if (!j_inst.stop_reason){ //if j_inst is still going, stop it.
+ j_inst.stop_for_reason("interrupted", "In human_task, user stopped this job which is dependent on job: " + job_instance.name)
+ j_inst.set_up_next_do(1)
+ }
+ }
+ }
+ }
+ else { //individual choices are in buttons and the user clicked on one of them
+ job_instance.user_data = vals.clicked_button_value
+ }
+ job_instance.set_up_next_do(1) //even for the case where we're stopping the job,
+ //this lets the do_next_item handle finishing the job properly
+}
+
+Instruction.Control.human_enter_instruction = class human_enter_instruction extends Instruction.Control{
+ constructor ({task = "Enter a next instruction for this Job.",
+ instruction_type = "Dexter.move_all_joints (a)",
+ instruction_args = "5000, 5000, 5000, 5000, 5000",
+ dependent_job_names = [],
+ title, x=600, y=200, width=420, height=400, background_color="rgb(238, 238, 238)"}={}) {
+ super()
+ this.task = task
+ this.instruction_type = instruction_type
+ this.instruction_args = instruction_args
+ this.dependent_job_names = dependent_job_names
+ this.title = title
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+
+ make_instruction_options(){
+ let result = ""
+ let key_value_pairs = [] //Object.keys(Dexter.instruction_type_to_function_name_map).sort()
+ for(let oplet of Object.keys(Dexter.instruction_type_to_function_name_map)){
+ key_value_pairs.push([oplet, Robot.instruction_type_to_function_name(oplet)])
+ }
+ key_value_pairs.sort(function(a, b){ return ((a[1] < b[1])? -1 : 1 ) })
+ for (let pair of key_value_pairs){
+ let oplet = pair[0]
+ let name = pair[1]
+ let label = name + " (" + oplet + ")"
+ let sel_html = ((label == this.instruction_type) ? "selected" : "")
+ let the_html = "
" + label + "
"
+ result += the_html
+ }
+ return result
+ }
+
+ do_item (job_instance){
+ if (!job_instance.enter_instruction_recording) { //don't always init as might have instructions from prev dialog in this set
+ job_instance.enter_instruction_recording = []
+ }
+ var hidden = "" +
+ ""
+ var type_html = '' +
+ this.make_instruction_options() +
+ ''
+ let rs = job_instance.robot.robot_status
+ var immediate_do = ' or'
+
+ var args_html = ""
+ var buttons = '' +
+ '' +
+ ''
+ if (this.title === undefined) {
+ this.title = "Job: " + job_instance.name + ", Human Enter Instruction"
+ if (job_instance.robot instanceof Human){
+ this.title = job_instance.name + " task for: " + job_instance.robot.name
+ }
+ }
+ else if (this.title == "") { this.title = "" }
+ if(job_instance.robot instanceof Dexter){
+ out(Dexter.robot_status_to_html(job_instance.robot.robot_status, "on job: " + job_instance.name), "black", true)
+ }
+ show_window({content: "
" +
+ "Arguments: " + args_html + "" +
+ buttons +
+ hidden ,
+ callback: human_enter_instruction_handler,
+ title: this.title,
+ x: this.x,
+ y: this.y,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color //having larger than 350 does not increase the number of combo box menu items shown.
+ })
+ //setTimeout(function(){immediate_do_id.focus()}, 100) //always focus on immediate_do_id id because if user is in a loop using it, we might as well focus on it. No other widgets where focus would matter in this dialog
+ //above line can't work because we're in sandbox where immediate_do_id is unbound
+ immediate_do_id.focus()
+ }
+}
+
+var human_enter_instruction_handler = function(vals){
+ var job_instance = Job[vals.job_name]
+ var hei_instance = job_instance.do_list[job_instance.program_counter]
+ if (vals.clicked_button_value == "Stop this & dependent jobs"){
+ job_instance.enter_instruction_recording = []
+ job_instance.stop_for_reason("interrupted", "In human_enter_instruction, user stopped this job.")
+ var dep_job_names = JSON.parse(vals.dependent_job_names) //If the user did not pass in a dependent_job_names arg when
+ //creating the human_job, dep_job_names will now be [] so the below if hits but
+ //the for loop has nothing to loop over so nothing will be done.
+ if (dep_job_names && Array.isArray(dep_job_names)){
+ for (let j_name of dep_job_names){
+ let j_inst = Job[j_name]
+ if (!j_inst.stop_reason){ //if j_inst is still going, stop it.
+ j_inst.stop_for_reason("interrupted", "In human_enter_instruction, user stopped this job which is dependent on job: " + job_instance.name)
+ j_inst.set_up_next_do(1)
+ }
+ }
+ }
+ //close_window(vals.window_index) //not needed. this is a submit button
+ }
+ else if (vals.clicked_button_value == "Continue this job without reprompting") {
+ job_instance.enter_instruction_recording = []
+ //close_window(vals.window_index) //not needed. this is a submit button
+ }
+ else if (vals.clicked_button_value == "Save") {
+ let job_source_to_save = human_enter_instruction_job_source_to_save(job_instance)
+ Editor.insert(job_source_to_save, "selection_end")
+ job_instance.enter_instruction_recording = []
+ recorded_instructions_count_id.innerHTML = "0"
+ out("Human.enter_instruction: recorded instructions saved and cleared.", "purple", true)
+ immediate_do_id.focus()
+ return
+ }
+ else if (vals.clicked_button_value == "Clear") {
+ job_instance.enter_instruction_recording = []
+ recorded_instructions_count_id.innerHTML = "0"
+ out("Human.enter_instruction cleared all recorded instructions.", "purple")
+ immediate_do_id.focus()
+ return
+ }
+ else if (vals.clicked_button_value == "Erase last") {
+ let last_ins = job_instance.enter_instruction_recording.pop()
+ if (last_ins){
+ recorded_instructions_count_id.innerHTML = "" + job_instance.enter_instruction_recording.length
+ out("Human.enter_instruction erased the last previously recorded instruction of: " + stringify_value(last_ins),
+ "purple")
+ }
+ else {
+ out("There are no instructions in the recording to erase.", "red", true)
+ }
+ immediate_do_id.focus()
+ return
+ }
+
+ else { //Run ins & reprompt" or "immediate_do
+ let oplet, ins_type
+ if (vals.clicked_button_value == "immediate_do"){
+ if (vals.immediate_do == "") {
+ oplet = "a"
+ }
+ else {
+ oplet = last(vals.immediate_do)
+ }
+ ins_type = oplet //probably won't do any good as its hard to init the combo box to something other than one of its already named items.
+ close_window(vals.window_index)
+ //console.log("in human_enter_instruction_handler after close_window")
+ }
+ else { //user clicked a submit button so don't need to close the window.
+ ins_type = vals.instruction_type.trim()
+ if (ins_type.length == 1){ oplet = ins_type }
+ else {
+ oplet = ins_type.split("(")[1]
+ oplet = oplet[0]
+ }
+ }
+ let args = vals.args
+ let args_array = args.split(/,s*/) //the s* doesn't soak up the whitespace unfortunately
+ if ((vals.clicked_button_value == "immediate_do") && (vals.immediate_do == "")){
+ let rs = job_instance.robot.robot_status
+ args_array = make_ins(oplet, rs[Dexter.J1_ANGLE], rs[Dexter.J2_ANGLE],
+ rs[Dexter.J3_ANGLE], rs[Dexter.J4_ANGLE], rs[Dexter.J5_ANGLE])
+ }
+ else {
+ let new_array = make_ins(oplet)
+ for (let i = 0; i < args_array.length; i++){
+ new_array.push(parseFloat(args_array[i]))
+ }
+ args_array = new_array
+ }
+ if (vals.clicked_button_value == "immediate_do"){
+ let prefix = "Human.enter_instruction made instruction:"
+ if (vals.immediate_do == ""){
+ prefix = "Human.enter_instruction captured Dexter's joint angles for instruction:"
+ }
+ out(prefix + " " + stringify_value(args_array), "purple")
+ job_instance.enter_instruction_recording.push(args_array)
+ //don't to the above set_in_ui because the win is now closed, but the new count will show up when the window redisplays
+ }
+ let new_human_instruction = Human.enter_instruction({task: hei_instance.task, instruction_type: ins_type, instruction_args: args, dependent_job_names: hei_instance.dependent_job_names})
+ let new_ins_array = [args_array, new_human_instruction]
+ job_instance.insert_instructions(new_ins_array)
+ job_instance.added_items_count[job_instance.program_counter] = 1
+ }
+ job_instance.set_up_next_do(1) //even for the case where we're stopping the job,
+ //this lets the do_next_item handle finishing the job properly
+}
+
+var human_enter_instruction_job_source_to_save = function(job_instance){
+ let instructions_src = ""
+ let prefix = ""
+ for (let ins of job_instance.enter_instruction_recording){
+ let ins_src = "make_ins("
+ for (let i = Dexter.INSTRUCTION_TYPE; i < ins.length; i++){
+ let val = stringify_value_sans_html(ins[i])
+ let arg_prefix = ((i == Dexter.INSTRUCTION_TYPE) ? "" : ", ")
+ ins_src += arg_prefix + val
+
+ }
+ ins_src += ")"
+ instructions_src += prefix + ins_src
+ prefix = ",\n "
+ }
+ let new_job_name = "recorded_from_" + job_instance.name
+ let result = '\n' +
+'new Job({name: "' + new_job_name + '",\n' +
+' robot: Robot.' + job_instance.robot.name + ',\n' +
+' do_list: [' + instructions_src +
+'\n ]})\n'
+ return result + "Job." + new_job_name + ".start()\n"
+}
+
+Instruction.Control.human_enter_number = class human_enter_number extends Instruction.Control{
+ constructor ( {task="",
+ user_data_variable_name="a_number",
+ initial_value=0,
+ min=0,
+ max=100,
+ step=1,
+ dependent_job_names=[],
+ title, x=200, y=200, width=400, height=400, background_color="rgb(238, 238, 238)"}={}){
+ super()
+ this.task = task
+ this.user_data_variable_name = user_data_variable_name
+ this.initial_value=initial_value
+ this.min = min
+ this.max = max
+ this.step = step
+ this.dependent_job_names = dependent_job_names
+ this.title = title
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+
+ do_item (job_instance){
+ var hidden = "" +
+ "" +
+ ""
+
+ var number_html = "
" + this.user_data_variable_name + " = " + "
"
+ var buttons = '
'
+ if (this.title === undefined){
+ this.title = "Job: " + job_instance.name + ", Human Task"
+ if (job_instance.robot instanceof Human){
+ this.title = job_instance.name + " task for: " + job_instance.robot.name
+ }
+ }
+ else if (this.title == "") { this.title = "" }
+ show_window({content: this.task + " " + number_html + " " + buttons + hidden,
+ callback: human_enter_number_handler,
+ title: this.title,
+ x: this.x,
+ y: this.y,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color})
+ }
+}
+
+var human_enter_number_handler = function(vals){
+ var job_instance = Job[vals.job_name]
+ if (vals.clicked_button_value != "Submit"){
+ job_instance.stop_for_reason("interrupted", "In human_enter_number, user stopped this job.")
+ var dep_job_names = JSON.parse(vals.dependent_job_names) //If the user did not pass in a dependent_job_names arg when
+ //creating the human_job, dep_job_names will now be [] so the below if hits but
+ //the for loop has nothing to loop over so nothing will be done.
+ if (dep_job_names && Array.isArray(dep_job_names)){
+ for (let j_name of dep_job_names){
+ var j_inst = Job[j_name]
+ if (!j_inst.stop_reason){ //if j_inst is still going, stop it.
+ j_inst.stop_for_reason("interrupted", "In human_enter_number, user stopped this job which is dependent on job: " + job_instance.name)
+ j_inst.set_up_next_do(1)
+ }
+ }
+ }
+ }
+ else { //Done
+ var the_choice = parseFloat(vals.choice)
+ job_instance.user_data[vals.user_data_variable_name] = the_choice
+ }
+ job_instance.set_up_next_do(1) //even for the case where we're stopping the job,
+ //this lets the do_next_item handle finishing the job properly
+}
+
+Instruction.Control.human_enter_text = class human_enter_text extends Instruction.Control{
+ constructor ({task="",
+ user_data_variable_name="a_text",
+ initial_value="OK",
+ line_count=1, //if 1, makes an input type=text. If > 1 makes a resizeable text area
+ dependent_job_names=[],
+ title, x=200, y=200, width=400, height=400, background_color="rgb(238, 238, 238)"}={}) {
+ super()
+ this.task = task
+ this.user_data_variable_name = user_data_variable_name
+ this.initial_value = initial_value
+ this.line_count = line_count
+ this.dependent_job_names = dependent_job_names
+ this.title = title
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+
+ do_item (job_instance){
+ var hidden = "" +
+ "" +
+ ""
+ var text_html
+ if(this.line_count == 1){
+ text_html = this.user_data_variable_name + " = "
+ }
+ else {
+ text_html = this.user_data_variable_name + " = "
+ }
+ var buttons = '
" + buttons + hidden,
+ callback: human_enter_text_handler,
+ title: this.title,
+ x: this.x,
+ y: this.y,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color}
+ )
+ }
+}
+
+var human_enter_text_handler = function(vals){
+ var job_instance = Job[vals.job_name]
+ if (vals.clicked_button_value != "Submit"){
+ job_instance.stop_for_reason("interrupted", "In human_enter_text, user stopped this job.")
+ var dep_job_names = JSON.parse(vals.dependent_job_names) //If the user did not pass in a dependent_job_names arg when
+ //creating the human_job, dep_job_names will now be [] so the below if hits but
+ //the for loop has nothing to loop over so nothing will be done.
+ if (dep_job_names && Array.isArray(dep_job_names)){
+ for (let j_name of dep_job_names){
+ var j_inst = Job[j_name]
+ if (!j_inst.stop_reason){ //if j_inst is still going, stop it.
+ j_inst.stop_for_reason("interrupted", "In human_enter_text, user stopped this job which is dependent on job: " + job_instance.name)
+ j_inst.set_up_next_do(1)
+ }
+ }
+ }
+ }
+ else { //Done
+ var the_choice = vals.choice
+ job_instance.user_data[vals.user_data_variable_name] = the_choice
+ }
+ job_instance.set_up_next_do(1) //even for the case where we're stopping the job,
+ //this lets the do_next_item handle finishing the job properly
+}
+
+Instruction.Control.human_notify = class human_notify extends Instruction.Control{
+ constructor ({task="",
+ window=true,
+ output_pane=true,
+ beep_count=0,
+ speak=false,
+ //does not have x and y because those are automatically set to make
+ //multiple notify windows visible.
+ title, width=400, height=400, background_color="rgb(238, 238, 238)"}={}) {
+
+ super()
+ //copy_missing_fields(arguments[0], this) //BUG! doesn't get the default values from above
+ this.task=task,
+ this.window=window,
+ this.output_pane=output_pane,
+ this.beep_count=beep_count,
+ this.speak=speak
+ this.title = title
+ this.width = width
+ this.height = height
+ this.background_color = background_color
+ }
+
+ do_item (job_instance){
+ if (this.title === undefined){
+ this.title = job_instance.name + ", Notification"
+ if (job_instance.robot instanceof Human){
+ this.title += " for: " + job_instance.robot.name
+ }
+ }
+ else if (this.title == "") { this.title = "" }
+ var prefix = "
"
+ if (this.window){
+ show_window({content: prefix + " " + this.task,
+ y: human_notify.get_window_y(), //do y first since it might cause reset of positions
+ x: human_notify.get_window_x(),
+ title: this.title,
+ width: this.width,
+ height: this.height,
+ background_color: this.background_color
+ })
+ }
+ if (this.output_pane){
+ out(this.title + " " + prefix + this.task, "#951616")
+ }
+ var the_notifiy = this
+ beeps(this.beep_count,
+ function(){if (the_notifiy.speak){
+ speak({speak_data: the_notifiy.title + ", " + the_notifiy.task})
+ }})
+ job_instance.set_up_next_do(1)
+ }
+ static get_window_x(){
+ human_notify.window_x += 40
+ return window.outerWidth - 370 - human_notify.window_x
+ }
+ static get_window_y(){
+ human_notify.window_y += 40
+ if (human_notify.window_y > (window.outerHeight - 300)){
+ human_notify.window_x = 0
+ human_notify.window_y = 40
+ }
+ return human_notify.window_y
+ }
+}
+
+Instruction.Control.human_notify.window_x = 0
+Instruction.Control.human_notify.window_y = 0
+
+Instruction.Control.if_any_errors = class if_any_errors extends Instruction.Control{
+ constructor (job_names=[], instruction_if_error=null) {
+ super()
+ this.job_names = job_names
+ this.instruction_if_error = instruction_if_error
+ }
+ do_item (job_instance){
+ for(let job_name of this.job_names){
+ let j_inst = Job[job_name]
+ if (j_inst){
+ if ((j_inst.status_code == "errored") ||
+ (j_inst.status_code == "interrupted")){
+ let the_error_ins = this.instruction_if_error
+ if (the_error_ins == null){
+ let message = "In job: " + job_instance.name +
+ ", an instruction of type: Robot.if_any_errors, " +
+ "discovered that job: " + job_name + " has errored."
+ the_error_ins = Robot.error(message)
+ }
+ job_instance.insert_single_instruction(the_error_ins)
+ break;
+ }
+ }
+ else { dde_error("In job: " + job_instance.name +
+ ", an instruction of type: Robot.if_any_errors " +
+ "was passed a job name of: " + job_name + " that doesn't exist.")
+ return
+ }
+ }
+ job_instance.set_up_next_do(1)
+ }
+}
+
+Instruction.Control.label = class label extends Instruction.Control{
+ //also job_names may or may not contain the name of the current job. It doesn't matter.
+ constructor (name) {
+ super()
+ if (!name){
+ dde_error("Instruction label has not been passed a name.")
+ }
+ this.name = name
+ }
+ do_item (job_instance){
+ job_instance.set_up_next_do(1)
+ }
+ toString(){ return this.name }
+}
+
+Instruction.Control.out = class Out extends Instruction.Control{
+ constructor (val, color) {
+ super()
+ this.val = val
+ this.color = color
+ }
+ do_item (job_instance){
+ let message = "Job: " + job_instance.name + ", instruction ID: " + job_instance.program_counter + " " + this.val
+ out(message, this.color)
+ job_instance.set_up_next_do(1)
+ }
+ toString(){
+ return "" + this.val
+ }
+}
+
+Instruction.Control.send_to_job = class send_to_job extends Instruction.Control{
+ constructor ({//to_job_name = "required",
+ do_list_item = null, //can be null, a single instruction, or an array of instructions
+ where_to_insert = "required", //"next_top_level",
+ wait_until_done = false,
+ start = false,
+ unsuspend = false,
+ status_variable_name = null} = {}) {
+ super()
+ let params = arguments[0]
+ if (!params.where_to_insert || (params.where_to_insert == "required")) { //the defaults listed above don't actually work
+ //params.where_to_insert = "next_top_level"
+ dde.error("Instruction send_to_job ws not supplied with a 'where_to_send' instruction location.")
+ }
+ copy_missing_fields(params, this)
+ }
+
+ do_item (job_instance){ //job_instance is the "from" job
+ if (this.to_job_name == job_instance.name) { this.wait_until_done = false } //when a job is insterting code into itself,
+ //we don't want it to hang waiting for itself.
+ this.from_job_name = job_instance.name
+ this.from_instruction_id = job_instance.program_counter
+ var to_job_instance = Job[this.to_job_name]
+ if (this.status_variable_name){
+ job_instance.user_data[this.status_variable_name] = "sent"
+ }
+ this.destination_do_send_to_job(job_instance, to_job_instance) //this COULD be just a json obj of name value pairs. Don't really need the whole instance here.
+ //if we need to send to a job on another computer, convert to that json obj.
+ if(this.wait_until_done){
+ job_instance.wait_until_instruction_id_has_run = job_instance.program_counter
+ job_instance.set_up_next_do(0) //the one place I pass 0 here!
+ //since this is not going through robot_done_with_instruction
+ }
+ else{
+ job_instance.set_up_next_do(1)
+ }
+ }
+
+ //fns prefixed with destination are run on the to_job.
+//"this" is the send_to_job instruction instance
+//This fn is not a user fn and is not an instruction for a do_list.
+ destination_do_send_to_job(from_job_instance, to_job_instance){
+ let params = this
+ var to_job_instance = Job.instruction_location_to_job(params.where_to_insert)
+ if (!to_job_instance) { to_job_instance = from_job_instance }
+ //first, add destination_send_to_job_is_done to do_items if need be.
+ var do_items = params.do_list_item
+ var notify_item = null
+ if (params.wait_until_done){
+ //var send_back_obj = {from_job_name: params.from_job_name,
+ // from_instruction_id: params.from_instruction_id,
+ // status_variable_name: params.status_variable_name
+ // }
+ var notify_item = new Instruction.Control.destination_send_to_job_is_done(params)
+ //notify_item is appeneded to the end of do_items, and the whole array of instructions
+ //stuck into the destination job's do_list
+ if (do_items == null){
+ do_items = notify_item
+ }
+ else if (Instruction.is_instruction_array(do_items)){
+ if(notify_item){
+ do_items = [do_items, notify_item]
+ }
+ }
+ else if (Instruction.is_instructions_array(do_items)){
+ if(notify_item){
+ do_items = do_items.slice(0).push(notify_item)
+ }
+ }
+ else { //typically a function.
+ if(notify_item){
+ do_items = [do_items, notify_item]
+ }
+ }
+ }
+ // next, bundle do_items into a sent_from_job instruction
+ let sfj_ins = new Instruction.Control.sent_from_job({do_list_item: do_items,
+ from_job_name: from_job_instance.name,
+ from_instruction_id: from_job_instance.program_counter,
+ where_to_insert: params.where_to_insert, //just for debugging
+ wait_until_done: params.wait_until_done //just for debugging
+ })
+ if (to_job_instance.status_code == "not_started"){
+ if(params.start){
+ to_job_instance.start({initial_instruction: sfj_ins})
+ }
+ }
+ else {
+ //Instruction.Control.send_to_job.insert_sent_from_job(to_job_instance, sfj_ins)
+ Job.insert_instruction_at_location(sfj_ins, where_to_insert)
+ if (to_job_instance.status_code == "suspended"){
+ if(params.unsuspend){
+ to_job_instance.unsuspend()
+ //this.set_up_next_do(1) //don't do this because unsuspend does it.
+ }
+ }
+ }
+ //don't do this as to_job should already be running.
+ //else{
+ // to_job_instance.set_up_next_do(1)
+ //}
+ }
+
+ static insert_sent_from_job(to_job_instance, sfj_ins){
+ switch(sfj_ins.where_to_insert){
+ case "after_pc":
+ to_job_instance.insert_single_instruction(sfj_ins)
+ break;
+ case "end":
+ to_job_instance.do_list.push(sfj_ins)
+ break;
+ case "next_top_level":
+ to_job_instance.sent_from_job_instruction_queue.push(sfj_ins)
+ break;
+ default:
+ let valid = false
+ for(let to_job_ins_id = to_job_instance.program_counter;
+ to_job_ins_id < to_job_instance.do_list.length;
+ to_job_ins_id++){
+ if (to_job_ins_id < 0) { continue; } //might be on -1 (when job isn't started.)
+ let to_job_ins = to_job_instance.do_list[to_job_ins_id]
+ if ((to_job_ins instanceof Instruction.Control.sync_point) &&
+ (to_job_ins.name == sfj_ins.where_to_insert)) {
+ to_job_instance.do_list.splice(to_job_ins_id + 1, 0, sfj_ins)
+ valid = true
+ break;
+ }
+ }
+ if (!valid) {dde_error("The send_to_job instruction in job: " + sfj_ins.from_job_name +
+ " with id: " + sfj_ins.from_instruction_id +
+ " has a where_to_insert of: " + sfj_ins.where_to_insert +
+ " but there is no sync point with that name in job: " + to_job_instance.name +
+ " at or after the id of: " + to_job_instance.program_counter)
+ }
+ break;
+ }
+ }
+}
+
+Instruction.Control.send_to_job.param_names = ["do_list_item", "where_to_insert",
+ "wait_until_done", "start",
+ "unsuspend", "status_variable_name",
+ "from_job_name", "from_instruction_id",
+ "to_job_name"]
+
+//user's never create this directly, but an instance of this is created by destination_do_send_to_job
+//and stuck on the destination do_list.
+Instruction.Control.destination_send_to_job_is_done = class destination_send_to_job_is_done extends Instruction.Control{
+ constructor (params){
+ super()
+ this.params = params
+ }
+ do_item(job_instance){ //job_instance is the "to" job
+ var from_job_instance = Job[this.params.from_job_name]
+ for (var user_var of Object.getOwnPropertyNames(this.params)){ //we can have multiple user_data vars that we set. The vars arae set in the sending job
+ if(Instruction.Control.send_to_job.param_names.indexOf(user_var) == -1){ //if its not one of the regular paranms. that mens its the name of a user_data var to set in the from_job_instance
+ var fn = this.params[user_var]
+ if (typeof(fn) == "function"){
+ var val = fn.call(job_instance)
+ this.params[user_var] = val //this.params is really the to_job_instance.
+ }
+ else {
+ shouldnt("In job: " + job_instance.name +
+ " Instruction.Control.destination_send_to_job_is_done.do_item got user var: " + user_var +
+ " whose value: " + fn + " is not a function.")
+ }
+ }
+ }
+ from_job_instance.send_to_job_receive_done(this.params)
+ job_instance.set_up_next_do(1)
+ }
+}
+
+Instruction.Control.sent_from_job = class sent_from_job extends Instruction.Control{
+ constructor ({do_list_item = null, //can be null, a single instruction, or an array of instructions
+ from_job_name = "required",
+ from_instruction_id = "required",
+ where_to_insert = "next_top_level", //just for debugging
+ wait_until_done = null //just for debugging
+ } = {}) {
+ super()
+ let params = arguments[0]
+ if (!params.where_to_insert) { //the defaults listed above don't actually work
+ params.where_to_insert = "next_top_level"
+ }
+ copy_missing_fields(params, this)
+ }
+
+ do_item (job_instance){
+ if (Instruction.is_instruction_array(this.do_list_item) ||
+ !Array.isArray(this.do_list_item)){
+ job_instance.insert_single_instruction(this.do_list_item)
+ job_instance.added_items_count[job_instance.program_counter] = 1
+ }
+ else {
+ job_instance.insert_instructions(this.do_list_item)
+ job_instance.added_items_count[job_instance.program_counter] = this.do_list_item.length
+ }
+ job_instance.set_up_next_do(1)
+ }
+}
+
+Instruction.Control.start_job = class start_job extends Instruction.Control{
+ constructor (job_name) {
+ super()
+ this.job_name = job_name
+ }
+ do_item (job_instance){
+ const new_job = Job[this.job_name]
+ if (new_job){
+ new_job.start()
+ }
+ else {
+ job_instance.stop_for_reason("errored",
+ "In Job." + job_instance.name + " a start_job instruction attempted to start the undefined Job." + this.job_name)
+
+ }
+ job_instance.set_up_next_do(1)
+ }
+ toString(){
+ return "stop: " + this.reason
+ }
+}
+
+Instruction.Control.stop = class stop extends Instruction.Control{
+ constructor (reason) {
+ super()
+ this.reason = reason
+ }
+ do_item (job_instance){
+ job_instance.stop_for_reason("stopped", "Job: " + job_instance.name + " stopped for: " + this.reason)
+ //job_instance.set_up_next_do(0)
+ job_instance.do_next_item()
+ }
+ toString(){
+ return "stop: " + this.reason
+ }
+}
+
+Instruction.Control.suspend = class suspend extends Instruction.Control{
+ constructor (reason) {
+ super()
+ this.reason = reason
+ }
+ do_item (job_instance){
+ job_instance.status_code = "suspended"
+ //doesn't call set_up_next_do nor does it change the pc
+ }
+}
+
+Instruction.Control.sync_point = class sync_point extends Instruction.Control{
+ //permit an empty array for job_names. We might be getting such an array from some computation
+ //that legitimately has no items. Allow it. Then when this instruction's do_item is called,
+ //it will always be in_sync and proceed. Empty job_names also useful for send_to_job
+ //where_to_insert labels.
+ //also job_names may or may not contain the name of the current job. It doesn't matter.
+ constructor (name, job_names=[]) {
+ super()
+ if (!name){
+ dde_error("Instruction sync_point has not been passed a name.")
+ }
+ this.name = name
+ this.job_names = job_names
+ this.inserted_empty_instruction_queue = false
+ }
+ /*The below started from my old arch (pre aug 2016) in which when a sync point was encoutered,
+ and its other jobs hadn't reach their sync points yet, this job simly didn't have
+ its set_up_next_do called so it just was frozen.
+ Then the last job of the sync job group, got to here, it could "unfreeze" all the
+ other jobs. The great thing about this arch is that the 'frozen jobs' took up zreo compute time.
+ BUT when we want to move to the new arch of allowing job_a to wait for job_b but NOT have
+ job_b wait for job_a, this is no longer any good, because we would start out with Job_a
+ waiting for job_b. Then Job b comes along and jsut breezes though its sync point
+ since it doesn't wait for any job, and now job_a is hanging with no one to start it up again,
+ even though the sync point it was waiting for in job b had been achieved.
+ So job_a has to call set_up_next_do(0) while its waiting, just to see
+ if job_b has made it through its sync point. This is slower but will work,
+ however that means we have to get rid of the code wherein the last
+ job to reach its sync point unfreezes all the other jobs because we
+ really don't want to have a job get set_up_next_do called twice when
+ it is unfrozen. So in the new implementaiton (after this comment)
+ each job unfreezes itself. Slower, but gives us the
+ increased funtionality of the one_sided dependency with no extra args to sync_point.
+ If the slowdown becomes important we could re-implement the old sync point,
+ and have a different instruction to do the one_sides algorithm which is slower.
+
+ do_item (job_instance){
+ for(let job_name of this.job_names){
+ if (job_name != job_instance.name){ //ignore self
+ var j_inst = Job[job_name]
+ if(!j_inst){
+ job_instance.stop_for_reason("errored",
+ "Job." + job_instance.name +
+ " has a sync_point instruction that has a job-to-sync-with named: " + job_name +
+ " which is not defined.")
+ return;
+ }
+ // j_inst might have stopped, and perhaps completed fine so don't halt syn_point
+ // just because a job is stopped.
+ // else if (j_inst.stop_reason){
+ // job_instance.stop_for_reason("errored", "sync_point has a job-to-sync-with named: Job." + job_name +
+ // " that has already stopped.")
+ // return;
+ //}
+ else if (j_inst.program_counter < 0) {//j_inst hasn't started yet. That's ok, it just hasn't reached the sync point.
+ job_instance.wait_reason = "for Job." + j_inst.name + " to get to sync_point named: " + this.name + " but that Job hasn't started yet.."
+ //job_instance.status_code = "waiting" //don't change this from "not_started"
+ return
+ }
+ else {
+ var cur_instruction = j_inst.do_list[j_inst.program_counter]
+ if (j_inst.at_or_past_sync_point(this.name)){ continue; } //good. j_inst is at the sync point.
+ //beware that j_inst *could* be at a sync point of a different name, and if so,
+ //let's hope there's a 3rd job that it will sync with to get it passed that sync point.
+ else { //j_inst didn't get to sync point yet
+ job_instance.wait_reason = "for Job." + j_inst.name + " to get to sync_point named: " + this.name
+ job_instance.status_code = "waiting"
+ return; //we have not acheived sync, so just pause job_instance, in hopes
+ //that another job will be the last job to reach sync and force job_instance
+ //to proceed.
+ }
+ }
+ }
+ }
+ //made it through all job_names, so everybody's in sync
+ for(let job_name of this.job_names){
+ let j_inst = Job[job_name]
+ let cur_ins = j_inst.current_instruction()
+ if ((cur_ins instanceof Instruction.Control.sync_point) &&
+ (cur_ins.name == this.name) &&
+ (j_inst.status_code == "waiting")){ //beware that j_inst *might* already be past the
+ //sync point, or even stopped from completion, so above makes sure its merely AT the sync point, thus we can
+ //get it going again (but not attempt to do that if its already past the sync point).
+ j_inst.wait_reason = null
+ j_inst.status_code = "running"
+ j_inst.set_up_next_do(1)
+ }
+ }
+ //note that the above does NOT process job_instance because job_instance.status_code
+ //will be "running". If we get this far, job_instance will be the last
+ //sync_point job to reach its sync_point, and it will still be running,
+ //so just tell it to keep going with the below call to set_up.
+ //We put the below code AFTER the above loop so that the other jobs
+ //that reached their sync point first will be allowed to go ahead before job_instance.
+ job_instance.set_up_next_do(1)
+ }
+ */
+ do_item (job_instance){
+ if ((job_instance.robot instanceof Dexter) &&
+ (this.inserted_empty_instruction_queue == false) &&
+ (this.job_names.length > 0) &&
+ ((this.job_names.length > 1) || //must contain a job other than itself
+ (this.job_names[0] != job_instance.name))){ //the one job name its got is not job_instance so we've got to flush the instruction_queue
+ let instruction_array = Dexter.empty_instruction_queue()
+ job_instance.do_list.splice(job_instance.program_counter, 0, instruction_array);
+ this.inserted_empty_instruction_queue = true
+ job_instance.set_up_next_do(0) //go an do this empty_instruction_queue instruction, and when it finaly returns, to the sync_point proper
+ }
+ else {
+ for(let job_name of this.job_names){
+ if (job_name != job_instance.name){ //ignore self
+ var j_inst = Job[job_name]
+ if(!j_inst){
+ job_instance.stop_for_reason("errored",
+ "Job." + job_instance.name +
+ " has a sync_point instruction that has a job-to-sync-with named: " + job_name +
+ " which is not defined.")
+ return;
+ }
+ // j_inst might have stopped, and perhaps completed fine so don't halt syn_point
+ // just because a job is stopped.
+ // else if (j_inst.stop_reason){
+ // job_instance.stop_for_reason("errored", "sync_point has a job-to-sync-with named: Job." + job_name +
+ // " that has already stopped.")
+ // return;
+ //}
+ else if (j_inst.program_counter < 0) {//j_inst hasn't started yet. That's ok, it just hasn't reached the sync point.
+ job_instance.wait_reason = "for Job." + j_inst.name + " to get to sync_point named: " + this.name + " but that Job hasn't started yet.."
+ //job_instance.status_code = "waiting" //don't change this from "not_started"
+ job_instance.set_up_next_do(0)
+ return
+ }
+ else {
+ if (j_inst.at_or_past_sync_point(this.name)){ continue; } //good. j_inst is at the sync point.
+ //beware that j_inst *could* be at a sync point of a different name, and if so,
+ //let's hope there's a 3rd job that it will sync with to get it passed that sync point.
+ else { //j_inst didn't get to sync point yet
+ job_instance.wait_reason = "for Job." + j_inst.name + " to get to sync_point named: " + this.name
+ job_instance.status_code = "waiting"
+ job_instance.set_up_next_do(0)
+ return; //we have not acheived sync, so just pause job_instance, in hopes
+ //that another job will be the last job to reach sync and cause job_instance
+ //to proceed.
+ }
+ }
+ }
+ }
+ //made it through all job_names, so everybody's in sync, but each job has to unfreeze itself.
+ job_instance.set_up_next_do(1)
+ }
+ }
+}
+
+Instruction.Control.wait_until = class wait_until extends Instruction.Control{
+ constructor (fn_date_dur) {
+ super()
+ this.fn_date_dur = fn_date_dur
+ if (typeof(fn_date_dur) == "number") { this.fn_date_dur = new Duration(fn_date_dur) }
+ this.start_time = null
+ }
+ do_item (job_instance){
+ if (typeof(this.fn_date_dur) == "function"){
+ if (this.fn_date_dur.call(job_instance)) {
+ //console.log("wait_until fn returned true")
+ job_instance.wait_reason = null
+ job_instance.status_code = "running"
+ job_instance.set_up_next_do(1) //advance the PC
+ }
+ else {
+ job_instance.wait_reason = "until function returns true"
+ job_instance.status_code = "waiting"
+ job_instance.set_up_next_do(0) //loop until its true
+ }
+ }
+ else if (this.fn_date_dur instanceof Date){
+ if(Date.now() >= this.fn_date_dur){
+ job_instance.wait_reason = null
+ job_instance.status_code = "running"
+ job_instance.set_up_next_do(1)
+ }
+ else {
+ job_instance.wait_reason = "until Date: " + this.fn_date_dur
+ job_instance.status_code = "waiting"
+ job_instance.set_up_next_do(0)
+ }
+ }
+ else if (this.fn_date_dur instanceof Duration){
+ if (this.start_time == null) { this.start_time = Date.now() } //hits the first time this do_item is called for an inst
+ var dur_from_start = Date.now() - this.start_time
+ if (dur_from_start >= this.fn_date_dur.milliseconds){
+ job_instance.wait_reason = null
+ job_instance.status_code = "running"
+ this.start_time = null //essential for the 2nd thru nth call to start() for this job.
+ job_instance.set_up_next_do(1)
+ }
+ else if ((job_instance.robot instanceof Dexter) && (dur_from_start > 1000)){
+ //so that we can keep the tcp connection alive, send a virtual heartbeat
+ let new_instructions = [make_ins("g"), //just a do nothing to get a round trip to Dexter.
+ Brain.wait_until(this.fn_date_dur.milliseconds - 1000)] //create new wait_until to wait for the remaining time
+ job_instance.insert_instructions(new_instructions)
+ job_instance.status_code = "running"
+ job_instance.set_up_next_do(1)
+ }
+ else {
+ job_instance.wait_reason = "until Duration: " + this.fn_date_dur.milliseconds + " ms"
+ job_instance.status_code = "waiting"
+ job_instance.set_up_next_do(0)
+ }
+ }
+ }
+}
+
+//upper case G to avoid a conflict, but the user instruction is spelled Robot.get_page
+Instruction.Control.Get_page = class Get_page extends Instruction.Control{
+ constructor (url_or_options, response_variable_name) {
+ super()
+ this.url_or_options = url_or_options
+ this.response_variable_name = response_variable_name
+ this.sent = false
+ }
+ do_item (job_instance){
+ var the_var_name = this.response_variable_name //for the closures
+ if (this.sent == false){ //hits first time only
+ job_instance.user_data[the_var_name] = undefined //must do in case there was some other
+ //http_request for this var name, esp likely if its default is used.
+ get_page_async(this.url_or_options, //note I *could* simplify here and use get_page (syncrhonos), but this doesn't freeze up UI while getting the page so a little safer.
+ function(err, response, body) {
+ //console.log("gp top of cb with the_var_name: " + the_var_name)
+ //console.log("gp got err: " + err)
+ //console.log("ojb inst: " + job_instance)
+ //console.log("response: " + response)
+ if(err) { //bug err is not null when bad url
+ console.log("gp in err: ")
+ job_instance.user_data[the_var_name] = "Error: " + err
+ console.log("gp after err: ")
+ }
+ else if(response.statusCode !== 200){
+ job_instance.user_data[the_var_name] = "Error: in getting url: " + this.url_or_options + ", received error status code: " + response.statusCode
+ }
+ else {
+ //console.log("gp in good: ")
+ job_instance.user_data[the_var_name] = body
+ //console.log("gp after good: ")
+ }
+ })
+ this.sent = true
+ job_instance.set_up_next_do(0)
+ }
+ else if (job_instance.user_data[the_var_name] === undefined){ //still waiting for the response
+ job_instance.set_up_next_do(0)
+ }
+ else { job_instance.set_up_next_do(1)} //got the response, move to next instruction
+ }
+}
diff --git a/job.js b/job.js
new file mode 100644
index 00000000..f93ef220
--- /dev/null
+++ b/job.js
@@ -0,0 +1,1332 @@
+/**Created by Fry on 2/5/16. */
+var Job = class Job{
+ constructor({name=null, robot=new Brain(), do_list=[], keep_history=true, log_instructions=false,
+ inter_do_item_dur = 100, user_data={}, program_counter=0, initial_instruction = null} = {}){
+ //program_cpunter is the counter of the next instruction that should be executed.
+ //so since we're currently "executing" 1 instruction, and after its done,
+ //we'll be incrementing the pc, then internally we decriment the
+ //passed in program_counter. If its negative, it means
+ //computer it from the end, ie -1 means when set_next_do is called,
+ //it will set the pc to the length of the do_list, hence we'll be done
+ //with the job. -2 means we want to execute the last instruction of the
+ //job next, etc.
+ //save the args
+ this.orig_args = {do_list: do_list, keep_history: keep_history, log_instructions: log_instructions,
+ inter_do_item_dur: inter_do_item_dur, user_data: user_data,
+ program_counter: program_counter, initial_instruction: initial_instruction}
+ this.name = name
+ this.robot = robot
+ //setup name
+ Job.job_id_base += 1
+ this.job_id = Job.job_id_base
+ if (this.name == null){ this.name = "job_" + this.job_id }
+ Job[this.name] = this //beware: if we create this job twice, the 2nd version will be bound to the name, not the first.
+ Job.remember_job_name(this.name)
+ this.status_code = "not_started" //one of "not_started", "starting", "running" "completed", "suspended", "errored" "interrupted" (user stopped manually), "waiting" (wait_until, sync_point)
+ }
+
+ //Called by user to start the job and "reinitialize" a stopped job
+ start(options={}){ //sent_from_job = null
+ if(Job.disable_all){
+ out('Attempt to start Job: ' + this.name + " but all jobs have been disabled.")
+ }
+ else if (["starting", "running", "suspended"].includes(this.status_code)){
+ dde_error("Attempt to restart job: " + this.name +
+ " but it has status code: " + this.status_code +
+ " which doesn't permit restarting.")
+ }
+ else{//init from orig_args
+ this.do_list = Job.flatten_do_list_array(this.orig_args.do_list) //make a copy in case the user passes in an array that they will use elsewhere, which we wouldn't want to mung
+ this.keep_history = this.orig_args.keep_history
+ this.log_instructions = this.orig_args.log_instructions
+ this.inter_do_item_dur = this.orig_args.inter_do_item_dur
+ this.user_data = // don't do as gets non-enumerables, etc. messes up printing of what should be empty user_data of a job jQuery.extend(true, {}, this.orig_args.user_data) //performs deep copy. This is hard, so use jquery
+ shallow_copy(this.orig_args.user_data)
+ this.program_counter = this.orig_args.program_counter //see robot_done_with_instruction as to why this isn't 0,
+ //its because the robot.start effectively calls set_up_next_do(1), incremening the PC
+ this.initial_instruction = this.orig_args.initial_instruction
+ const sent_from_job = options.sent_from_job
+ delete options.sent_from_job //even if this field is not present, that's ok, this is a oop
+
+ //first we set all the orig (above), then we over-ride them with the passed in ones
+ for (let key in options){
+ if (options.hasOwnProperty(key)){
+ let new_val = options[key]
+ //if (key == "program_counter") { new_val = new_val - 1 } //don't do. You set the pc to the pos just before the first instr to execute.
+ if (key == "do_list") { new_val = Job.flatten_do_list_array(new_val) }
+ if (key == "user_data") { new_val = shallow_copy(new_val) }
+ this[key] = new_val
+ }
+ }
+ let maybe_symbolic_pc = this.program_counter
+ this.program_counter = 0 //just temporarily so that instruction_location_to_id can start from 0
+ this.program_counter = this.instruction_location_to_id(maybe_symbolic_pc)
+ if (this.program_counter >= this.do_list.length){ //note that maybe_symbolic_pc can be "end" which is length of do_list which is ok, though no instructions would be execute in that case so we error.
+ dde_error("While starting job: " + this.name +
+ " the programer_counter is initialized to: " + this.program_counter +
+ " but the highest instruction ID in the do_list is: " + (this.do_list.length - 1))
+ }
+ else if (this.program_counter >= this.do_list.length){
+ warning("While starting job: " + this.name +
+ " the programer_counter is initialized to: " + this.program_counter +
+ " but the highest instruction ID in the do_list is: " + (this.do_list.length - 1) +
+ ". so no instructions in this job will be executed.")
+ }
+ Job.last_job = this
+
+ //this.robot_status = [] use this.robot.robot_status instead //only filled in when we have a Dexter robot by Dexter.robot_done_with_instruction or a Serial robot
+ this.rs_history = [] //only filled in when we have a Dexter robot by Dexter.robot_done_with_instruction or a Serial robot
+ this.sent_instructions = []
+
+ this.start_time = new Date()
+ this.stop_time = null
+ this.status_code = "starting" //before setting it here, it should be "not_started"
+ this.stop_reason = null
+
+ this.wait_reason = null //not used when waiting for instruction, but used when status_code is "waiting"
+ this.wait_until_instruction_id_has_run = null
+ this.highest_completed_instruction_id = -1
+
+ //this.iterator_stack = []
+ this.sent_from_job_instruction_queue = [] //send_to_job uses this. its on the "to_job" instance and only stores instructions when send_to_job has
+ //where_to_insert="next_top_level"
+ if (this.initial_instruction) {
+ //Instruction.Control.send_to_job.insert_sent_from_job(this, sent_from_job)
+ Job.insert_instruction_at_location(this.initial_instruction, {job: this, offset: "program_counter"})
+ }
+ const added_items_initial_length =
+ this.added_items_count = new Array(this.program_counter) //This array parallels and should be the same length as the run items on the do_list.
+ this.added_items_count.fill(0) //stores the number of items "added" by each do_list item beneath it
+ //if the initial pc is > 0, we need to have a place holder for all the instructions before it
+ this.go_state = true
+ out("Starting job: " + this.name + " ...")
+ this.robot.start(this)
+ }
+ }
+
+ is_active(){ return ((this.status_code != "not_started") && (this.stop_reason == null)) }
+
+ //called in utils stringify_value used for original_do_list
+ static non_hierarchical_do_list_to_html(a_do_list){
+ var result = "
ID
" +
+ "
Instruction
"
+ for(var i = 0; i < a_do_list.length; i++){
+ result += "
" + i + "
" + stringify_value(a_do_list[i]) + "
"
+ }
+ result += "
"
+ return "original do_list" + result + ""
+ }
+
+ do_list_to_html(){
+ Job.do_list_to_html_set_up_onclick()
+ return "do_list" +
+ this.do_list_to_html_aux(0, 1) +
+ ""
+ }
+
+ static do_list_to_html_set_up_onclick(){
+ setTimeout(function(){
+ let elts = document.getElementsByClassName("do_list_item")
+ for (let i = 0; i < elts.length; i++) { //more clever looping using let elt of elts breaks but only on windows deployed DDE
+ let elt = elts[i]
+ elt.onclick = Job.do_list_item_present_robot_status }
+ }, 500)
+ }
+ //runs in UI
+ static do_list_item_present_robot_status(event){
+ event.stopPropagation();
+ let elt = event.target
+ let [job_name, instruction_id] = elt.dataset.do_list_item.split(" ")
+ Job.show_robot_status_history_item(job_name, parseInt(instruction_id))
+ }
+
+ instruction_id_to_rs_history_item(id){
+ for (let item of this.rs_history){
+ if (item[Dexter.INSTRUCTION_ID] == id) { return item }
+ }
+ if (this.keep_history){
+ shouldnt("Job.instruction_id_to_rs_history_item passed id: " + id + " but couldn't be found in rs_history: " + this.rs_history)
+ }
+ else { return null }
+ }
+
+ current_instruction(){
+ return this.do_list[this.program_counter]
+ }
+
+ is_top_level_do_item(do_item){
+ return this.orig_args.do_list.includes(do_item)
+ }
+
+ at_sync_point(sync_point_name){
+ let ins = this.current_instruction()
+ return ((ins instanceof Instruction.Control.sync_point) &&
+ (ins.name == sync_point_name))
+ }
+
+ at_or_past_sync_point(sync_point_name){
+ for(let a_pc = this.program_counter; a_pc >= 0; a_pc--){
+ let ins = this.do_list[a_pc]
+ if ((ins instanceof Instruction.Control.sync_point) &&
+ (ins.name == sync_point_name)) { return true }
+ }
+ return false
+ }
+
+ static show_robot_status_history_item(job_name, instruction_id){
+ let job_instance = Job[job_name]
+ let rs_history_item = job_instance.instruction_id_to_rs_history_item(instruction_id)
+ if (rs_history_item) {
+ let table_html = Dexter.robot_status_to_html_table(rs_history_item)
+ show_window({content: table_html,
+ title: "Robot status for " + job_name + ", instruction: " + instruction_id,
+ width: 800,
+ height: 380})
+ }
+ else {
+ out("Robot: " + job_instance.robot.name + " in job: " + job_instance.name +
+ " has not kept robot_status for instruction: " + instruction_id + "." +
+ " Job " + job_instance.name + " keep_history is: " + job_instance.keep_history,
+ "red")
+ }
+ }
+
+ do_list_to_html_aux(id_to_start_from = 0, indent_level = 0, sub_item_count){
+ if (!sub_item_count) {
+ if (this.do_list) { sub_item_count = this.do_list.length}
+ else { sub_item_count = 0 }
+ }
+ let result = ""
+ let sub_sub_items_processed = 0
+ for(let sub_item_index = 0; sub_item_index < sub_item_count; sub_item_index++){
+ let id = id_to_start_from + sub_item_index + sub_sub_items_processed
+ if (id >= this.do_list.length) {return result}
+ let item = this.do_list[id]
+ let new_sub_item_count = this.added_items_count[id]
+ let class_html = "class='do_list_item' "
+ let rs_button = ""
+ if (Instruction.is_instruction_array(item)) { rs_button = " "}
+ let item_text = "id=" + id +
+ " si=" + new_sub_item_count + "" +
+ rs_button +
+ " " + Instruction.text_for_do_list_item(item) //core of the_item
+ let html_indent = 'style="margin-left:' + (indent_level * 20) + 'px; background-color:' + Instruction.instruction_color(item) + ';"'
+
+ let actual_sub_items_grabbed_this_iter
+ if (new_sub_item_count > 0) {
+ item_text = "" + item_text + ""
+ let sub_items_text = this.do_list_to_html_aux(id + 1, indent_level + 1, new_sub_item_count)
+ item_text = item_text + sub_items_text + ""
+ actual_sub_items_grabbed_this_iter = (sub_items_text.match(/
" + item_text + "
"
+ actual_sub_items_grabbed_this_iter = 0
+ }
+
+ result += item_text
+ }
+ return result
+ }
+ time_to_string(a_time){
+ if (a_time){
+ return a_time.getHours() + ":" + a_time.getMinutes() + ":" + a_time.getSeconds()
+ }
+ else { return "null" }
+ }
+ stringify(){
+ let stat_code = this.status_code
+ if (stat_code == "completed") { stat_code = "completed" }
+ else if ((stat_code === "errored") || (stat_code === "interrupted")) {
+ stat_code = "" + stat_code + ""
+ }
+ let dur_string = milliseconds_to_human_string(this.stop_time - this.start_time)
+ let result = "Job name: " + this.name + ", job_id: " + this.job_id + ", is_simulating: " + this.is_simulating() + " " +
+ "start_time: " + this.time_to_string(this.start_time) +
+ ", stop_time: " + this.time_to_string(this.stop_time) +
+ ", dur: " + dur_string + " " +
+ "program_counter: " + this.program_counter + ", status_code: " + stat_code + ", " +
+ "stop_reason: " + this.stop_reason + ", wait_reason: " + this.wait_reason + " " +
+ "wait_until_instruction_id_has_run: " + this.wait_until_instruction_id_has_run + " " +
+ "highest_completed_instruction_id: " + this.highest_completed_instruction_id + " " +
+ "user_data: " + stringify_value(this.user_data) + ", " +
+ Job.non_hierarchical_do_list_to_html(this.orig_args.do_list) +
+ this.do_list_to_html() +
+ Dexter.sent_instructions_to_html(this.sent_instructions) +
+ Dexter.make_show_rs_history_button_html(this.job_id) +
+ ""
+
+ return result
+ }
+
+ //takes nested items in array and makes flattened list where the elts are
+ //a dexter instrution array, a fn, or something else that can be a do_item.
+ //could possibly return [] which will be ignored by do_next_item
+ static flatten_do_list_array(arr, result=[]){
+ for(let elt of arr){
+ if (Instruction.is_instruction_array(elt)) { result.push(elt) }
+ else if (Array.isArray(elt)) { //if elt is empty array, tbis works fine too.
+ Job.flatten_do_list_array(elt, result)
+ }
+ else if (elt == null) {} //includes undefined
+ else if (Instruction.is_control_instruction(elt)) { result.push(elt) }
+ else if (typeof(elt) === "function") { result.push(elt) }
+ else if (is_iterator(elt)) { result.push(elt) }
+ else if (elt === "debugger") { result.push(elt) }
+ else {
+ throw(TypeError("Job.flatten_do_list_array got illegal item on do list: " + elt))
+ }
+ }
+ return result
+ }
+ //can't be an instruction, must be called from a method
+ //unsuspend is like start, ie it calls start_after_connected which calls send get status
+ // which calls robot_done_with_instruction which calls set_up_next_do(1)
+ unsuspend(){
+ if (this.status_code == "suspended"){
+ this.status_code = "running"
+ this.set_up_next_do(1)
+ }
+ }
+ record_sent_instruction_stop_time(ins_id, stop_time){
+ if (this.keep_history){
+ for(let ins of this.sent_instructions){
+ if (ins[Instruction.INSTRUCTION_ID] === ins_id){
+ ins[Instruction.STOP_TIME] = stop_time
+ return
+ }
+ }
+ shouldnt("a_job.record_sent_instruction_stop_time passed ins_id: " + ins_id +
+ " but couldn't find an instruction with that id in Job." + this.name + ".sent_instructions")
+ }
+ }
+
+ xyz_for_rs_history(){
+ let result = []
+ let rob = this.robot
+ for(let rs of this.rs_history){
+ let angles = [rs[Dexter.J1_ANGLE], rs[Dexter.J2_ANGLE], rs[Dexter.J3_ANGLE], rs[Dexter.J4_ANGLE], rs[Dexter.J5_ANGLE]]
+ let a_xyz = Kin.J_angles_to_xyz(angles, rob.base_xyz, rob.base_plane, rob.base_rotation)[5]
+ result.push(a_xyz)
+ }
+ return result
+ }
+
+
+
+}
+Job.global_user_data = {}
+Job.job_id_base = 0 //only used for making the job_id.
+Job.disable_all = false //allows all jobs to run
+Job.all_names = [] //maintained in both UI and sandbox/ used by replacement series job names
+
+//note that once we make 1 job instance with a name, that binding of
+//Job.the_name never goes away, and that name will always be in the
+//the all_names list. But if you redefine a Job (with the same name)
+//the old value of that name is gc'd.
+Job.remember_job_name = function(job_name){
+ if (!Job.all_names.includes(job_name)){
+ Job.all_names.push(job_name)
+ $("#videos_id").prepend("
Job: " + job_name + "
")
+ }
+}
+
+Job.forget_job_name = function(job_name){
+ let i = Job.all_names.indexOf(job_name)
+ if (i != -1){
+ Job.all_names.splice(i, 1)
+ }
+}
+
+//we can't send to sandbox or UI, this has to work in both.
+//that's why we have Job.remember_job_name().
+//used by series replacement
+Job.is_job_name = function(a_string){
+ return Job.all_names.includes(a_string)
+}
+
+Job.all_jobs = function(){
+ let result = []
+ for(let name of Job.all_names){
+ result.push(Job[name])
+ }
+ return result
+}
+
+Job.job_id_to_job_instance = function(job_id){
+ for(let name of Job.all_names){
+ if (Job[name].job_id === job_id) {return Job[name]}
+ }
+ return null
+}
+
+Job.last_job = null
+
+Job.stop_all_jobs = function(){
+ var stopped_job_names = []
+ for(var j of Job.all_jobs()){
+ if (j.stop_reason == null){
+ j.status_code = "interruped"
+ j.stop_reason = "User stopped all jobs."
+ j.stop_time = new Date()
+ if (j.robot.heartbeat_timeout_obj) { clearTimeout(j.robot.heartbeat_timeout_obj) }
+ stopped_job_names.push(j.name)
+ }
+ // j.robot.close() //does not delete the name of the robot from Robot, ie Robot.mydex will still exist, but does disconnect serial robots
+ //this almost is a good idea, but if there's a job that's stopped but for some reason,
+ //its serial port is still alive, better to call serial_disconnect_all()
+ }
+ serial_disconnect_all()
+ if (stopped_job_names.length == 0){
+ out("There are no active jobs to stop.")
+ }
+ else {
+ out("Stopped jobs: " + stopped_job_names)
+ }
+}
+
+Job.clear_stopped_jobs = function(){
+ var cleared_job_names = []
+ for(var j of Job.all_jobs()){
+ if ((j.stop_reason != null) || (j.status_code = "not_started")){
+ delete Job[j.name]
+ Job.forget_job_name(j.name)
+ cleared_job_names.push(j.name)
+ if (j == Job.last_job) { Job.last_job = null }
+
+ }
+ }
+ if ((Job.last_job === null) && (Job.all_names.length > 0)){
+ Job.last_job = last(Job.all_names) //not technically the last job created since
+ //that was deleted
+ //and might not even be the last job "redefined".
+ //but its pretty close and the use of last_job isn't really sensitve to
+ //being precise so this is pretty good.
+ }
+ if (cleared_job_names.length == 0){
+ out("There are no stopped jobs to clear.")
+ }
+ else { out("Cleared jobs: " + cleared_job_names) }
+}
+
+//used in making robot_status_history window.
+/* this functionality doesn't match its name, and its never called so don't have it!
+Job.prototype.highest_sent_instruction_id = function(){
+ if (this.sent_instructions.length > 0){
+ return this.sent_instructions[0]
+ }
+ else { return null }
+}*/
+
+Job.report = function(){
+ if (Job.all_names.length == 0){
+ out("Either no jobs have been created in this session, " +
+ "or all the jobs have been cleared. " +
+ "See the Insert example menu item " +
+ "for help in creating a job.")
+ }
+ else {
+ result = "
Job Name
ID
Robot
Start Time
Stop Time
Status
"
+ for (var j of Job.all_jobs()){
+ var start_time = "Not started"
+ var stop_time = ""
+ if (j.start_time){
+ start_time = j.start_time.getHours() + ":" +
+ j.start_time.getMinutes() + ":" +
+ j.start_time.getSeconds() + ":" +
+ j.start_time.getMilliseconds()
+ stop_time = "ongoing"
+ }
+ if (j.stop_time){
+ stop_time = j.stop_time.getHours() + ":" +
+ j.stop_time.getMinutes() + ":" +
+ j.stop_time.getSeconds() + ":" +
+ j.stop_time.getMilliseconds()
+ }
+ var action = 'Job.print_out_one_job,,' + j.name
+ //var name = "" + j.name + ""
+ var job_name = "" + j.name + ""
+
+ result += "
" + job_name + "
" + j.job_id + "
" + j.robot.name + "
" + start_time + "
" + stop_time + "
" + j.status() + "
"
+ }
+ result += "
"
+ out(result)
+ install_onclick_via_data_fns()
+ }
+}
+
+Job.prototype.print_out = function(){
+ out(this.stringify())
+ //setTimeout(function(){install_onclick_via_data_fns()}, 200) //needs to let the html render.
+}
+
+Job.print_out_one_job = function(job_name){
+ var j = Job[job_name]
+ j.print_out()
+}
+
+Job.prototype.status = function (){
+ if (this.stop_reason) { return this.status_code + ": " + this.stop_reason }
+ else if (this.wait_reason) { return this.status_code + ": " + this.wait_reason}
+ else {
+ let len = this.orig_args.do_list.length
+ if ( this.do_list) { len = this.do_list.length }
+ let pc = 0
+ if (this.program_counter) { pc = this.program_counter }
+ return this.status_code + ", pc: " + pc + " of " + len
+ }
+}
+
+Job.prototype.is_simulating = function(){
+ return this.robot.simulate //don't look at this.socket_id because that won't be inited until after we call start and get back the socket_id
+ //when in simulation, the job_id is always the same integer j.send(Dexter.get_robot_status()) //doesn't go on do_list, I guess that's ok. do_next_item still hasn't been called once yet
+}
+
+Job.prototype.finish_job = function(){ //regardless of more to_do items or wiating for instruction, its over.
+ this.robot.finish_job()
+ this.print_out()
+ out("Done with job: " + this.name)
+}
+
+Job.go_button_state = true
+
+Job.set_go_button_state = function(bool){ //called initially from sandbox
+ pause_id.checked = !bool
+ Job.go_button_state = bool
+}
+
+Job.go = function(){
+ if (Job.go_button_state){
+ let any_active_jobs = false
+ for(let a_job of Job.all_jobs()){
+ if (a_job.is_active()){
+ any_active_jobs = true
+ if (a_job.go_state) {} //user hit go button with go_button_state true and a_job go true. let it run
+ //a_job.set_up_next_do(a_job.pause_next_program_counter_increment, false)
+ else { //go_button state is true but a_job go is false so turn it on an run
+ a_job.go_state = true
+ a_job.set_up_next_do(a_job.pause_next_program_counter_increment, false)
+ }
+ }
+ }
+ if (!any_active_jobs) { warning("There are no active jobs.", true) }
+ }
+ else { //go_button_state is false
+ let any_active_jobs = false
+ for(let a_job of Job.all_jobs()){
+ if (a_job.is_active()){
+ any_active_jobs = true
+ //if (a_job.go_state) {
+ a_job.set_up_next_do(a_job.pause_next_program_counter_increment, true) //allow once
+ //}
+ //else {} //go_button_state is false and a_job go is false, already paused, do nothing
+ }
+ }
+ if (!any_active_jobs) { warning("There are no active jobs.", true) }
+ }
+ return "dont_print"
+}
+
+//in EVERY call, as of mar 7, 2016 the arg is 1. So probably should just get rid of the arg.
+//nope: we need it to be 0 when we have a fn that is "looping" checking for some
+//condition to be true, in which case it moves on to incfement by 1, like "sleep" or something.
+//this is important because send_to_job might do insert of its instruction "after_pc"
+//and we want that to be in a "good" spot, such that the inserted insetruction
+//will run next. So we want to keep the incrementing of the PC to be
+//in the setTimeout so that when we do a insert "after_pc",
+//that inserted instruction is run next.
+Job.prototype.set_up_next_do = function(program_counter_increment = 1, allow_once=false){ //usual arg is 1 but a few control instructions that want to take a breath call it with 0
+ var job_instance = this
+ if (Job.go_button_state || allow_once){ //the normal case
+ if (program_counter_increment > 0) {
+ job_instance.highest_completed_instruction_id = job_instance.program_counter
+ }
+ job_instance.program_counter += program_counter_increment
+ setTimeout(function(){
+ job_instance.do_next_item()
+ },
+ this.inter_do_item_dur)
+ }
+ else {
+ job_instance.pause_next_program_counter_increment = program_counter_increment
+ job_instance.go_state = false
+ let suffix = ""
+ if (job_instance.program_counter == -1) { suffix = " (initing robot status)" }
+ else if (job_instance.program_counter == 0) { suffix = " (your first instruction)" }
+ else if (job_instance.program_counter == job_instance.do_list.length - 1) { suffix = " (last instruction)" }
+ else if (job_instance.program_counter == job_instance.do_list.length - 2) { suffix = " (2nd to last instruction)" }
+ let out_text = job_instance.name + " paused after program_counter=" + job_instance.program_counter + " of " +
+ job_instance.do_list.length + suffix + " "
+ if(job_instance.program_counter >= 0) {
+ out_text += "Prev ins: " + Instruction.text_for_do_list_item_for_stepper(this.do_list[job_instance.program_counter])
+ }
+ else { out_text += "Prev ins: None" }
+ out_text += " Next ins: "
+ if ((job_instance.program_counter + 1) >= job_instance.do_list.length){
+ out_text += "None"
+ }
+ else {
+ out_text += Instruction.text_for_do_list_item_for_stepper(this.do_list[job_instance.program_counter + 1])
+ }
+ out(out_text, "brown", true)
+ }
+}
+
+Job.prototype.stop_for_reason = function(status_code, //"errored", "interrupted", "completed"
+ reason_string){
+ this.status_code = status_code
+ this.stop_reason = reason_string
+ this.stop_time = new Date()
+}
+
+
+Job.prototype.do_next_item = function(){ //user calls this when they want the job to start, then this fn calls itself until done
+ //this.program_counter += 1 now done in set_up_next_do
+ if (this.log_instructions){
+ console.log("Top of do_next_item in job: " + this.name + " with PC: " + this.program_counter)
+ }
+ //this.pc_at_do_item_start = this.program_counter
+ if (Job.disable_all){//stop even if we're waiting for instrunctions to be confirmed done.
+ this.stop_for_reason("interrupted", "Job: " + this.name + " and all jobs disabled.")
+ this.finish_job()
+ }
+ else if ((this.status_code == "interrupted") || //put before the wait until instruction_id because interrupted is the user wanting to halt, regardless of pending instructions.
+ (this.status_code == "errored")){
+ this.finish_job()
+ }
+ else if (this.wait_until_instruction_id_has_run || (this.wait_until_instruction_id_has_run === 0)){ //the ordering of this clause is important. Nothing below has go wait for instructions to complete
+ //wait for the wait instruction id to be done
+ //the waited for instruction coming back thru robot_done_with_instruction will call set_up_next_do(1)
+ //so don't do it here. BUT still have this clause to block doing anything below if we're waiting.
+ }
+ else if (this.stop_reason){ this.finish_job() }
+ else if (this.program_counter >= this.do_list.length) { //&& (this.iterator_stack.length == 0)
+ //the normal stop case
+ if ((this.robot instanceof Dexter) &&
+ ((this.do_list.length == 0) ||
+ (last(this.do_list)[Dexter.INSTRUCTION_TYPE] != "g"))){
+ this.program_counter = this.do_list.length //probably already true, but just to make sure.
+ this.do_list.splice(this.do_list.length, 0, Dexter.get_robot_status()) //this final instruction naturally flushes dexter'is instruction queue so that the job will stay alive until the last insetruction is done.
+ this.set_up_next_do(0)
+ }
+ else if (!this.stop_reason){
+ this.stop_for_reason("completed", "Finished all do_list items.")
+ this.finish_job()
+ }
+ else { this.finish_job() }
+ }
+
+ else{
+ //regardless of whether we're in an iter or not, do the item at pc. (might or might not
+ //have been just inserted by the above).
+ var cur_do_item = this.current_instruction()
+ if (this.log_instructions) { console.log(" now processing instruction: " + stringify_value(cur_do_item))}
+ if (this.program_counter >= this.added_items_count.length) { this.added_items_count.push(0)} //might be overwritten further down in this method
+ else if (this.added_items_count[this.program_counter] > 0) { //will only happen if we go_to backwards,
+ //in which case we *might* call an instruction twice that makes some items that it adds to the to_do list.
+ //so we want to get rid of those items and "start over" with that instruction.
+ const sub_items_count = this.added_items_count[this.program_counter]
+ this.do_list.splice(this.program_counter + 1, sub_items_count) //cut out the sub-items under the pc instruction
+ }
+ if (cur_do_item == null){ //nothing to do, just skip it.
+ this.set_up_next_do(1)
+ }
+ else if ((this.sent_from_job_instruction_queue.length > 0) &&
+ this.is_top_level_do_item(cur_do_item)){
+ //bad, inserts after pc not AT pc this.insert_instructions(this.sent_from_job_instruction_queue) //all items on queue are next_top_level, so just insert them all.
+ this.do_list.splice(this.program_counter, 0, ...this.sent_from_job_instruction_queue)
+ //note we're inserting sent_from_job instructions, not the REAL instruction we want to execute.
+ //that's because in the hierarchical do_list display, we want to see where those REAL instructions came from for debugging purposes.
+ this.sent_from_job_instruction_queue = []
+ this.set_up_next_do(0)
+ }
+ else if (Array.isArray(cur_do_item) && (cur_do_item.length == 0)){ //nothing to do, just skip it.
+ this.set_up_next_do(1)
+ }
+ else if (Instruction.is_control_instruction(cur_do_item)){
+ cur_do_item.do_item(this)
+ }
+ else if (Instruction.is_instruction_array(cur_do_item)){
+ this.wait_until_instruction_id_has_run = this.program_counter
+ this.send(cur_do_item)
+ }
+ /* for (var i = 0; i <= this.max_contiguous_instructions; i++){
+ if(i > 0) {this.program_counter += 1}
+ if (i == this.max_contiguous_instructions){
+ this.stop_for_reason("error", "Job: " + this.name + " has " + this.max_contiguous_instructions +
+ " instructions on the do list. " +
+ "That's too many. You might have an infinite loop. " +
+ "If you legitimately put that many instruction in one fell swoop, " +
+ "that prevents this job from getting proper feedback from Dexter.")
+ break;
+ }
+ else if(this.program_counter > this.do_list.length){ shouldnt("in do_next_item, instruction_array processing, pc is > doList.length")}
+ else if(this.program_counter === this.do_list.length){ //turn off heartbeat, but don't close socket until we've waited for the final instruction to be done
+ //this will not hit on the first iteration of this for loop,
+ //because this case would have been caught above.
+ this.program_counter -= 1 //LET Dexter.robot_done_with_instruction increment the PC and let the top of do_next_item
+ //catch that we're done and set the reason.
+ this.wait_until_instruction_id_has_run = this.program_counter
+ //even though we've sent out all the items on the do list, don't quit
+ //until the last sent item is confirmed done and robot_done_with_instruction calls
+ //set_up_next_do
+ break;
+ }
+ else {
+ var cur_do_item = this.do_list[this.program_counter] //for the first of a seq of instruction arrays, we end up retriveing it twice from the to do list but for non first, we need this each loop iteration
+ if (Instruction.is_instruction_array(cur_do_item)){ //first one will get this check twice (first is above) but that's ok
+ if ("gz".indexOf(cur_do_item[0]) != -1){
+ this.wait_until_instruction_id_has_run = this.program_counter
+ //this.set_up_next_do(1) //don't want to run this instruction again
+ this.send(cur_do_item)
+ break;
+ }
+ else {
+ this.send(cur_do_item)
+ }
+ }
+ else {//got non array so we finished the continuous arrays so done with do_next_item
+ //we just put out a list of instructions so wait until they're run before
+ //running any more do_list items
+ //this will not hit the first iteration
+ this.program_counter -= 1 //LET Dexter.robot_done_with_instruction increment the PC
+ this.wait_until_instruction_id_has_run = this.program_counter
+ break;
+ }
+ }
+ }
+ } */
+ else if (is_iterator(cur_do_item)){ //must be before "function" because an iterator is also of type "function".
+ var next_obj = cur_do_item.next()
+ var do_items = next_obj.value
+ if (next_obj.done){ //don't insert cur_do_item (the iterator) cause we're all done.
+ if (do_items) { //happens when our gen fn has a return value.
+ if(Instruction.is_instructions_array(do_items)){ this.insert_instructions(do_items) }
+ else { this.insert_single_instruction(do_items) }
+ this.set_up_next_do(1)
+ }
+ else { //normal, we're beyond the last yield but just did our next call to "exhaust" the gen. nothing to do for cur_do_item
+ this.set_up_next_do(1)
+ }
+ }
+ else { //iterator not done. push the next_obj.value into the do_list followed by the iterator in cur_do_item
+ if(Instruction.is_instructions_array(do_items)){
+ do_items = do_items.slice(0) //copy the do_items just in case user is hanging on to that array, we don't want to mung it.
+ }
+ else if (do_items == null) { do_items = [] } //no point in sticking null on do_list as its a no-op. An iterator might return null because
+ //its waiting for some callback to complete as in dxf_to_instructions,
+ //so throw out the null and let do_list loop around again.
+ else {//just one item
+ do_items = [do_items]
+ }
+ do_items.push(cur_do_item) //add the iterator on the end so that after we do these "next" items, we'll call next again on the iterator
+ this.insert_instructions(do_items)
+ this.set_up_next_do(1)
+ }
+ }
+ //else if (is_iterator(cur_do_item)){ //calling a generator fn returns an iterator
+ // this.iterator_stack.push([cur_do_item, this.program_counter])
+ // this.set_up_next_do(1)
+ //}
+ else if (typeof(cur_do_item) == "function"){
+ var do_items = cur_do_item.call(this)
+ this.handle_function_call_or_gen_next_result(cur_do_item, do_items)
+ }
+ else if (cur_do_item == "debugger"){
+ Job.set_go_button_state(false)
+ this.set_up_next_do(1)
+ }
+ else {
+ this.stop_for_reason("errored", "Job: " + this.name + " got illegal do_item on do_list of: " +
+ stringify_value(cur_do_item))
+ //It's over, Jim, So don't take a breath, by calling set_up_next_do(0),
+ //just kill it quickly before anything else can happen.
+ //we don't want to increment the pc,
+ this.do_next_item()
+ }
+ }
+}
+
+/*cur_do_item is the fn, do_items is the val returned from calling it.
+ cur_do_item merely for error message. the real item to do is do_items which might be an array of items
+
+ A do_list function on the do_list can return:
+ - an instruction_array (1 letter op_let) stick it on the do_list and send it.
+ - an array of items to stick on the do_list.
+ - another function. stick it on the do_list and next time call it.\
+ - a generator function
+ - an iterator
+ Stick them all (except for iterator) on the do_list and execute them.
+ */
+Job.prototype.handle_function_call_or_gen_next_result = function(cur_do_item, do_items){
+ if ((do_items == null) || (Array.isArray(do_items) && (do_items.length == 0))) {//ok, just nothing to insert
+ this.set_up_next_do(1)
+ }
+ else if (do_items == "dont_call_set_up_next_do"){
+ //do nothing as the fn that was called is expected to have called its
+ //own do_next_item, perhaps via a "I'm done callback" to the fn that
+ //does the real work. such as beep({callback: function(){job_instance.set_up_next_do() } )
+ }
+ else if (Instruction.is_instruction_array(do_items) ||
+ Instruction.is_control_instruction(do_items) ||
+ (typeof(do_items) == "function") //ok if this includes generator functions
+ ) {
+ this.insert_single_instruction(do_items)
+ this.added_items_count[this.program_counter] = 1
+ this.set_up_next_do(1)
+ }
+ else if (Array.isArray(do_items)){
+ let flatarr = Job.flatten_do_list_array(do_items)
+ this.insert_instructions(flatarr)
+ this.added_items_count[this.program_counter] = flatarr.length
+ this.set_up_next_do(1)
+ }
+ else if (is_iterator(do_items)){ //calling a generator fn returns an iterator
+ //this.iterator_stack.push([do_items, this.program_counter])
+ //this.set_up_next_do(1)
+ this.insert_single_instruction(do_items)
+ this.added_items_count[this.program_counter] = 1
+ this.set_up_next_do(1)
+ }
+ else if (do_items == "debugger"){
+ this.insert_single_instruction(do_items)
+ this.added_items_count[this.program_counter] = 1
+ this.set_up_next_do(1)
+ }
+ else {
+ this.stop_for_reason("errored", "do_item function: " + stringify_value(cur_do_item) +
+ " returned invalid value: " + stringify_value(do_items))
+ //its over. Don't take a breath with set_up_next_do, kill it off.
+ //don't increment pc
+ this.do_next_item()
+ }
+}
+
+Job.prototype.insert_single_instruction = function(instruction_array){
+ let the_do_list = this.do_list
+ //if (!the_do_list){ the_do_list = this.orig_args.do_list }
+ the_do_list.splice(this.program_counter + 1, 0, instruction_array);
+}
+
+Job.prototype.insert_instructions = function(array_of_do_items){
+ this.do_list.splice.apply(this.do_list, [this.program_counter + 1, 0].concat(array_of_do_items));
+}
+
+Job.prototype.send = function(instruction_array){ //if remember is false, its a heartbeat
+ var instruction_id
+ if(instruction_array[Instruction.INSTRUCTION_TYPE] == "h") { //op_let is first elt UNTIL we stick in the instuction id
+ //instruction_id = -1 //heartbeat always has instruction id of -1
+ shouldnt('Job.send passed "h" instruction (heartbeat) but that shouldnt happen as heartbeat is handled lower level by Dexter robot')
+ }
+ else if (this.status_code == "not_started"){ //instuction_array should be a Job.get_robot_status
+ instruction_id = -3 //looked at by robot_done_with_instruction
+ }
+ else if (this.status_code == "starting"){ //instuction_array should be a Job.get_robot_status
+ instruction_id = -1 //looked at by robot_done_with_instruction
+ }
+ else{
+ instruction_id = this.program_counter
+ }
+ instruction_array[Instruction.JOB_ID] = this.job_id
+ instruction_array[Instruction.INSTRUCTION_ID] = instruction_id
+ instruction_array[Instruction.START_TIME] = Date.now()
+ if (this.keep_history){
+ this.sent_instructions.push(instruction_array) //for debugging mainly
+ }
+ this.robot.send(instruction_array)
+}
+
+//"this" is the from_job
+//send_to_job_receive_done is kinda like Serial and Dexter.robot_done_with_instruction
+//but used only with sent_to_job and only when the from_job is waiting for the
+//to_job to complete the ins it was sent before allowing the from_job to continue.
+Job.prototype.send_to_job_receive_done = function(params){
+ if (this.wait_until_instruction_id_has_run == params.from_instruction_id){
+ this.highest_completed_instruction_id = params.from_instruction_id
+ this.wait_until_instruction_id_has_run = null
+ for (var user_var in params){
+ if (Instruction.Control.send_to_job.param_names.indexOf(user_var) == -1){
+ var val = params[user_var]
+ this.user_data[user_var] = val
+ }
+ }
+ this.user_data[params.status_variable_name] = "done"
+ this.set_up_next_do(1)
+ }
+ else {
+ shouldnt("In job: " + this.name + " destination_send_to_job_is_done got params.from_instruction_id of: " +
+ params.from_instruction_id +
+ " but wait_until_instruction_id_has_run is: " + this.wait_until_instruction_id_has_run)
+ }
+}
+
+//right now I don't use this (a_job) but will need it in the future to get a_job.robot. its transformations
+Job.prototype.dxf_to_instructions = function (filepath, scale = 1, up_distance = 2000){
+ let the_content
+ if((filepath.length <= 512) &&
+ (filepath.endsWith(".dxf") || filepath.endsWith(".DXF"))){
+ the_content = file_content(filepath)
+ }
+ else { the_content = filepath }
+ scale = scale_to_micron_factor(scale)
+ let parser = new DxfParser();
+ try {
+ let dxf_entities = parser.parseSync(the_content).entities
+ let prev_xyz = null
+ let ins = []
+ for(let i = 0; i < dxf_entities.length; i++){
+ ent = dxf_entities[i]
+ if (ent.type == "LINE"){
+ let a = point_object_to_array(ent.vertices[0])
+ let b = point_object_to_array(ent.vertices[1])
+ a = scale_point(a, scale)
+ b = scale_point(b, scale)
+ if (prev_xyz == null) {
+ if ((dxf_entities.length > 1) &&
+ (point_equal(a, point_object_to_array(dxf_entities[1].vertices[0])) ||
+ point_equal(a, point_object_to_array(dxf_entities[1].vertices[1])))){
+ let c = a; a = b; b = c //swap
+ }
+ //ins.push(Dexter.move_to_relative([0, 0, up_distance])) //probably a bad idea. Plus I want to get rid of the relative calls.
+ ins.push(Dexter.move_to([a[0], a[1], a[2] + up_distance]))
+ ins.push(Dexter.move_to(a))
+ if (!point_equal(a, b)){
+ ins.push(Dexter.move_to(b))
+ }
+ prev_xyz = b
+ }
+ else {
+ if (point_equal(prev_xyz, b)){
+ let c = a; a = b; b = c //swap
+ }
+ //Now if prev is equal to orig a or orig b, then
+ //that orig equal point is in a, ie a and b are ordered correctly
+ if (prev_xyz != a) {
+ ins.push(Dexter.move_to([prev_xyz[0], prev_xyz[1], prev_xyz[2] + up_distance]))
+ ins.push(Dexter.move_to([a[0], a[1], a[2] + up_distance]))
+ ins.push(Dexter.move_to(a)) //pen down
+ }
+
+ if (!point_equal(a, b)){
+ ins.push(Dexter.move_to(b))
+ }
+ prev_xyz = b
+ }
+ }
+ }//end for
+ return ins
+ }
+ catch(err) { out(err.message); }
+}
+
+//right now I don't use this (a_job) but will need it in the future to get a_job.robot. its transformations
+Job.prototype.gcode_to_instructions = function* (filepath, scale = 1){
+ let the_content = null
+ file_content(filepath, function(content){
+ the_content = content //closed over in outer context
+ })
+ while (the_content === null) { yield null }
+ scale = scale_to_micron_factor(scale)
+ let gcode_lines = the_content.split("\n")
+ for(let i = 0; i < gcode_lines.length; i++){
+ let gobj = Job.gcode_line_to_obj(gcode_lines[i])
+ if (gobj == null) { continue; }
+ else {
+ let result
+ switch(gobj.type){
+ case "G0":
+ result = Job.gobj_to_move_to(gobj, scale)
+ yield result
+ break;
+ case "G1":
+ result = Job.gobj_to_move_to(gobj, scale)
+ yield result
+ break;
+ case "G28": //home
+ result = Job.gobj_to_move_to({X: 100, Y:100, Z:0}, scale) //needed to initialize out of the way
+ yield result
+ case "VAR":
+ break; //ignore. do next iteration
+ default:
+ break; //ignore. do next iteration
+ }
+ }
+ }
+}
+//rekturns lit obj or null if gstring is a comment or blank line
+Job.gcode_line_to_obj = function(gstring){
+ gstring = Job.gline_remove_comment(gstring)
+ if (gstring == "") { return null }
+ else if (gstring.startsWith(";")){ //semicolon on non first line starts end of line comment.
+ return Job.gcode_varline_to_obj(gstring)
+ }
+ else {
+ var litobj = {}
+ var garray = gstring.split(" ")
+ litobj.type = garray[0]
+ for(let arg of garray){
+ arg = arg.trim()
+ let letter = arg[0] //typically M, G, X, Y, X, E, F
+ let num = arg.substring(1)
+ if (is_string_a_number(num)){
+ num = parseFloat(num)
+ }
+ litobj[letter] = num //allowed to be a string, just in case somethign wierd, but is
+ //usually a number
+ }
+ return litobj
+ }
+}
+//trims whitespace and comment. Careful: if line begins with semicolon, its not a comment
+Job.gline_remove_comment = function(gstring){
+ let comment_pos = gstring.lastIndexOf(";")
+ if (comment_pos == -1) { return gstring.trim() }
+ else if (comment_pos == 0) {
+ if (gstring.includes("=")) { return gstring.trim()} //not actually a comment, its a var
+ else { return "" } //a comment whose line starts with semicolon as in the top line of a file
+ }
+ else { return gstring.substring(0, comment_pos).trim() }
+}
+
+Job.gcode_varline_to_obj = function (gstring){
+ let litobj = {}
+ gstring = gstring.substring(1).trim() //cut off the semicolon
+ let var_val = gstring.split("=")
+ let var_name = var_val[0].trim()
+ litobj.type = "VAR"
+ litobj.name = var_name
+ let val = var_val[1].trim()
+ if (val.includes(",")){
+ let vals = val.split(",")
+ litobj.val = []
+ for(let subval of vals){
+ let processed_subval = Job.gcode_process_subval(subval) //probably won't be [12, "%"] but if it is, ok
+ litobj.val.push(processed_subval) //if our val is something like "0x0,2x3,4x5" then each subval will b [0, 0] etc and we'll have an array of arrays
+ }
+ }
+ else {
+ let processed_subval = Job.gcode_process_subval(val)
+ if (Array.isArray(processed_subval) &&
+ (processed_subval.length == 2) &&
+ (typeof(processed_subval[1]) != "number")){
+ litobj.val = processed_subval[0]
+ litobj.units = processed_subval[1]
+ }
+ else { litobj.val = processed_subval }
+ }
+ return litobj
+}
+
+//subval can be "123", "123.45", "123%" "#FFFFFF" "0x0", "123x45", "G28" "M104 S0", "12.3mm", "1548.5mm (3.7cm3)", ""
+//return a number, [123, "%"] "#FFFFFF", [0, 0] [123, 45], "G28" "M104 S0", [12.3, "mm"], "1548.5mm (3.7cm3)", ""
+Job.gcode_process_subval = function(subval){
+ subval = subval.trim()
+ let x_pos = subval.indexOf("x")
+ if (subval.includes(" ")) { return subval } //just a string
+ else if ((x_pos != -1) &&
+ (x_pos != 0) &&
+ (x_pos != (subval.length - 1))) { //we've probably got subval of format "12x34"
+ let subsubvals = subval.split("x")
+ let val = []
+ for(let subsubval of subsubvals){
+ if (is_string_a_number(subsubval)) { val.push(parseFloat(subsubval))}
+ else { return subval } //its just a string with an x in the middle of it.
+ }
+ return val
+ }
+ else if (is_string_a_number(subval)){
+ return parseFloat(subval)
+ }
+ else { //maybe have a number with units ie 12.3mm, but we don't have just a number, we might have just a string
+ for(let i = 0; i < subval.length; i++){
+ let char = subval[i]
+ if ("0123456789.-".includes(char)) {} //continue looping
+ else if (i == 0) { //first char not in a num so whole thing is a string
+ return subval
+ }
+ else if ((i == 1) && (subval[0] == "-")){ //example "-foo". Its not a num
+ return subval
+ }
+ else {
+ let num = parseFloat(subval.substring(0, i))
+ let units = subval.substring(i)
+ return [num, units]
+ }
+ }
+ //not expecting this to happen, but in case it does
+ return subval
+ }
+}
+
+//G0 or G1 code
+Job.gobj_to_move_to = function(gobj, scale){ //ok for say, gobj to not have Z. that will just return undefined, and
+ //move_to will get the existing Z value and use it.
+ let the_x = gobj.X
+ if (the_x){ the_x = the_x * scale }
+ let the_y = gobj.Y
+ if (the_y){ the_y = the_y * scale }
+ let the_z = gobj.Z
+ if (the_z){ the_z = the_z * scale }
+ let result = Dexter.move_to([the_x, the_y, the_z])
+ return result
+}
+//for go_to
+Job.job_of_instruction_location = function(instruction_location){ //instruction_location should be an array, as any instruction_location that isn't an array doesn't really make sense.
+ //if there's no job in instruction_location, returns null or undefined.
+ var il_item = instruction_location
+ if (Array.isArray(instruction_location)){ il_item = instruction_location[0] }
+ const the_job = il_item.job
+ if (the_job){
+ if (typeof(the_job) == "string"){
+ the_job = Job[the_job]
+ dde_error("Attempt to find instruction_location: " + instruction_location +
+ " but the specified job: " + instruction_location[0].job +
+ " isn't a defined job.")
+ }
+ }
+ return the_job //beware might be null or undefined.
+}
+
+Job.instruction_location_to_job = function (instruction_location, maybe_error=true){
+ var the_job_elt = instruction_location
+ if (Array.isArray(instruction_location)){
+ if (instruction_location.length === 0){
+ if (maybe_error) {
+ dde_error("Job.instruction_location passed empty array. " +
+ " It must have at least 1 item in it,,br/>" +
+ 'with the first of format: {job:"some_job"}')
+ }
+ else {return null}
+ }
+ else { the_job_elt = instruction_location[0] }
+ }
+ if (the_job_elt){
+ if (the_job_elt.job) {
+ var the_job = the_job_elt.job
+ if (typeof(the_job) == "string"){
+ the_job = Job[the_job]
+ if (!the_job) {
+ if (maybe_error) {
+ dde_error("Attempt to find instruction_location: " + instruction_location +
+ " but the specified job: " + instruction_location[0].job +
+ " isn't a defined job.")
+ }
+ else { return null }
+ }
+ }
+ return the_job
+ }
+ else {
+ if (maybe_error) {
+ dde_error("Job.instruction_location passed " + instruction_location +
+ ' which does not have an element of format: {job:"some_job"}')
+ }
+ else { return null }
+ }
+ }
+ else {
+ if (maybe_error) {
+ dde_error("Job.instruction_location passed a location: " + instruction_location +
+ " that doesn't have a job in it.")
+ }
+ else { return null }
+ }
+}
+//intruction_location can be 5, {offset: 5}, [{offset: 5}}, {job: "myjob", offset:5}
+// [{job:myjob}, {offset:5}], then throw in process attribute.
+//getting a job makes it hold for the rest of the il, any there should be at most
+//one job and it should be in the first element.
+//offset and process DON'T carry forward to become defaults for later array elts.
+//if the first offset is negative, it is added to the job's do_list length to
+//get the resulting instruction id.
+Job.prototype.instruction_location_to_id = function(instruction_location, starting_id=null, orig_instruction_location=null){
+ var job_instance = this
+ if (orig_instruction_location == null) { orig_instruction_location = instruction_location} //used for error messages
+ let inst_loc = instruction_location
+ let process = "forward_then_backward" //process ignored for integer inst_loc's.
+ if ((typeof(inst_loc) == "object") && !Array.isArray(inst_loc)){
+ if (instruction_location.job) {
+ job_instance = instruction_location.job
+ if (typeof(job_instance) == "string") { job_instance = Job[job_instance] }
+ if (!(job_instance instanceof Job)) {
+ dde_error("instruction_location_to_id passed: " + orig_instruction_location +
+ " passed an invalid job of: " + job_instance)
+ }
+ }
+ //an object might have just a job, just an offset, or both
+ if(instruction_location.offset) {
+ inst_loc = instruction_location.offset
+ if (instruction_location.process) {
+ process = instruction_location.process
+ }
+ }
+ else {
+ dde_error("In instruction_location_to_id, got an object: " + instruction_location +
+ " that did not have an offset field, " +
+ "in the original_instruction_location: " + orig_instruction_location)
+ }
+ }
+ if (typeof(inst_loc) == "number"){
+ if (starting_id == null){
+ if (inst_loc >= 0) { starting_id = 0 }
+ else { starting_id = job_instance.do_list.length } // an initial negative inst_loc means count from the end, with -1 pointin at the last instruction
+ }
+ let result = starting_id + inst_loc
+ if ((result < 0) || (result > job_instance.do_list.length)){
+ dde_error("instruction_location_to_id passed: " + instruction_location +
+ " but that finds an instruction outside the range of " +
+ " valid ids: 0 through " + (job_instance.do_list.length) +
+ " in the original_instruction_location: " + orig_instruction_location)
+
+ }
+ else { return result }
+ }
+ else if (typeof(inst_loc) == "string"){
+ if (inst_loc == "program_counter") { return job_instance.program_counter }
+ else if (inst_loc == "before_program_counter") { return job_instance.program_counter - 1 }
+ else if (inst_loc == "after_program_counter") { return job_instance.program_counter + 1 }
+ else if (inst_loc == "end") { return job_instance.do_list.length } //bad for go_to but ok for insert instruction, ie a new last instruction
+ else if (inst_loc == "next_top_level") { return "next_top_level" } //used only by insert_instruction_at_location
+ else { // a label or a sync_point name search pc, then after, then before pc
+ if (starting_id == null) { starting_id = this.program_counter }
+ if (process == "forward_then_backward") { return job_instance.ilti_forward_then_backward(inst_loc, starting_id, orig_instruction_location) }
+ else if (process == "backward_then_forward") { return job_instance.ilti_backward_then_forward(inst_loc, starting_id, orig_instruction_location) }
+ else if (process == "forward") { return job_instance.ilti_forward( inst_loc, starting_id, orig_instruction_location) }
+ else if (process == "backward") { return job_instance.ilti_backward(inst_loc, starting_id, orig_instruction_location) }
+ else {
+ dde_error("instruction_location_to_id passed process: " + process +
+ " but the only valid processes are: " +
+ '"forward_then_backward", "backward_the_forward", "forward", "backward".' +
+ " in the original_instruction_location: " + orig_instruction_location)
+ }
+ }
+ }
+ else if (Array.isArray(inst_loc)){
+ let result = starting_id //will be null on first call
+ for(let item of inst_loc){
+ if (item.job){
+ if(result == null){ //we're on the first elt of the array. so ok for it to have a job
+ job_instance = item.job
+ if (typeof(job_instance) == "string") {
+ job_instance = Job[job_instance]
+ if (!job_instance) { dde_error("In instruction_location_to_id got undefined job name: " + job_inst)}
+ }
+ }
+ else {
+ dde_error("In instruction_location_to_id got a non-first item " +
+ " that has job in it, which is invalid. That invalid job is: " + item.job +
+ " in the original_instruction_location: " + orig_instruction_location)
+ }
+ }
+ result = job_instance.instruction_location_to_id(item, result, orig_instruction_location)
+ }
+ return result
+ }
+ else {dde_error("Job." + this.name + " doesn't contain a location named: " + inst_loc +
+ "in the original_instruction_location: " + orig_instruction_location)}
+}
+
+Job.prototype.ilti_forward_then_backward = function(inst_loc, starting_id, orig_instruction_location){
+ for(let id = starting_id; id < this.do_list.length; id++){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //gets label, sync_point and fn name
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ for(let id = starting_id - 1; id >= 0; id--){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //finds both label and sync_point instructions with "name" of inst_loc
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ dde_error("Job." + this.name + " doesn't contain a location named: " + inst_loc +
+ " in the original_instruction_location: " + orig_instruction_location)
+}
+
+Job.prototype.ilti_backward_then_forward = function(inst_loc, starting_id){
+ for(let id = starting_id - 1; id >= 0; id--){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //finds both label and sync_point instructions with "name" of inst_loc
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ for(let id = starting_id; id < this.do_list.length; id++){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //gets label, sync_point and fn name
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ dde_error("Job." + this.name + " doesn't contain a location named: " + inst_loc +
+ " in the original_instruction_location: " + orig_instruction_location)
+}
+
+Job.prototype.ilti_forward = function(inst_loc, starting_id){
+ for(let id = starting_id; id < this.do_list.length; id++){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //gets label, sync_point and fn name
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ dde_error("Job." + this.name + " doesn't contain a location named: " + inst_loc +
+ " in the original_instruction_location: " + orig_instruction_location)
+}
+
+Job.prototype.ilti_backward = function(inst_loc, starting_id){
+ for(let id = starting_id - 1; id >= 0; id--){
+ let ins = this.do_list[id]
+ if (ins.name === inst_loc) {return id} //finds both label and sync_point instructions with "name" of inst_loc
+ else if (ins instanceof Instruction){
+ if (ins.constructor.name === inst_loc) { return id }
+ }
+ else if (Instruction.is_instruction_array(ins)){
+ if (ins[Instruction.INSTRUCTION_TYPE] === inst_loc) { return id }
+ }
+ }
+ dde_error("Job." + this.name + " doesn't contain a location named: " + inst_loc +
+ " in the original_instruction_location: " + orig_instruction_location)
+}
+
+Job.insert_instruction_at_location = function(instruction, location){
+ const the_job = Job.job_of_instruction_location(location)
+ if (the_job){
+ const index = the_job.instruction_location_to_id(location)
+ if (index === "next_top_level"){
+ the_job.sent_from_job_instruction_queue.push(instruction)
+ }
+ else { the_job.do_list.splice(index, 0, instruction) }
+ }
+ else {
+ dde_error("insert_instruction_at_location passed location: " + insert_instruction_at_location +
+ " which doesn't specify a job. Location should be an array with" +
+ "a first element of a literal object of {job:'some-job'}")
+ }
+}
+
+//todo allow an instruction location elt to be a lit obj that has
+ // job, offset, AND process all in one. But also aloow it
+ //to just oave "job".
+
+
+
+
diff --git a/job_examples.js b/job_examples.js
new file mode 100644
index 00000000..513af3f1
--- /dev/null
+++ b/job_examples.js
@@ -0,0 +1,557 @@
+/* Created by Fry on 3/11/16.*/
+var job_examples = [null, //don't have example 0
+`//////// Job Example 1
+//A Job is esssentially a named list of instructions to
+//be executed by a robot. There are several different
+//formats for instructions. The most general is a
+//function defintion. Below you can define a simple job
+//with a name and 2 instructions by
+//holding down the 'alt' key and clicking on 'new'.
+//This will select the Job definition.
+//With that selected, click the Eval button.
+new Job({name: "my_job",
+ do_list: [Robot.out("first instruction"), //will cause 'first instruction' to be printed in output pane when run
+ function(){out("2nd instruction")}]}) //This function will be called
+
+//Now click the Output pane's Clear button.
+//Hold down the 'alt' key and click on 'my_job'
+//to select this call to 'start'.
+//Click the Eval button.
+Job.my_job.start() //Start running 'my_job'
+//Scroll to the top of the Output pane.
+//You will see 'Starting job", followed by
+//the results of calling the two function instructions
+//followed by details of the job's ending state,
+//including status_code: "completed" if all goes well.
+`,
+
+`///////// Job Example 2
+//An instruction can also be a function call that
+//returns a low level array for Dexter to execute.
+///Dexter.sleep and Dexter.move_all_joints_relative
+//are two such calls. Select and eval them to see their result.
+//Just as in a normal JavaScript program, we can
+//wrap a call in another function and call that other function
+//as we do below by wrapping Dexter.move_all_joints in "move_once".
+function move_once(){
+ return Dexter.move_all_joints([1, 2, 3, 4, 5]) //also try: Dexter.move_to([100000, 200000, 300000])
+}
+function sleep_and_move(){
+ return [Dexter.move_all_joints([10000, 20000, 30000, 40000, 50000]), //also try: Dexter.move_to_relative([1000, 3000, 4500])
+ Dexter.sleep(500),
+ Dexter.move_to([100000, 200000, 250000], [0, 0, -1], Dexter.RIGHT_UP_IN)
+ ]
+}
+new Dexter({name: "my_dex",
+ simulate: true //simulate is true by default
+ })
+new Job({name: "j1",
+ robot: Robot.my_dex, //assigns a robot to this job
+ do_list: [move_once, sleep_and_move]} //use the above function definitions as do_list items
+)
+Job.j1.start()
+/* Job.j1 //the newly created Job instance
+ Job.j1.status_code
+ Job.j1.robot.joint_angles() //array of 5 angles, each in arcseconds
+ Job.j1.robot.joint_angle(2) //1 thru 5
+ Job.j1.robot.joint_xyz(5) //0 thru 5, default 5. 0 is robot base position
+ Job.j1.robot.joint_xyzs() //Array of base xyz and all joint xyzs.
+*/
+`,
+
+
+`//////// Job Example 3: Generators See https://davidwalsh.name/es6-generators
+//A generator is a function that can effectively return a value
+//in the middle of its definition via 'yield', then be called again
+//and resume after the previous 'yield'.
+//A generator can be used as a do-list instruction.
+//Running a job automatically handles the re-calling
+//of a generator until its exhausted.
+
+//_______Job Example 3a: Simple Generator
+function* gen_moves(){
+ yield (Dexter.move_all_joints([1, 200000, 3, 40, 50]))
+ yield (Dexter.sleep(1000))
+ yield* [Dexter.move_all_joints([1, 300001]),
+ Dexter.sleep(999)
+ ]
+}
+new Job({name: "j1", robot: new Dexter(), do_list: [gen_moves]})
+Job.j1.start()
+
+//_______Job Example 3b: Generator with for loop
+function* complex_gen(){
+ for(var i = 0; i < 4; i++){
+ yield Dexter.move_all_joints(i * 100000)
+ }
+}
+new Job({name: "j2", robot: new Dexter(), do_list: [complex_gen]})
+Job.j2.start()
+
+//________Job Example 3c: Nested Generators
+function* nested_gen(){
+ var complex_iterator = complex_gen()
+ for(var instru of complex_iterator){
+ yield instru
+ }
+ yield Dexter.sleep(1000)
+}
+new Job({name: "j3", robot: new Dexter(), do_list: [nested_gen]})
+Job.j3.start()
+`,
+
+
+`////////Job Example 4a: synchronizing Jobs
+//The sync_point control instruction causes a job
+//to wait until all the other jobs with the same
+//sync_point name (i.e. "midway") reach that sync point.
+new Job({name: "job_a",
+ do_list: [Robot.out("hello"),
+ Robot.sync_point("midway", ["job_a", "job_b"]),
+ Robot.out("goodbye")]})
+
+new Job({name: "job_b",
+ do_list: [Robot.out("hello"),
+ Robot.wait_until(10000),
+ Robot.sync_point("midway", ["job_a", "job_b"]),
+ Robot.out("goodbye")]})
+Job.job_a.start(); Job.job_b.start() //execute both at once.
+//job_a will wait at its "midway" point until job_b gets to
+//its "midway" point, then they both proceed.
+
+
+/////////Job Example 4b: One job controlling another
+//Control instructions increase the flexibility of Jobs.
+//They can add instructions to other jobs (send_to_job)
+// as well as pause (suspend) and resume (unsuspend) jobs.
+
+new Dexter({name: "my_dex", ip_address: "192.168.1.142", port: 5000})
+new Job({name: "j4", robot: Robot.my_dex,
+ do_list: [Dexter.move_all_joints(100000, 200000),
+ Robot.suspend(), //j5 will unsuspend this
+ Robot.out("j4 sez goodbye.")]})
+Job.j4.start()
+
+new Dexter({name: "my_dex2", ip_address: "192.168.1.143", port: 5000})
+new Job({name: "j5", robot: Robot.my_dex2,
+ do_list: [Robot.send_to_job(
+ {do_list_item: Dexter.move_to([100000, 100000, 100000]),
+ where_to_insert: {job: "j4", offset: "after_program_counter"},
+ unsuspend: true,
+ wait_until_done: true}),
+ Robot.out("j5 sez goodbye.")]})
+Job.j5.start()
+
+////////Job Example 4c: Instructing another job and getting its data
+//In DDE, its easy for a job to get the state of another job.
+//Job.other_job_name.program_counter or Job.other_job_name.user_data
+//or any other part of the job. But if you want to send an instruction
+//to another job, then get the effect of that instruction has had,
+// use sent_to_job with a status_variable_name, etc as below
+//and you can bring that remote data into the user_data of the requesting job.
+//First we create the job that is being controlled by, and supplying
+//data to another job:
+new Job({name: "j6", robot: new Dexter(), do_list: []})
+//we'll let j7 start j6
+
+//Now for our requesting job:
+new Job({name: "j7",
+ do_list: [Robot.send_to_job({
+ do_list_item: Dexter.move_all_joints(200000, 100000),
+ where_to_insert: {job: "j6", offset: "after_program_counter"},
+ start: true, //starts j6
+ wait_until_done: true,
+ status_variable_name: "that_j6_task",
+ //and any number of values you want to get from j6
+ j6_joint_5_pos: function(){return this.robot.joint_xyz(5)},
+ j6_angle_number_2: function(){return this.robot.joint_angle(2)}
+ })]})
+Job.j7.start()
+/* Job.j7.user_data contains info snatched from job j6
+If you use Robot.send_to_job({where_to_insert: {job: "to_job", offset: "end"},
+ wait_until_done: true, ...}
+then the job with the sent_to_job instruction will wait until
+the whole of the to_job is done before proceeding
+*/
+
+////// Job Example 4d: Extending the do_list when calling start.
+//sent_from_job is not commonly used by users directly,
+//but is used internally by send_to_jobs that are not yet started.
+new Job ({name: "j8",
+ do_list: [Robot.out("first instruction"), //will cause 'first instruction' to be printed in output pane when run
+ Robot.sync_point("sp1"),
+ Robot.out("2nd instruction")]})
+
+Job.j8.start(Robot.sent_from_job({do_list_item:
+ Robot.out("special insert"),
+ where_to_insert: "sp1"})) //insert "special interest" between "first instruction" nad "2nd instruction"
+
+`,
+
+
+`//////// Job Example 5 Calling show_window from an instruction
+function handle_print_job_1_dialog_input(vals){
+ if(vals.clicked_button_value == "Continue"){
+ Job.print_job_1.user_data.color = vals.input_3
+ Job.print_job_1.user_data.color_status = "ok"
+ }
+ else if(vals.clicked_button_value == "Cancel"){
+ Job.print_job_1.user_data.color_status = "cancel"
+ }
+}
+
+function print_job_1_dialog(){
+ show_window({content:` + "`" + `
+
+ There's no more white filament left.
+
+ Please choose another color or cancel the job.
+
+
+ black
+ blue
+
+
+
+
+ ` + "`" + `,
+ title: "Warning!",
+ background_color: "#eeeeee",
+ height: 150,
+ callback: handle_print_job_1_dialog_input
+ }
+ )
+}
+
+new Job({name: "print_job_1", robot: new Dexter(),
+ do_list:
+ [Dexter.move_all_joints([1, 2, 3, 4, 5]),
+ function(){print_job_1_dialog()},
+ Robot.wait_until(function(){return this.user_data.color_status != undefined}),
+ function(){if (this.user_data.color_status == "cancel"){
+ return Robot.error("ran out of filament.")
+ }
+ else {return null}
+ },
+ Dexter.move_all_joints([10, 20, 30, 40, 50])
+ ]})
+Job.print_job_1.start()
+// Job.print_job_1.user_data //data set by the dialog
+`,
+
+
+`//////// Job Example 6a: Using a human 'robot' cooperating with a Brain robot
+//Jobs may contain instructions for human operators as well as robots,
+//facilitating well-coordinated human-machine processes.
+new Job({name: "lots_of_options_task",
+ robot: new Dexter(),
+ do_list: [Human.task({task: "Load more filament.",
+ title: "Pay Attention!!!",
+ x: 0,
+ y: 0,
+ width: 600,
+ height: 150,
+ background_color: "rgb(230, 200, 250)"
+ }), //waits until user clicks 'Done'.
+ Dexter.move_to([0, 100000, 450000])
+ ]})
+Job.lots_of_options_task.start()
+
+//////// Job Example 6b: Dependent Jobs
+new Job({name: "dependent_job", //robot type defaults to Brain
+ do_list: [Robot.sync_point("load_filament", ["my_job"]),
+ Robot.out("dependent_job last instruction")]})
+
+new Job({name: "my_job", robot: new Human({name: "Joe Jones"}),
+ do_list: [Human.task({task: "Load more filament.",
+ height: 150,
+ dependent_job_names: ["dependent_job"]}), //this optional arg
+ //lists jobs to be stopped if user clicks
+ //"Stop this & dependent jobs" button.
+ Robot.sync_point("load_filament"),
+ Robot.out("my_job last instruction")]})
+
+Job.dependent_job.start(); Job.my_job.start() //start both at once
+
+
+//////// Job Example 6c: human chooses material from list
+new Job({name: "material_job", robot: new Human({name: "Joe Jones"}),
+ do_list: [Human.enter_choice({
+ task: "Which material should we use?",
+ user_data_variable_name: "material_choice", // user_data variable to store choice
+ choices: ["copper", "silver", "gold"],
+ show_choices_as_buttons: false, // the default, which shows choices as menu items
+ one_button_per_line: false, // the default. relevant when showing buttons only
+ dependent_job_names: []}), // [] means no dependent jobs.
+ Robot.out("material_job last instruction")
+ ]})
+Job.material_job.start()
+// Job.material_job.user_data
+
+//////// Job Example 6d: human enters a number
+new Job({name: "number_job",
+ robot: new Human({name: "Joe Jones"}),
+ do_list: [Human.enter_number({
+ task: "How many millimeters long should we make the pipe?",
+ user_data_variable_name: "pipe_length", // user_data variable to store the number
+ initial_value: 15,
+ min: 10,
+ max: 1000,
+ step: 1,
+ dependent_job_names: []}), // [] means no dependent jobs.
+ Robot.out("number_job last instruction")]})
+Job.number_job.start()
+// Job.number_job.user_data
+
+//////// Job Example 6e: human enters text
+new Job({name: "text_job",
+ robot: new Human({name: "Joe Jones"}),
+ do_list: [Human.enter_text({
+ task: "Describe how this job is going.",
+ user_data_variable_name: "job_description", // user_data variable to store the text
+ initial_value: "OK",
+ line_count: 3,
+ dependent_job_names: []}), // [] means no dependent jobs.
+ Robot.out("text_job last instruction")]})
+Job.text_job.start()
+// Job.text_job.user_data
+
+//////// Job Example 6f: Notify
+//Tell human something without pausing execution.
+new Job({name: "notify_job",
+ robot: new Human({name: "Joe Jones"}),
+ do_list: [Human.notify({
+ task: "Take off work early today!",
+ window: true, //the default
+ output_pane: true, //the default
+ beep_count: 0, //the default
+ speak: false //the default
+ }),
+ Robot.out("text_job last instruction")]})
+Job.notify_job.start()
+`,
+
+
+`//////// Job Example 7: Human Enter Instruction
+//This job pauses and presents a dialog box allowing
+//the entry of an instruction, to continue the job, or to cancel it.
+//An instruction can be entered via text or we can GENERATE
+//instructions by moving a Dexter robot where we want it to
+//go as in 'training'.
+new Dexter({name: "my_dex", ip_address: "192.168.1.142", port: 50000})
+
+new Job({name: "my_job",
+ robot: Robot.my_dex,
+ do_list: [function(){out("first instruction")}, //will cause 'first instruction' to be printed in output pane when run
+ Human.enter_instruction(), // Pops up a dialog requesting user input of an instruction.
+ Robot.out("last instruction")]})
+
+Job.my_job.start()
+`,
+
+
+`/* Job Example 8 Async Instructions
+Using "dont_call_set_up_next_do"
+ Normally when a function in JS is called, it
+ executes the code in its body and returns
+ (possibly with a value computed by the body).
+ These are called "Synchronous Functions".
+ But some functions, particularly ones that take a long time
+ to run (ie hundreds of milliseconds or more) or are
+ performed on other computers such as a Dexter, are
+ designed to return immediately when called, but then
+ the real work of the function goes on behind the scenes.
+ These are called "Asynchronous Functions".
+ Often such functions take an argument
+ that is a "callback function" that is called when
+ the real work of the function ends.
+
+ If you want to call such a function,
+ and wait until its done, before calling another function,
+ you can't simply place calls to the functions
+ one after the other as in normal code, because
+ the 2nd one will start executing right after the
+ immediate return of the first,
+ not when the "real work" of the 1st is done.
+
+ An example of such a function is "beep"
+ (supplied in DDE, but not normal JS).
+ First try a call to beep:
+ */
+beep({frequency: 440})
+/*ok now select two calls to beep at once before hitting "Eval".*/
+beep({frequency: 440, duration: 1000})
+beep({frequency: 500, duration: 2000})
+/*notice that the first call returns immediately and the
+ 2nd call is executing while the first beep is still beeping
+ thus playing a 2 note chord.
+ (We've extending the duration of the 2nd note to have it
+ continue beyond the first to make the chord more obvious.
+
+ OK playing chords is nice but what if you want to play a melody,
+ ie one note AFTER the first has completed?
+ One approach is to use the "callback when done" for the first.
+ */
+beep({frequency: 330, callback: beep})
+//and if we want to call that 2nd beep with other than its default args.
+beep({frequency: 330, callback: function(){beep({frequency: 220})}})
+/*this nesting trick can be played again by using the callback
+ arg of the 2nd beep to place a 3rd beep, etc.
+ But notice the code starts to get hard to read as the nesting
+ level goes up.
+
+ However, this problem is what the Job's do_list is
+ designed to solve. We define a function that calls
+ a method that returns immediatly but has a callback
+ to call when done. Our callback calls set_up_next_do,
+ which causes the do_list program counter to increment
+ and then execute the next instruction on the do_list.
+ But to avoid the job code itself calling set_up_next_do as it
+ usually does, we have to turn off that call by returning
+ "dont_call_set_up_next_do" to avoid calling it twice
+ for the same instrution.*/
+function my_waiting_beeper(){
+ var job_instance = this
+ beep({duration: 1000, callback: function(){job_instance.set_up_next_do()}})
+ return "dont_call_set_up_next_do"
+}
+/* Now our Job definition can just list 2 references to the
+ my_waiting_beeper function as regular do_list items,
+ without the hair of the sequencing
+ callback code buried in my_waiting_beeper */
+new Job({name: "my_job",
+ do_list: [my_waiting_beeper, my_waiting_beeper]})
+Job.my_job.start()
+/* In our do_list we can have as many calls to my_waiting_beeper
+ as we like, and they don't have to be contigous.
+
+ We can also play sequential chords*/
+
+function my_waiting_chording_beeper(){
+ var job_instance = this
+ beep({duration: 1000, frequency: 600})
+ beep({duration: 1000, callback: function(){job_instance.set_up_next_do()}})
+ return "dont_call_set_up_next_do"
+}
+
+new Job({name: "my_job",
+ do_list: [my_waiting_chording_beeper,
+ my_waiting_chording_beeper,
+ my_waiting_beeper,
+ my_waiting_chording_beeper
+ ]})
+Job.my_job.start()
+/* You can use this pattern to sequence any functions that return immediately
+ but have a callback-when-done argument.
+
+ One last fun audio trick: play a chord with the two notes being very close
+ in frequency to each other for the 'beating' effect. */
+
+beep({frequency: 440, duration: 5000})
+beep({frequency: 440.5, duration: 5000})
+`,
+`/* Job Example 9 Serial Port
+ Connections between different devices are often problematic,
+ because this is much more complex than most programmers expect.
+ Your most useful trait is persistence!
+
+ This walks you though controlling an Arduino board from DDE.
+ If you haven't used Arduino before,
+ 1. Download the Arduino IDE from https://www.arduino.cc, SOFTWARE tab,
+ 2. Launch it,
+ 3. Choose Help menu/Getting Started, and do what it says including:
+ 4. Connect your Arduino board to your computer via a USB cable.
+ The green power light on the board should go on.
+ Now get info on the connected hardware (low level, doesn't need Jobs/Robots)
+*/
+serial_devices() //show all serial devices available
+//Use one of the returned "comName" paths like so:
+var ard_path = last(serial_devices()).comName // something like:
+ //"/dev/tty.usbmodem1411"
+
+//Now we are going to install a program into your Arduino.
+//In the Arduino App, choose File menu/new and paste in:
+/*
+#define LED 13
+void setup() {
+ Serial.begin(9600);
+ pinMode(LED, OUTPUT);
+ digitalWrite(LED, LOW); // Turn LED off
+}
+//from http://www.fabiobiondi.com/blog/2014/02/html5-chrome-packaged-apps-and-arduino-bidirectional-communication-via-serial/
+int incomingByte = 0;
+void loop() {
+ // Check if there's a serial message waiting.
+ if (Serial.available() > 0) { //read the incoming byte.
+ incomingByte = Serial.read();
+
+ if (incomingByte == 'y') {
+ digitalWrite(LED, HIGH); //turn on LED
+ Serial.println("LED on"); //return this string to DDE
+ }
+ else if (incomingByte == 'n') { //trun off LED
+ digitalWrite(LED, LOW);
+ Serial.println("LED off");
+ }
+ }
+ delay(1000);
+}
+*/
+//Save this as an Arduino Sketch in led_y_or_n.ino
+//In the Arduino IDE, click the upload button, annoying labeled as a right arrow.
+//This should cause the orange light on the Arduino to falsh briefly signifying
+//that its getting some data.
+//If the uplaod fails, you'll see red text in the Arduino IDE output pane.
+//Try unplugging and replugging your USB cable and uploading again.
+//After success, connect to the device
+serial_connect_low_level(ard_path) //returns lots of info including the path
+
+serial_path_to_info_map //Shows us what the current connections are.
+ //this should contain one with our "ard_path".
+
+serial_send_low_level(ard_path, "y") //turns on orange light on board.
+// in the DDE output pane you should see
+// "serial write just sent: y" as the "y" char is sent from DDE and
+// "onReceiveCallback_low_level got data str: LED on"
+// with data back from the Arduino.
+serial_send_low_level(ard_path, "n") //turns off orange light on board.
+serial_flush(ard_path) //just makes sure all pending data moved. Not usually needed.
+
+serial_disconnect(ard_path) //returns null
+serial_path_to_info_map //now this will return {}
+
+//Now we're ready to use DDE's Job software to control our Arduino.
+//First, you may want to programmatically upload a file into Arduino from DDE.
+//When the Arduino IDE uploads a file to Arduino, it first compiles the
+//file in to a .hex file. It is this .hex file that is actually uploaded.
+//The clever authors of the Arduino IDE made finding this file challenging.
+//https://forum.arduino.cc/index.php?topic=131655.0 tells you how to do it
+//for Windows, but not the Mac.
+//Move that file to under your dde_apps folder and use:
+serial_send_low_level(file_content("some_arduino_file.ino.hex"), ard_path)
+//please let us know if this works, esp. if you're on a Mac.
+
+//_________serial job_______
+new Serial({name: "S1", simulate: false,
+ sim_fun: function(input){
+ return "got: " + input + "\n"
+ },
+ path: ard_path,
+ connect_options: {baudRate: 300},
+ capture_n_items: 1, parse_items: true})
+
+new Job({name: "j10",
+ robot: Robot.S1,
+ do_list: [Serial.string_instruction("y"),
+ Robot.grab_robot_status("yes_result"),
+ Robot.wait_until(new Duration(2000)),
+ Serial.string_instruction("n"),
+ Robot.grab_robot_status("no_result", Serial.DATA0)
+ ]}
+)
+Job.j10.start()
+
+Job.j10.user_data //all the user data
+Job.j10.user_data.yes_result //just our yes_result
+`
+]
\ No newline at end of file
diff --git a/jquery-1.11.3.min.js b/jquery-1.11.3.min.js
new file mode 100644
index 00000000..0f60b7bd
--- /dev/null
+++ b/jquery-1.11.3.min.js
@@ -0,0 +1,5 @@
+/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
+
+return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
";B+=o;ar+=E;if(!this.rowinfo[G.uid]){this.rowinfo[G.uid]={group:Y,row:G,details:null,detailsHeight:200,initialized:false,expanded:false}}else{if(!("group" in this.rowinfo[G.uid])){this.rowinfo[G.uid].group=Y}if(!("row" in this.rowinfo[G.uid])){this.rowinfo[G.uid].row=G}if(!("details" in this.rowinfo[G.uid])){this.rowinfo[G.uid].details=null}if(!("detailsHeight" in this.rowinfo[G.uid])){this.rowinfo[G.uid].detailsHeight=200}if(!("initialized" in this.rowinfo[G.uid])){this.rowinfo[G.uid].initialized=false}if(!("expanded" in this.rowinfo[G.uid])){this.rowinfo[G.uid].expanded=false}}if(this.serverProcessing){this.rowinfo[G.uid].row=G}if(this.rowDetails){var F=this.rowinfo[G.uid].detailsHeight;if(this.rowinfo[G.uid]){if(this.rowinfo[G.uid].expanded){var ah='