From 274d85bf05d82d13fad6bf4a706a6a3c43cfc564 Mon Sep 17 00:00:00 2001 From: Jamie Peabody Date: Sun, 24 Feb 2013 21:57:25 +0000 Subject: [PATCH] Made use of CodeMirror viewport to greatly improve performance. Added settings to toggle paragraph LCD; line wrapping; white space; and side bars. Released with CodeMirror 3.1. --- doc/LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++ doc/index.html | 6 + editor/editor.css | 19 +- editor/editor.js | 70 ++++- lib/codemirror.css | 5 + lib/codemirror.js | 411 ++++++++++++++++++--------- lib/mergely.css | 11 +- lib/mergely.js | 321 +++++++++++++++------ lib/searchcursor.js | 56 ++-- 9 files changed, 1304 insertions(+), 269 deletions(-) create mode 100755 doc/LICENSE diff --git a/doc/LICENSE b/doc/LICENSE new file mode 100755 index 0000000..94a9ed0 --- /dev/null +++ b/doc/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/doc/index.html b/doc/index.html index ddb3a3d..36d98e3 100644 --- a/doc/index.html +++ b/doc/index.html @@ -95,6 +95,12 @@ $(document).ready(function () {
Starting width. Defaults to '400px'.
editor_height
Starting height. Defaults to '400px'.
+
ignorews
+
Ignore white-space. Defaults to false.
+
lcs
+
Enables/disables LCS computation for paragraphs (word-by-word changes). Disabling can give a performance gain for large documents. Defaults to true.
+
sidebar
+
Enables/disables sidebar markers. Disabling can give a performance gain for large documents. Defaults to true.
resize_timeout
The timeout, after a resize, before Mergely auto-resizes. Only used when autoresize enabled. Defaults to 500.
change_timeout
diff --git a/editor/editor.css b/editor/editor.css index 065f5b7..e4a24e8 100755 --- a/editor/editor.css +++ b/editor/editor.css @@ -5,9 +5,9 @@ body { margin: 0px; font-family: "trebuchet ms"; } #logo { background: transparent url(/images/mergely_sm.png) no-repeat; width: 113px; height:30px; display: inline-block; top: 5px; left: 5px; position: relative; float: left; margin-right: 77px; } #info h3, #info p { display: none; } #info button { visibility: hidden; font-size: 0.75em; } -#about, .button-editor, #settings { float: right !important; margin: 6px 5px 0 0; } -#settings { display: inline-block; height: 16px; } -#settings img { display: inline-block; height: 16px; } +#about, #editor, #settings { float: right !important; margin: 6px 5px 0 5px; } +#settings { } +#settings img { display: inline-block; height: 16px; vertical-align: middle; padding-bottom: 3px; } .toolbar { display: none; margin: 0px; background: #e2e8ec url(../../images/toolbar_bg.png); border-bottom: 1px solid #A7BCC8; line-height: 14px; } .title { display: none; font-weight: bold; } @@ -15,22 +15,17 @@ body { margin: 0px; font-family: "trebuchet ms"; } .toolbar input[type=text] { float: left; border: 1px solid #888; font-size: 12px; font-weight: bold; font-family: tahoma; letter-spacing: 1px; width: 150px; color: #444; margin-right: 2px; } .toolbar .buttonset { display: inline-block; padding-top:5px; } .toolbar .buttonset .ui-button { padding: 2px 14px 2px 7px; float: left; } -#share-menu { display: none; background-color:white;border: 3px solid #606060;left:340px;top:33px;position:absolute;width:280px;z-index:50; padding: 5px; height: 40px; } +#share-menu { display: none; background-color:white;border: 3px solid #606060;left:382px;top:34px;position:absolute;width:280px;z-index:50; padding: 5px; height: 40px; } #share-menu label {font-weight: bold; font-size: .80em; color: #37AFFF; width: 80px; display: inline; padding-right: 5px; } #share-menu input { width: 200px; border: 1px solid #606060;} #dialog-confirm { display:none; } .ui-dialog { font-size:0.75em; } .toolbar .ui-button { margin-right: 1px; } #download { font-size: 1.1em; } -.mbutton { - font: normal 0.8em Verdana,Arial,sans-serif; text-decoration: none; - background: url('mergely-theme/images/ui-bg_flat_100_808080_40x100.png') repeat-x scroll 50% 50% #808080; - border: 1px solid #575757; color: #fff; font-weight: normal; display: inline-block; margin-right: 0.1em; overflow: visible; padding: 5px 6px; position: relative; - text-align: center; cursor: pointer; border-radius: 3px; -} -.mbutton:hover { background: url('mergely-theme/images/ui-bg_highlight-soft_25_37afff_1x100.png') repeat-x scroll 50% 50% #808080; } +.mbutton { font-size: 12px; line-height: 24px; padding: 0 5px; border-width: 2px; border-radius: 4px; } +.mbutton:hover { text-decoration: underline; } #dialog-settings { visibility: hidden; } #dialog-settings label { width: 85px; display: inline-block; font-weight: bold; padding: 5px; } #dialog-settings input[type=text] { width: 70px; border: 1px solid #444; float:right; } #dialog-settings label.checkbox { width: auto; } -#dialog-settings fieldset { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; border: 1px solid #ccc; width: 175px; padding-right: 15px; } +#dialog-settings fieldset { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; border: 1px solid #ccc; width: 222px; padding-right: 15px; } diff --git a/editor/editor.js b/editor/editor.js index 665e4e3..d2d2692 100755 --- a/editor/editor.js +++ b/editor/editor.js @@ -7,6 +7,22 @@ String.prototype.random = function(length) { } return randomstring; } +function getParameters() { + var parameters = {}; + window.location.search.substr(1).split('&').forEach(function(pair) { + if (pair === '') return; + var parts = pair.split('='); + if (parts[1] == 'true') parameters[parts[0]] = true; + else if (parts[1] == 'false') parameters[parts[0]] = false; + else parameters[parts[0]] = parts[1] && decodeURIComponent(parts[1].replace(/\+/g, ' ')); + }); + return { + get: function(name, defaultValue) { + if (parameters.hasOwnProperty(name)) return parameters[name]; + return defaultValue; + } + }; +} $(document).ready(function () { $('.button-search').button({icons:{primary:'ui-icon-search'}, text:false}); @@ -17,8 +33,11 @@ $(document).ready(function () { $('.button-download').button({icons:{primary:'ui-icon-disk'}, text:false}); $('.button-upload').button({icons:{primary:'ui-icon-folder-open'}, text:false}); $('.button-share').button({icons:{primary:'ui-icon-triangle-1-s'}, text:true}); + $('button').button(); $('.button-download-diff').button({icons:{primary:'ui-icon-script'}, text:false}); - + $('#new').on('click', function() { + window.location = '/'; + }); $('#share').on({ mouseenter: function () { $('#share-menu').fadeIn(500); }, mouseleave: function () { @@ -67,10 +86,13 @@ $(document).ready(function () { if (files.length >= 2) load_file(sides[1], files[1]); } }); - + + var parameters = getParameters(); + $('#compare').mergely({ - readonly: key == '4qsmsDyb', - linewrapping: false, + ignorews: parameters.get('ws', false), + lcs: parameters.get('lcs', true), + sidebar: parameters.get('sb', true), height: function(h) { return h - 100; }, @@ -86,7 +108,9 @@ $(document).ready(function () { $('#title-rhs').css({'left':rhsx}); }, cmsettings: { - mode: 'text/plain' + mode: 'text/plain', + lineWrapping: parameters.get('wrap') || false, + readOnly: (key == '4qsmsDyb') || parameters.get('ro') } }); if (key.length == 8) { @@ -264,12 +288,22 @@ $(document).ready(function () { 'd-bg': {id: '#d-bg', defaultColor: '#edc0c0', getColor: function() { return sd.css('background-color'); }, setColor: function(color) { $('#'+this.id).val(color) }}, }; + var ignorews = $('#compare').mergely('options').ignorews; + var lineWrapping = $('#compare').mergely('cm', 'lhs').getOption('lineWrapping') || $('#compare').mergely('cm', 'rhs').getOption('lineWrapping'); + var readOnly = $('#compare').mergely('cm', 'lhs').getOption('readOnly') || $('#compare').mergely('cm', 'rhs').getOption('readOnly'); + var lcs = $('#compare').mergely('options').lcs; + var sidebar = $('#compare').mergely('options').sidebar; + $.each(conf, function(key, item){ $(item.id).val(item.getColor()); }); - $('#ignore-ws').prop('checked', $('#compare').mergely('options').ignorews); + $('#ignore-ws').prop('checked', ignorews); + $('#wraplines').prop('checked', lineWrapping); + $('#readonly').prop('checked', readOnly); + $('#lcs').prop('checked', lcs); + $('#sidebar').prop('checked', sidebar); $('#settings').click(function(){ dlg.dialog({ - height: 350, width: 450, modal: true, + width: 490, modal: true, buttons: { Apply: function() { var cborder = $('#c-border').val(); @@ -279,14 +313,19 @@ $(document).ready(function () { var dbg = $('#d-bg').val(); var cbg = $('#c-bg').val(); var ignorews = $('#ignore-ws').prop('checked'); + var wraplines = $('#wraplines').prop('checked'); + var readonly = $('#readonly').prop('checked'); + var lcs = $('#lcs').prop('checked'); + var sidebar = $('#sidebar').prop('checked'); var text = - '.mergely.a.rhs.start { border-top: 1px solid ' + aborder + ' }\n\ + '.mergely.a.rhs.start { border-top: 1px solid ' + aborder + '; }\n\ .mergely.a.lhs.start.end,\n\ - .mergely.a.rhs.end { border-bottom: 1px solid ' + aborder + ' }\n\ - .mergely.bg.a.rhs { background-color: ' + abg + ' }\n\ - .mergely.d.lhs { background-color: ' + dbg + ' }\n\ + .mergely.a.rhs.end { border-bottom: 1px solid ' + aborder + '; }\n\ + .mergely.a.rhs { background-color: ' + abg + '; }\n\ + .mergely.d.lhs { background-color: ' + dbg + '; }\n\ .mergely.d.lhs.end,\n\ .mergely.d.rhs.start.end { border-bottom: 1px solid ' + dborder + '; }\n\ + .mergely.d.rhs.start.end.first { border-bottom: 0; border-top: 1px solid ' + dborder + '; }\n\ .mergely.d.lhs.start { border-top: 1px solid ' + dborder + '; }\n\ .mergely.c.lhs,\n\ .mergely.c.rhs { background-color: ' + cbg + '; }\n\ @@ -295,10 +334,15 @@ $(document).ready(function () { .mergely.c.lhs.end,\n\ .mergely.c.rhs.end { border-bottom: 1px solid ' + cborder + '; }\n\ .mergely.ch.a.rhs { background-color: ' + abg + '; }\n\ - .mergely.ch.d.lhs { background-color: ' + dbg + '; text-decoration: line-through; color: #888; }\n' + .mergely.ch.d.lhs { background-color: ' + dbg + '; text-decoration: line-through; color: #888; }'; $('').appendTo('head'); - $('#compare').mergely('options', {ignorews: ignorews, fgcolor:{a:aborder,c:cborder,d:dborder}}); + $('#compare').mergely('options', {ignorews: ignorews, lcs: lcs, sidebar: sidebar, fgcolor:{a:aborder,c:cborder,d:dborder}}); + $('#compare').mergely('cm', 'lhs').setOption('lineWrapping', wraplines); + $('#compare').mergely('cm', 'rhs').setOption('lineWrapping', wraplines); + $('#compare').mergely('cm', 'lhs').setOption('readOnly', readonly); + $('#compare').mergely('cm', 'rhs').setOption('readOnly', readonly); + $('#compare').mergely('update'); }, Reset: function() { diff --git a/lib/codemirror.css b/lib/codemirror.css index 1ceb080..8de0b19 100644 --- a/lib/codemirror.css +++ b/lib/codemirror.css @@ -148,6 +148,7 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} .CodeMirror-gutters { position: absolute; left: 0; top: 0; height: 100%; + padding-bottom: 30px; z-index: 3; } .CodeMirror-gutter { @@ -199,6 +200,10 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} overflow: auto; } +.CodeMirror-widget { + display: inline-block; +} + .CodeMirror-wrap .CodeMirror-scroll { overflow-x: hidden; } diff --git a/lib/codemirror.js b/lib/codemirror.js index 5ee107b..87339d0 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -1,3 +1,5 @@ +// CodeMirror version 3.1 +// // CodeMirror is the only global var we claim window.CodeMirror = (function() { "use strict"; @@ -60,7 +62,6 @@ window.CodeMirror = (function() { draggingText: false, highlight: new Delayed()}; - this.nextOpId = 0; themeChanged(this); if (options.lineWrapping) this.display.wrapper.className += " CodeMirror-wrap"; @@ -387,7 +388,7 @@ window.CodeMirror = (function() { return String(options.lineNumberFormatter(i + options.firstLineNumber)); } function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + return getRect(display.scroller).left - getRect(display.sizer).left; } // DISPLAY DRAWING @@ -431,18 +432,6 @@ window.CodeMirror = (function() { var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; - // When merged lines are present, the line that needs to be - // redrawn might not be the one that was changed. - if (sawCollapsedSpans) - for (var i = 0; i < changes.length; ++i) { - var ch = changes[i], merged; - while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) { - var from = merged.find().from.line; - if (ch.diff) ch.diff -= ch.from - from; - ch.from = from; - } - } - // Used to determine which lines need their line numbers updated var positionsChangedFrom = Infinity; if (cm.options.lineNumbers) @@ -461,7 +450,22 @@ window.CodeMirror = (function() { // Create a range of theoretically intact lines, and punch holes // in that using the change info. - var intact = computeIntact([{from: display.showingFrom, to: display.showingTo}], changes); + var intact = [{from: Math.max(display.showingFrom, doc.first), + to: Math.min(display.showingTo, end)}]; + if (intact[0].from >= intact[0].to) intact = []; + else intact = computeIntact(intact, changes); + // When merged lines are present, we might have to reduce the + // intact ranges because changes in continued fragments of the + // intact lines do require the lines to be redrawn. + if (sawCollapsedSpans) + for (var i = 0; i < intact.length; ++i) { + var range = intact[i], merged; + while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { + var newTo = merged.find().from.line; + if (newTo > range.from) range.to = newTo; + else { intact.splice(i--, 1); break; } + } + } // Clip off the parts that won't be visible var intactLines = 0; @@ -499,7 +503,7 @@ window.CodeMirror = (function() { height = bot - prevBottom; prevBottom = bot; } else { - var box = node.getBoundingClientRect(); + var box = getRect(node); height = box.bottom - box.top; } var diff = node.lineObj.height - height; @@ -513,7 +517,7 @@ window.CodeMirror = (function() { } updateViewOffset(cm); - if (visibleLines(display, doc, viewPort).to >= to) + if (visibleLines(display, doc, viewPort).to > to) updateDisplayInner(cm, [], viewPort); return true; } @@ -732,7 +736,7 @@ window.CodeMirror = (function() { // Move the hidden textarea near the cursor to prevent scrolling artifacts var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)) + "px"; display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, @@ -928,7 +932,7 @@ window.CodeMirror = (function() { function paddingTop(display) {return display.lineSpace.offsetTop;} function paddingLeft(display) { - var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x")); + var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); return e.offsetLeft; } @@ -998,7 +1002,7 @@ window.CodeMirror = (function() { removeChildrenAndAdd(display.measure, pre); - var outer = display.lineDiv.getBoundingClientRect(); + var outer = getRect(display.lineDiv); var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; // Work around an IE7/8 bug where it will sometimes have randomly // replaced our pre with a clone at this point. @@ -1006,7 +1010,7 @@ window.CodeMirror = (function() { removeChildrenAndAdd(display.measure, pre); for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { - var size = cur.getBoundingClientRect(); + var size = getRect(cur); var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot); for (var j = 0; j < vranges.length; j += 2) { var rtop = vranges[j], rbot = vranges[j+1]; @@ -1020,7 +1024,9 @@ window.CodeMirror = (function() { } } if (j == vranges.length) vranges.push(top, bot); - data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j}; + var right = size.right; + if (cur.measureRight) right = getRect(cur.measureRight).left; + data[i] = {left: size.left - outer.left, right: right - outer.left, top: j}; } for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { var vr = cur.top; @@ -1029,7 +1035,7 @@ window.CodeMirror = (function() { if (!cm.options.lineWrapping) { var last = pre.lastChild; if (last.nodeType == 3) last = pre.appendChild(elt("span", "\u200b")); - data.width = last.getBoundingClientRect().right - outer.left; + data.width = getRect(last).right - outer.left; } return data; @@ -1053,7 +1059,7 @@ window.CodeMirror = (function() { var yOff = heightAtLine(cm, lineObj); if (context != "local") yOff -= cm.display.viewOffset; if (context == "page") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); + var lOff = getRect(cm.display.lineSpace); yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop); var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft); rect.left += xOff; rect.right += xOff; @@ -1083,10 +1089,9 @@ window.CodeMirror = (function() { if (part.from < ch && part.to > ch) return get(ch, rtl); var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to; if (left == ch) { - // Opera and IE return bogus offsets and widths for edges - // where the direction flips, but only for the side with the - // lower level. So we try to use the side with the higher - // level. + // IE returns bogus offsets and widths for edges where the + // direction flips, but only for the side with the lower + // level. So we try to use the side with the higher level. if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true); else here = get(rtl && part.from != part.to ? ch - 1 : ch); if (rtl == linedir) main = here; else other = here; @@ -1104,14 +1109,20 @@ window.CodeMirror = (function() { return main; } + function PosMaybeOutside(line, ch, outside) { + var pos = new Pos(line, ch); + if (outside) pos.outside = true; + return pos; + } + // Coords must be lineSpace-local function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; - if (y < 0) return {line: doc.first, ch: 0, outside: true}; + if (y < 0) return PosMaybeOutside(doc.first, 0, true); var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineNo > last) - return Pos(doc.size - 1, getLine(doc, last).text.length); + return PosMaybeOutside(doc.first + doc.size - 1, getLine(doc, last).text.length, true); if (x < 0) x = 0; for (;;) { @@ -1143,15 +1154,17 @@ window.CodeMirror = (function() { var bidi = getOrder(lineObj), dist = lineObj.text.length; var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), toX = getX(to); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - if (x > toX) return {line: lineNo, ch: to, outside: wrongLine}; + if (x > toX) return PosMaybeOutside(lineNo, to, toOutside); // Do a binary search between these bounds. for (;;) { if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { var after = x - fromX < toX - x, ch = after ? from : to; while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; - return {line: lineNo, ch: ch, after: after, outside: wrongLine}; + var pos = PosMaybeOutside(lineNo, ch, after ? fromOutside : toOutside); + pos.after = after; + return pos; } var step = Math.ceil(dist / 2), middle = from + step; if (bidi) { @@ -1159,8 +1172,8 @@ window.CodeMirror = (function() { for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); } var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;} - else {from = middle; fromX = middleX; dist = step;} + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist -= step;} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist = step;} } } @@ -1201,6 +1214,7 @@ window.CodeMirror = (function() { // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. + var nextOpId = 0; function startOperation(cm) { cm.curOp = { // An array of ranges of lines that have to be updated. See @@ -1212,7 +1226,7 @@ window.CodeMirror = (function() { selectionChanged: false, updateMaxLine: false, updateScrollPos: false, - id: ++cm.nextOpId + id: ++nextOpId }; if (!delayedCallbackDepth++) delayedCallbacks = []; } @@ -1233,7 +1247,7 @@ window.CodeMirror = (function() { var newScrollPos, updated; if (op.updateScrollPos) { newScrollPos = op.updateScrollPos; - } else if (op.selectionChanged) { + } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible var coords = cursorCoords(cm, doc.sel.head); newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); } @@ -1266,7 +1280,7 @@ window.CodeMirror = (function() { if (op.textChanged) signal(cm, "change", cm, op.textChanged); if (op.selectionChanged) signal(cm, "cursorActivity", cm); - if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](cm); + if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); } // Wraps a function in an operation. Returns the wrapped function. @@ -1333,6 +1347,13 @@ window.CodeMirror = (function() { if (!cm.state.focused || hasSelection(input) || isReadOnly(cm)) return false; var text = input.value; if (text == prevInput && posEq(sel.from, sel.to)) return false; + // IE enjoys randomly deselecting our input's text when + // re-focusing. If the selection is gone but the cursor is at the + // start of the input, that's probably what happened. + if (ie && text && input.selectionStart === 0) { + resetInput(cm, true); + return false; + } var withOp = !cm.curOp; if (withOp) startOperation(cm); sel.shift = false; @@ -1431,7 +1452,7 @@ window.CodeMirror = (function() { on(d.input, "keyup", operation(cm, function(e) { if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - if (e_prop(e, "keyCode") == 16) cm.doc.sel.shift = false; + if (e.keyCode == 16) cm.doc.sel.shift = false; })); on(d.input, "input", bind(fastPoll, cm)); on(d.input, "keydown", operation(cm, onKeyDown)); @@ -1493,7 +1514,7 @@ window.CodeMirror = (function() { target == display.scrollbarV || target == display.scrollbarV.firstChild || target == display.scrollbarFiller) return null; } - var x, y, space = display.lineSpace.getBoundingClientRect(); + var x, y, space = getRect(display.lineSpace); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } return coordsChar(cm, x - space.left, y - space.top); @@ -1502,7 +1523,7 @@ window.CodeMirror = (function() { var lastClick, lastDoubleClick; function onMouseDown(e) { var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; - sel.shift = e_prop(e, "shiftKey"); + sel.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { @@ -1591,7 +1612,7 @@ window.CodeMirror = (function() { } } - var editorSize = display.wrapper.getBoundingClientRect(); + var editorSize = getRect(display.wrapper); // 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, @@ -1687,17 +1708,17 @@ window.CodeMirror = (function() { try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } - if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false; + if (mX >= Math.floor(getRect(display.gutters).right)) return false; e_preventDefault(e); if (!hasHandler(cm, "gutterClick")) return true; - var lineBox = display.lineDiv.getBoundingClientRect(); + var lineBox = getRect(display.lineDiv); if (mY > lineBox.bottom) return true; 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) { + if (g && getRect(g).right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.options.gutters[i]; signalLater(cm, "gutterClick", cm, line, gutter, e); @@ -1838,16 +1859,16 @@ window.CodeMirror = (function() { // Ensure previous input has been read, so that the handler sees a // consistent view of the document if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; - var doc = cm.doc, prevShift = doc.sel.shift; + var doc = cm.doc, prevShift = doc.sel.shift, done = false; try { if (isReadOnly(cm)) cm.state.suppressEdits = true; if (dropShift) doc.sel.shift = false; - bound(cm); + done = bound(cm) != Pass; } finally { doc.sel.shift = prevShift; cm.state.suppressEdits = false; } - return true; + return done; } function allKeyMaps(cm) { @@ -1871,7 +1892,7 @@ window.CodeMirror = (function() { if (!name) return false; var keymaps = allKeyMaps(cm); - if (e_prop(e, "shiftKey")) { + if (e.shiftKey) { // 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-'. @@ -1908,15 +1929,15 @@ window.CodeMirror = (function() { if (!cm.state.focused) onFocus(cm); if (ie && e.keyCode == 27) { e.returnValue = false; } if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - var code = e_prop(e, "keyCode"); + var code = e.keyCode; // IE does strange things with escape. - cm.doc.sel.shift = code == 16 || e_prop(e, "shiftKey"); + cm.doc.sel.shift = code == 16 || e.shiftKey; // First give onKeyEvent option a chance to handle this. var handled = handleKeyBinding(cm, e); if (opera) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && e_prop(e, mac ? "metaKey" : "ctrlKey")) + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) cm.replaceSelection(""); } } @@ -1924,7 +1945,7 @@ window.CodeMirror = (function() { function onKeyPress(e) { var cm = this; if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; - var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); + var keyCode = e.keyCode, charCode = e.charCode; if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); @@ -2019,9 +2040,28 @@ window.CodeMirror = (function() { lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); } + // Make sure a position will be valid after the given change. + function clipPostChange(doc, change, pos) { + if (!posLess(change.from, pos)) return clipPos(doc, pos); + var diff = (change.text.length - 1) - (change.to.line - change.from.line); + if (pos.line > change.to.line + diff) { + var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; + if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); + return clipToLen(pos, getLine(doc, preLine).text.length); + } + if (pos.line == change.to.line + diff) + return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + + getLine(doc, change.to.line).text.length - change.to.ch); + var inside = pos.line - change.from.line; + return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); + } + // Hint can be null|"end"|"start"|"around"|{anchor,head} - function computeSelAfterChange(sel, change, hint) { - if (hint && typeof hint == "object") return hint; // Assumed to be {from, to} object + function computeSelAfterChange(doc, change, hint) { + if (hint && typeof hint == "object") // Assumed to be {anchor, head} object + return {anchor: clipPostChange(doc, change, hint.anchor), + head: clipPostChange(doc, change, hint.head)}; + if (hint == "start") return {anchor: change.from, head: change.from}; var end = changeEnd(change); @@ -2037,7 +2077,29 @@ window.CodeMirror = (function() { if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }; - return {anchor: adjustPos(sel.anchor), head: adjustPos(sel.head)}; + return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; + } + + function filterChange(doc, change) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + 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; + }, + cancel: function() { this.canceled = true; } + }; + 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}; } // Replace the range from from to to by the strings in replacement. @@ -2048,6 +2110,11 @@ window.CodeMirror = (function() { if (doc.cm.state.suppressEdits) return; } + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change); + 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); @@ -2062,7 +2129,7 @@ window.CodeMirror = (function() { } function makeChangeNoReadonly(doc, change, selUpdate) { - var selAfter = computeSelAfterChange(doc.sel, change, selUpdate); + var selAfter = computeSelAfterChange(doc, change, selUpdate); addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); @@ -2092,7 +2159,7 @@ window.CodeMirror = (function() { change.origin = type; anti.changes.push(historyChangeFromChange(doc, change)); - var after = i ? computeSelAfterChange(doc.sel, change, null) + var after = i ? computeSelAfterChange(doc, change, null) : {anchor: event.anchorBefore, head: event.headBefore}; makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); var rebased = []; @@ -2138,7 +2205,7 @@ window.CodeMirror = (function() { text: [change.text[0]], origin: change.origin}; } - if (!selAfter) selAfter = computeSelAfterChange(doc.sel, change, null); + if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); else updateDoc(doc, change, spans, selAfter); } @@ -2214,7 +2281,10 @@ window.CodeMirror = (function() { 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); - var ch = pos.ch, linelen = getLine(doc, pos.line).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; @@ -2242,10 +2312,24 @@ window.CodeMirror = (function() { if (doc.cm) doc.cm.curOp.userSelChange = true; } + function filterSelectionChange(doc, anchor, head) { + var obj = {anchor: anchor, head: head}; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); + return obj; + } + // Update the selection. Last two args are only used by // updateDoc, since they have to be expressed in the line // numbers before the update. function setSelection(doc, anchor, head, bias, checkAtomic) { + if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { + var filtered = filterSelectionChange(doc, anchor, head); + head = filtered.head; + anchor = filtered.anchor; + } + var sel = doc.sel; sel.goalColumn = null; // Skip over atomic spans. @@ -2263,6 +2347,8 @@ window.CodeMirror = (function() { if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + + signalLater(doc, "cursorActivity", doc); } function reCheckSelection(cm) { @@ -2321,7 +2407,7 @@ window.CodeMirror = (function() { function scrollCursorIntoView(cm) { var coords = scrollPosIntoView(cm, cm.doc.sel.head); if (!cm.state.focused) return; - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + var display = cm.display, box = getRect(display.sizer), 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) { @@ -2431,12 +2517,13 @@ window.CodeMirror = (function() { return line; } - function findPosH(doc, dir, unit, visually) { - var end = doc.sel.head, line = end.line, ch = end.ch; + function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch; var lineObj = getLine(doc, line); + var possible = true; function findNextLine() { var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return false; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); line = l; return lineObj = getLine(doc, l); } @@ -2446,10 +2533,11 @@ window.CodeMirror = (function() { if (!boundToLine && findNextLine()) { if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); else ch = dir < 0 ? lineObj.text.length : 0; - } else return false; + } else return (possible = false); } else ch = next; return true; } + if (unit == "char") moveOnce(); else if (unit == "column") moveOnce(true); else if (unit == "word") { @@ -2461,7 +2549,26 @@ window.CodeMirror = (function() { if (dir > 0) if (!moveOnce()) break; } } - return skipAtomic(doc, Pos(line, ch), dir, true); + var result = skipAtomic(doc, Pos(line, ch), dir, true); + if (!possible) result.hitSide = true; + return result; + } + + 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; + } 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; } function findWordAt(line, pos) { @@ -2585,7 +2692,7 @@ window.CodeMirror = (function() { }, coordsChar: function(coords) { - var off = this.display.lineSpace.getBoundingClientRect(); + var off = getRect(this.display.lineSpace); var scrollY = window.pageYOffset || (document.documentElement || document.body).scrollTop; var scrollX = window.pageXOffset || (document.documentElement || document.body).scrollLeft; return coordsChar(this, coords.left - off.left - scrollX, coords.top - off.top - scrollY); @@ -2699,40 +2806,55 @@ window.CodeMirror = (function() { execCommand: function(cmd) {return commands[cmd](this);}, - // Stuff used by commands, probably not much use to outside code. + 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: operation(null, function(dir, unit) { - var sel = this.doc.sel, pos = dir < 0 ? sel.from : sel.to; + var sel = this.doc.sel, pos; if (sel.shift || sel.extend || posEq(sel.from, sel.to)) - pos = findPosH(this.doc, dir, unit, this.options.rtlMoveVisually); + pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); + else + pos = dir < 0 ? sel.from : sel.to; extendSelection(this.doc, pos, pos, dir); }), deleteH: operation(null, function(dir, unit) { var sel = this.doc.sel; if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); - else replaceRange(this.doc, "", sel.from, findPosH(this.doc, dir, unit, false), "+delete"); + else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); this.curOp.userSelChange = true; }), - moveV: operation(null, function(dir, unit) { - var doc = this.doc, display = this.display; - var cur = doc.sel.head, pos = cursorCoords(this, cur, "div"); - var x = pos.left, y; - if (doc.sel.goalColumn != null) x = doc.sel.goalColumn; - if (unit == "page") { - var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - y = pos.top + dir * pageSize; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + 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; } - do { - var target = coordsChar(this, x, y); - y += dir * 5; - } while (target.outside && (dir < 0 ? y > 0 : y < doc.height)); + return cur; + }, - if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; + moveV: operation(null, function(dir, unit) { + var sel = this.doc.sel; + var pos = cursorCoords(this, sel.head, "div"); + if (sel.goalColumn != null) pos.left = sel.goalColumn; + var target = findPosV(this, pos, dir, unit); + + if (unit == "page") + this.display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; extendSelection(this.doc, target, target, dir); - doc.sel.goalColumn = x; + sel.goalColumn = pos.left; }), toggleOverwrite: function() { @@ -3097,11 +3219,7 @@ window.CodeMirror = (function() { map = getKeyMap(map); var found = map[name]; if (found === false) return "stop"; - if (found != null) { - try { var done = handle(found); } - catch (e) { if (e != Pass) throw e; } - if (done) return true; - } + if (found != null && handle(found)) return true; if (map.nofallthrough) return "stop"; var fallthrough = map.fallthrough; @@ -3121,16 +3239,16 @@ window.CodeMirror = (function() { } } function isModifierKey(event) { - var name = keyNames[e_prop(event, "keyCode")]; + var name = keyNames[event.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; } function keyName(event, noShift) { - var name = keyNames[e_prop(event, "keyCode")]; + var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) return false; - if (e_prop(event, "altKey")) name = "Alt-" + name; - if (e_prop(event, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; - if (e_prop(event, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; - if (!noShift && e_prop(event, "shiftKey")) name = "Shift-" + name; + if (event.altKey) name = "Alt-" + name; + if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; + if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; + if (!noShift && event.shiftKey) name = "Shift-" + name; return name; } CodeMirror.lookupKey = lookupKey; @@ -3259,9 +3377,6 @@ window.CodeMirror = (function() { } CodeMirror.TextMarker = TextMarker; - TextMarker.prototype.clearAll = function() { - this.lines = []; - } TextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; var cm = this.doc.cm, withOp = cm && !cm.curOp; @@ -3859,6 +3974,21 @@ window.CodeMirror = (function() { if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) builder.pre.appendChild(document.createTextNode("\u00a0")); + var order; + // Work around problem with the reported dimensions of single-char + // direction spans on IE (issue #1129). See also the comment in + // cursorCoords. + if (measure && ie && (order = getOrder(line))) { + var l = order.length - 1; + if (order[l].from == order[l].to) --l; + var last = order[l], prev = order[l - 1]; + if (last.from + 1 == last.to && prev && last.level < prev.level) { + var span = measure[builder.pos - 1]; + if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), + span.nextSibling); + } + } + return builder.pre; } @@ -3903,13 +4033,18 @@ window.CodeMirror = (function() { function buildTokenMeasure(builder, text, style, startStyle, endStyle) { for (var i = 0; i < text.length; ++i) { - if (i && i < text.length && - builder.cm.options.lineWrapping && - spanAffectsWrapping.test(text.slice(i - 1, i + 1))) + var ch = text.charAt(i), start = i == 0; + if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { + ch = text.slice(i, i + 2); + ++i; + } else if (i && builder.cm.options.lineWrapping && + spanAffectsWrapping.test(text.slice(i - 1, i + 1))) { builder.pre.appendChild(elt("wbr")); - builder.measure[builder.pos++] = - buildToken(builder, text.charAt(i), style, - i == 0 && startStyle, i == text.length - 1 && endStyle); + } + builder.measure[builder.pos] = + buildToken(builder, ch, style, + start && startStyle, i == text.length - 1 && endStyle); + builder.pos += ch.length; } if (text.length) builder.addedOne = true; } @@ -4028,6 +4163,7 @@ window.CodeMirror = (function() { doc.insert(from.line + 1, added); } + signalLater(doc, "change", doc, change); setSelection(doc, selAfter.anchor, selAfter.head, null, true); } @@ -4182,7 +4318,7 @@ window.CodeMirror = (function() { Doc.prototype = createObj(BranchChunk.prototype, { iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - (from - this.first), op); + if (op) this.iterN(from - this.first, to - from, op); else this.iterN(this.first, this.first + this.size, from); }, @@ -4307,6 +4443,15 @@ window.CodeMirror = (function() { } return markers; }, + 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; @@ -4378,14 +4523,11 @@ window.CodeMirror = (function() { Doc.prototype.eachLine = Doc.prototype.iter; // The Doc methods that should be available on CodeMirror instances - var toDelegate = ("setValue getValue getSelection replaceSelection eachLine undo redo historySize clearHistory markClean isClean " + - "getHistory setHistory markText setBookmark findMarksAt lineCount firstLine lastLine clipPos getCursor " + - "somethingSelected setCursor setSelection extendSelection setExtending getLine setLine removeLine getMode " + - "replaceRange getRange getLineHandle getLineNumber posFromIndex indexFromPos linkedDoc unlinkDoc iterLinkedDocs").split(" "); - for (var i = 0; i < toDelegate.length; ++i) (function(method) { - var target = Doc.prototype[method]; - CodeMirror.prototype[method] = function() {return target.apply(this.doc, arguments);}; - })(toDelegate[i]); + var dontDelegate = "iter insert remove copy getEditor".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]); function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { @@ -4701,13 +4843,6 @@ window.CodeMirror = (function() { return b; } - // Allow 3rd-party code to override event properties by adding an override - // object to an event object. - function e_prop(e, prop) { - var overridden = e.override && e.override.hasOwnProperty(prop); - return overridden ? e.override[prop] : e[prop]; - } - // EVENT HANDLING function on(emitter, type, f) { @@ -4747,10 +4882,21 @@ window.CodeMirror = (function() { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); + if (!delayedCallbacks) { + ++delayedCallbackDepth; + delayedCallbacks = []; + setTimeout(fireDelayed, 0); + } function bnd(f) {return function(){f.apply(null, args);};}; for (var i = 0; i < arr.length; ++i) - if (delayedCallbacks) delayedCallbacks.push(bnd(arr[i])); - else arr[i].apply(null, args); + delayedCallbacks.push(bnd(arr[i])); + } + + function fireDelayed() { + --delayedCallbackDepth; + var delayed = delayedCallbacks; + delayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); } function hasHandler(emitter, type) { @@ -4811,9 +4957,9 @@ window.CodeMirror = (function() { } function createObj(base, props) { - if (!base) return; - createObj.prototype = base; - var inst = new createObj(); + function Obj() {} + Obj.prototype = base; + var inst = new Obj(); if (props) copyObj(props, inst); return inst; } @@ -4845,7 +4991,7 @@ window.CodeMirror = (function() { return true; } - var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/; + var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; // DOM UTILITIES @@ -4876,6 +5022,11 @@ window.CodeMirror = (function() { } else e.textContent = str; } + function getRect(node) { + return node.getBoundingClientRect(); + } + CodeMirror.replaceGetRect = function(f) { getRect = f; }; + // FEATURE DETECTION // Detect drag-and-drop @@ -5227,7 +5378,7 @@ window.CodeMirror = (function() { // THE END - CodeMirror.version = "3.02 +"; + CodeMirror.version = "3.1"; return CodeMirror; })(); diff --git a/lib/mergely.css b/lib/mergely.css index 4a45d4d..47ea4e7 100644 --- a/lib/mergely.css +++ b/lib/mergely.css @@ -1,8 +1,3 @@ -/** - * Copyright (c) 2013 by Jamie Peabody, http://www.mergely.com - * All rights reserved. - * Version: 3.1 2013-01-05 - */ /* required */ .mergely-column textarea { width: 80px; height: 200px; } .mergely-column { float: left; } @@ -19,7 +14,7 @@ .mergely.a.rhs.start { border-top: 1px solid #a3d1ff; } .mergely.a.lhs.start.end, .mergely.a.rhs.end { border-bottom: 1px solid #a3d1ff; } -.mergely.bg.a.rhs { background-color: #ddeeff; } +.mergely.a.rhs { background-color: #ddeeff; } .mergely.d.lhs { background-color: #edc0c0; } .mergely.d.lhs.end, @@ -30,9 +25,9 @@ .mergely.c.lhs, .mergely.c.rhs { background-color: #fafafa; } .mergely.c.lhs.start, -.mergely.c.rhs.start { border-top: 1px solid #ccc; } +.mergely.c.rhs.start { border-top: 1px solid #a3a3a3; } .mergely.c.lhs.end, -.mergely.c.rhs.end { border-bottom: 1px solid #ccc; } +.mergely.c.rhs.end { border-bottom: 1px solid #a3a3a3; } .mergely.ch.a.rhs { background-color: #ddeeff; } .mergely.ch.d.lhs { background-color: #edc0c0; text-decoration: line-through; color: #888; } diff --git a/lib/mergely.js b/lib/mergely.js index 5e4b855..64f58e8 100644 --- a/lib/mergely.js +++ b/lib/mergely.js @@ -1,8 +1,3 @@ -/** - * Copyright (c) 2013 by Jamie Peabody, http://www.mergely.com - * All rights reserved. - * Version: 3.1 2013-01-05 - */ Mgly = {}; Mgly.Timer = function(){ @@ -361,13 +356,15 @@ jQuery.extend(Mgly.mergely.prototype, { this.settings = { autoupdate: true, autoresize: true, + lcs: true, + sidebar: true, ignorews: false, fadein: 'fast', editor_width: '400px', editor_height: '400px', resize_timeout: 500, change_timeout: 150, - fgcolor: {a:'#4ba3fa',c:'#cccccc',d:'#ff7f7f'}, + fgcolor: {a:'#4ba3fa',c:'#a3a3a3',d:'#ff7f7f'}, _bgcolor: '#eee', lhs: function(setValue) { }, rhs: function(setValue) { }, @@ -394,7 +391,7 @@ jQuery.extend(Mgly.mergely.prototype, { } if (this.resized) this.resized(); }, - _debug: 'change', //scroll,draw,calc,diff,markup,change + _debug: '', //scroll,draw,calc,diff,markup,change resized: function() { } }; var cmsettings = { @@ -448,7 +445,7 @@ jQuery.extend(Mgly.mergely.prototype, { // resize var sz_timeout1 = null; var sz = function() { - self.em_height = null; //recalculate + //self.em_height = null; //recalculate if (self.settings.resize) self.settings.resize(); self.editor[self.id + '-lhs'].refresh(); self.editor[self.id + '-rhs'].refresh(); @@ -498,6 +495,7 @@ jQuery.extend(Mgly.mergely.prototype, { options: function(opts) { if (opts) { jQuery.extend(this.settings, opts); + this.resize(); } else { return this.settings; @@ -568,6 +566,7 @@ jQuery.extend(Mgly.mergely.prototype, { this.change_funcs = []; this.prev_query = []; this.cursor = []; + this._skipscroll = {}; this.change_exp = new RegExp(/(\d+(?:,\d+)?)([acd])(\d+(?:,\d+)?)/); var merge_lhs_button; var merge_rhs_button; @@ -608,9 +607,9 @@ jQuery.extend(Mgly.mergely.prototype, { }, _scrolling: function(editor_name) { - if (self._skipscroll === true) { + if (this._skipscroll[editor_name] === true) { // scrolling one side causes the other to event - ignore it - self._skipscroll = false; + this._skipscroll[editor_name] = false; return; } var scroller = jQuery(this.editor[editor_name].getScrollerElement()); @@ -628,6 +627,9 @@ jQuery.extend(Mgly.mergely.prototype, { this.trace('scroll', 'top_to', top_to); this.trace('scroll', 'left_to', left_to); + var editor_name1 = this.id + '-lhs'; + var editor_name2 = this.id + '-rhs'; + for (var name in this.editor) { if (!this.editor.hasOwnProperty(name)) continue; if (editor_name == name) continue; //same editor @@ -638,37 +640,54 @@ jQuery.extend(Mgly.mergely.prototype, { // find the last change that is less than or within the midway point // do not move the rhs until the lhs end point is >= the rhs end point. var last_change = null; + var force_scroll = false; for (var i = 0; i < this.changes.length; ++i) { var change = this.changes[i]; if ((midline.line >= change[this_side+'-line-from'])) { last_change = change; if (midline.line >= last_change[this_side+'-line-to']) { - top_adjust += - (change[this_side+'-y-end'] - change[this_side+'-y-start']) - - (change[other_side+'-y-end'] - change[other_side+'-y-start']); + if (!change.hasOwnProperty(this_side+'-y-start') || + !change.hasOwnProperty(this_side+'-y-end') || + !change.hasOwnProperty(other_side+'-y-start') || + !change.hasOwnProperty(other_side+'-y-end')){ + // change outside of viewport + force_scroll = true; + } + else { + top_adjust += + (change[this_side+'-y-end'] - change[this_side+'-y-start']) - + (change[other_side+'-y-end'] - change[other_side+'-y-start']); + } } } } + var vp = this.editor[name].getViewport(); var scroll = true; if (last_change) { this.trace('scroll', 'last change before midline', last_change); - if ((last_change[this_side+'-line-from'] < midline.line) && - (last_change[this_side+'-line-to'] > midline.line)) { + if (midline.line >= vp.from && midline <= vp.to) { scroll = false; } } this.trace('scroll', 'scroll', scroll); - if (scroll) { + if (scroll || force_scroll) { // scroll the other side this.trace('scroll', 'scrolling other side', top_to - top_adjust); var scroller = jQuery(this.editor[name].getScrollerElement()); - self._skipscroll = true;//disable next event + this._skipscroll[name] = true;//disable next event scroller.scrollTop(top_to - top_adjust).scrollLeft(left_to); } else this.trace('scroll', 'not scrolling other side'); - this._calculate_offsets(this.id + '-lhs', this.id + '-rhs', this.changes); - this._draw_diff(this.id + '-lhs', this.id + '-rhs', this.changes); + + var timer = new Mgly.Timer(); + this._calculate_offsets(editor_name1, editor_name2, this.changes); + this.trace('change', 'offsets time', timer.stop()); + this._markup_changes(editor_name1, editor_name2, this.changes); + this.trace('change', 'markup time', timer.stop()); + this._draw_diff(editor_name1, editor_name2, this.changes); + this.trace('change', 'draw time', timer.stop()); + this.trace('scroll', 'scrolled'); } }, @@ -755,13 +774,20 @@ jQuery.extend(Mgly.mergely.prototype, { } return changes; }, - _get_extents: function() { - return { - 'top-offset': this.draw_top_offset, - 'em-height': this.em_height, - 'draw-lhs-min': this.draw_lhs_min, - 'draw-rhs-max': this.draw_rhs_max - }; + _get_viewport: function(editor_name1, editor_name2) { + var lhsvp = this.editor[editor_name1].getViewport(); + var rhsvp = this.editor[editor_name2].getViewport(); + return {from: Math.min(lhsvp.from, rhsvp.from), to: Math.max(lhsvp.to, rhsvp.to)}; + }, + _is_change_in_view: function(vp, change) { + if ((change['lhs-line-from'] < vp.from && change['lhs-line-to'] < vp.to) || + (change['lhs-line-from'] > vp.from && change['lhs-line-to'] > vp.to) || + (change['rhs-line-from'] < vp.from && change['rhs-line-to'] < vp.to) || + (change['rhs-line-from'] > vp.from && change['rhs-line-to'] > vp.to)) { + // if the change is outside the viewport, skip + return false; + } + return true; }, _calculate_offsets: function (editor_name1, editor_name2, changes) { if (this.em_height == null) { @@ -789,12 +815,61 @@ jQuery.extend(Mgly.mergely.prototype, { this.draw_rhs_width = 5; this.trace('calc', 'change offsets calculated', {top_offset: top_offset, lhs_min: this.draw_lhs_min, rhs_max: this.draw_rhs_max, lhs_width: this.draw_lhs_width, rhs_width: this.draw_rhs_width}); } + var lhschc = this.editor[editor_name1].charCoords({line: 0}); + var rhschc = this.editor[editor_name2].charCoords({line: 0}); + var vp = this._get_viewport(editor_name1, editor_name2); + for (var i = 0; i < changes.length; ++i) { var change = changes[i]; - var ls = this.editor[editor_name1].charCoords({line: change['lhs-line-from']}); - var le = this.editor[editor_name1].charCoords({line: change['lhs-line-to']}); - var rs = this.editor[editor_name2].charCoords({line: change['rhs-line-from']}); - var re = this.editor[editor_name2].charCoords({line: change['rhs-line-to']}); + + if (!this.settings.sidebar && !this._is_change_in_view(vp, change)) { + // if the change is outside the viewport, skip + delete change['lhs-y-start']; + delete change['lhs-y-end']; + delete change['rhs-y-start']; + delete change['rhs-y-end']; + continue; + } + + var ls, le, rs, re; + if (this.editor[editor_name1].getOption('lineWrapping') || this.editor[editor_name1].getOption('lineWrapping')) { + // If using line-wrapping, we must get the height of the line + var tls = this.editor[editor_name1].cursorCoords({line: change['lhs-line-from'], ch: 0}, 'page'); + var lhssh = this.editor[editor_name1].getLineHandle(change['lhs-line-from']); + ls = { top: tls.top, bottom: tls.top + lhssh.height }; + + var tle = this.editor[editor_name1].cursorCoords({line: change['lhs-line-to'], ch: 0}, 'page'); + var lhseh = this.editor[editor_name1].getLineHandle(change['lhs-line-to']); + le = { top: tle.top, bottom: tle.top + lhseh.height }; + + var tls = this.editor[editor_name2].cursorCoords({line: change['rhs-line-from'], ch: 0}, 'page'); + var rhssh = this.editor[editor_name2].getLineHandle(change['rhs-line-from']); + rs = { top: tls.top, bottom: tls.top + rhssh.height }; + + var tle = this.editor[editor_name2].cursorCoords({line: change['rhs-line-to'], ch: 0}, 'page'); + var rhseh = this.editor[editor_name2].getLineHandle(change['rhs-line-to']); + re = { top: tle.top, bottom: tle.top + rhseh.height }; + } + else { + // If not using line-wrapping, we can calculate the line position + ls = { + top: lhschc.top + change['lhs-line-from'] * this.em_height, + bottom: lhschc.bottom + change['lhs-line-from'] * this.em_height + 2 + }; + le = { + top: lhschc.top + change['lhs-line-to'] * this.em_height, + bottom: lhschc.bottom + change['lhs-line-to'] * this.em_height + 2 + }; + rs = { + top: rhschc.top + change['rhs-line-from'] * this.em_height, + bottom: rhschc.bottom + change['rhs-line-from'] * this.em_height + 2 + }; + re = { + top: rhschc.top + change['rhs-line-to'] * this.em_height, + bottom: rhschc.bottom + change['rhs-line-to'] * this.em_height + 2 + }; + } + if (change['op'] == 'a') { // adds (right), normally start from the end of the lhs, // except for the case when the start of the rhs is 0 @@ -837,6 +912,7 @@ jQuery.extend(Mgly.mergely.prototype, { var self = this; var led = this.editor[editor_name1]; var red = this.editor[editor_name2]; + var timer = new Mgly.Timer(); led.operation(function() { for (var i = 0; i < changes.length; ++i) { @@ -858,32 +934,32 @@ jQuery.extend(Mgly.mergely.prototype, { } } - // add widgets - var lhs_button = self.merge_lhs_button.clone(); - if (lhs_button.button) { - //jquery-ui support - lhs_button.button({icons: {primary: 'ui-icon-triangle-1-w'}, text: false}); + if (!red.getOption('readOnly')) { + // add widgets to lhs, if rhs is not read only + var rhs_button = self.merge_rhs_button.clone(); + if (rhs_button.button) { + //jquery-ui support + rhs_button.button({icons: {primary: 'ui-icon-triangle-1-e'}, text: false}); + } + rhs_button.addClass('merge-button'); + rhs_button.attr('id', 'merge-rhs-' + i); + led.setGutterMarker(change['lhs-line-from'], 'merge', rhs_button.get(0)); } - lhs_button.addClass('merge-button'); - lhs_button.attr('id', 'merge-lhs-' + i); - red.setGutterMarker(change['rhs-line-from'], 'merge', lhs_button.get(0)); - - var rhs_button = self.merge_rhs_button.clone(); - if (rhs_button.button) { - //jquery-ui support - rhs_button.button({icons: {primary: 'ui-icon-triangle-1-e'}, text: false}); - } - rhs_button.addClass('merge-button'); - rhs_button.attr('id', 'merge-rhs-' + i); - led.setGutterMarker(change['lhs-line-from'], 'merge', rhs_button.get(0)); } }); + + var vp = this._get_viewport(editor_name1, editor_name2); this.trace('change', 'markup lhs-editor time', timer.stop()); red.operation(function() { for (var i = 0; i < changes.length; ++i) { var change = changes[i]; + if (!self._is_change_in_view(vp, change)) { + // if the change is outside the viewport, skip + continue; + } + var clazz = ['mergely', 'rhs', change['op'], 'cid-' + i]; red.addLineClass(change['rhs-line-from'], 'background', 'start'); red.addLineClass(change['rhs-line-to'], 'background', 'end'); @@ -899,15 +975,31 @@ jQuery.extend(Mgly.mergely.prototype, { red.addLineClass(j, 'background', clazz.join(' ')); } } + + if (!led.getOption('readOnly')) { + // add widgets to rhs, if lhs is not read only + var lhs_button = self.merge_lhs_button.clone(); + if (lhs_button.button) { + //jquery-ui support + lhs_button.button({icons: {primary: 'ui-icon-triangle-1-w'}, text: false}); + } + lhs_button.addClass('merge-button'); + lhs_button.attr('id', 'merge-lhs-' + i); + red.setGutterMarker(change['rhs-line-from'], 'merge', lhs_button.get(0)); + } } }); this.trace('change', 'markup rhs-editor time', timer.stop()); // mark text deleted, LCS changes var marktext = []; - for (var i = 0; i < changes.length; ++i) { + for (var i = 0; this.settings.lcs && i < changes.length; ++i) { var change = changes[i]; - + + if (!this._is_change_in_view(vp, change)) { + // if the change is outside the viewport, skip + continue; + } if (change['op'] == 'd') { // apply delete to cross-out (left-hand side only) var from = change['lhs-line-from']; @@ -936,10 +1028,10 @@ jQuery.extend(Mgly.mergely.prototype, { } var lhs_line = led.getLine( j ); var rhs_line = red.getLine( k ); - var lhs_start = { 'line': -1, 'ch': -1 }; - var lhs_stop = { 'line': -1, 'ch': -1 }; - var rhs_start = { 'line': -1, 'ch': -1 }; - var rhs_stop = { 'line': -1, 'ch': -1 }; + var lhs_start = { line: -1, ch: -1 }; + var lhs_stop = { line: -1, ch: -1 }; + var rhs_start = { line: -1, ch: -1 }; + var rhs_stop = { line: -1, ch: -1 }; var lcs = new Mgly.LCS(lhs_line, rhs_line); var max = Math.max(lhs_line.length, rhs_line.length); @@ -1001,6 +1093,7 @@ jQuery.extend(Mgly.mergely.prototype, { } } } + this.trace('change', 'LCS marktext time', timer.stop()); // mark changes outside closure led.operation(function() { @@ -1020,6 +1113,7 @@ jQuery.extend(Mgly.mergely.prototype, { self.change_funcs.push(m[0].markText(m[1], m[2], m[3])); } }); + this.trace('change', 'LCS markup time', timer.stop()); // merge buttons var ed = {lhs:led, rhs:red}; @@ -1050,13 +1144,13 @@ jQuery.extend(Mgly.mergely.prototype, { var line = {lhs: ed['lhs'].lineInfo(change['lhs-line-to']), rhs: ed['rhs'].lineInfo(change['rhs-line-to'])}; var text = ed[side].getRange( - { 'line': change[side + '-line-from'], 'ch': 0 }, - { 'line': change[side + '-line-to'], 'ch': line[side].text.length }); + { line: change[side + '-line-from'], ch: 0 }, + { line: change[side + '-line-to'], ch: line[side].text.length }); if (change['op'] == 'c') { ed[oside].replaceRange( text, - { 'line': change[oside + '-line-from'], 'ch': 0 }, - { 'line': change[oside + '-line-to'], 'ch': line[oside].text.length }); + { line: change[oside + '-line-from'], ch: 0 }, + { line: change[oside + '-line-to'], ch: line[oside].text.length }); } else {// 'a' or 'd' var from = parseInt(change[oside + '-line-from']); @@ -1118,36 +1212,10 @@ jQuery.extend(Mgly.mergely.prototype, { ctx_rhs.fillRect(0, 0, 6.5, visible_page_height); ctx_rhs.strokeRect(0, 0, 6.5, visible_page_height); + var vp = this._get_viewport(editor_name1, editor_name2); for (var i = 0; i < changes.length; ++i) { var change = changes[i]; - var lhs_y_start = change['lhs-y-start']; - var lhs_y_end = change['lhs-y-end']; - var rhs_y_start = change['rhs-y-start']; - var rhs_y_end = change['rhs-y-end']; - - // draw left box - ctx.beginPath(); - ctx.strokeStyle = this.settings.fgcolor[change['op']]; - ctx.lineWidth = 1; - ctx.moveTo(this.draw_lhs_min, lhs_y_start); - ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_start); - ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_end + 1); - ctx.lineTo(this.draw_lhs_min, lhs_y_end + 1); - ctx.stroke(); - - // draw right box - ctx.moveTo(this.draw_rhs_max, rhs_y_start); - ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_start); - ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_end + 1); - ctx.lineTo(this.draw_rhs_max, rhs_y_end + 1); - ctx.stroke(); - - // connect boxes - ctx.moveTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_start + (lhs_y_end + 1 - lhs_y_start) / 2.0); - ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_start + (rhs_y_end + 1 - rhs_y_start) / 2.0); - ctx.stroke(); - this.trace('draw', change); // margin indicators lhs_y_start = ((change['lhs-y-start'] + lhs_scroller.scrollTop()) * visible_page_ratio); @@ -1169,6 +1237,91 @@ jQuery.extend(Mgly.mergely.prototype, { ctx_rhs.lineWidth = 0.5; ctx_rhs.fillRect(1.5, rhs_y_start, 4.5, Math.max(rhs_y_end - rhs_y_start, 5)); ctx_rhs.strokeRect(1.5, rhs_y_start, 4.5, Math.max(rhs_y_end - rhs_y_start, 5)); + + if (!this._is_change_in_view(vp, change)) { + continue; + } + + var lhs_y_start = change['lhs-y-start']; + var lhs_y_end = change['lhs-y-end']; + var rhs_y_start = change['rhs-y-start']; + var rhs_y_end = change['rhs-y-end']; + + var radius = 3; + + // draw left box + ctx.beginPath(); + ctx.strokeStyle = this.settings.fgcolor[change['op']]; + ctx.lineWidth = 1; + + var rectWidth = this.draw_lhs_width; + var rectHeight = lhs_y_end - lhs_y_start - 1; + var rectX = this.draw_lhs_min; + var rectY = lhs_y_start; + // top and top top-right corner + + // draw left box + ctx.moveTo(rectX, rectY); + if (navigator.appName == 'Microsoft Internet Explorer') { + // IE arcs look awful + ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_start); + ctx.lineTo(this.draw_lhs_min + this.draw_lhs_width, lhs_y_end + 1); + ctx.lineTo(this.draw_lhs_min, lhs_y_end + 1); + } + else { + if (rectHeight <= 0) { + ctx.lineTo(rectX + rectWidth, rectY); + } + else { + ctx.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + radius, radius); + ctx.arcTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - radius, rectY + rectHeight, radius); + } + // bottom line + ctx.lineTo(rectX, rectY + rectHeight); + } + ctx.stroke(); + + rectWidth = this.draw_rhs_width; + rectHeight = rhs_y_end - rhs_y_start - 1; + rectX = this.draw_rhs_max; + rectY = rhs_y_start; + + // draw right box + ctx.moveTo(rectX, rectY); + if (navigator.appName == 'Microsoft Internet Explorer') { + ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_start); + ctx.lineTo(this.draw_rhs_max - this.draw_rhs_width, rhs_y_end + 1); + ctx.lineTo(this.draw_rhs_max, rhs_y_end + 1); + } + else { + if (rectHeight <= 0) { + ctx.lineTo(rectX - rectWidth, rectY); + } + else { + ctx.arcTo(rectX - rectWidth, rectY, rectX - rectWidth, rectY + radius, radius); + ctx.arcTo(rectX - rectWidth, rectY + rectHeight, rectX - radius, rectY + rectHeight, radius); + } + ctx.lineTo(rectX, rectY + rectHeight); + } + ctx.stroke(); + + // connect boxes + var cx = this.draw_lhs_min + this.draw_lhs_width; + var cy = lhs_y_start + (lhs_y_end + 1 - lhs_y_start) / 2.0; + var dx = this.draw_rhs_max - this.draw_rhs_width; + var dy = rhs_y_start + (rhs_y_end + 1 - rhs_y_start) / 2.0; + ctx.moveTo(cx, cy); + if (cy == dy) { + ctx.lineTo(dx, dy); + } + else { + // fancy! + ctx.bezierCurveTo( + cx + 12, cy - 3, // control-1 X,Y + dx - 12, dy - 3, // control-2 X,Y + dx, dy); + } + ctx.stroke(); } // visible window feedback diff --git a/lib/searchcursor.js b/lib/searchcursor.js index 1750aad..7cb44e4 100755 --- a/lib/searchcursor.js +++ b/lib/searchcursor.js @@ -1,9 +1,11 @@ (function(){ + var Pos = CodeMirror.Pos; + function SearchCursor(cm, query, pos, caseFold) { this.atOccurrence = false; this.cm = cm; if (caseFold == null && typeof query == "string") caseFold = false; - pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0}; + pos = pos ? cm.clipPos(pos) : Pos(0, 0); this.pos = {from: pos, to: pos}; // The matches method is filled in based on the type of query. @@ -18,7 +20,7 @@ var line = cm.getLine(pos.line).slice(0, pos.ch), match = query.exec(line), start = 0; while (match) { start += match.index + 1; - line = line.slice(start); + line = line.slice(start); query.lastIndex = 0; var newmatch = query.exec(line); if (newmatch) match = newmatch; @@ -30,9 +32,9 @@ var line = cm.getLine(pos.line), match = query.exec(line), start = match && match.index; } - if (match) - return {from: {line: pos.line, ch: start}, - to: {line: pos.line, ch: start + match[0].length}, + if (match && match[0]) + return {from: Pos(pos.line, start), + to: Pos(pos.line, start + match[0].length), match: match}; }; } else { // String query @@ -40,15 +42,21 @@ 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) - this.matches = function(reverse, pos) { - var line = fold(cm.getLine(pos.line)), len = query.length, match; - if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) - : (match = line.indexOf(query, pos.ch)) != -1) - return {from: {line: pos.line, ch: match}, - to: {line: pos.line, ch: match + len}}; - }; - else + if (target.length == 1) { + if (!query.length) { + // Empty string would match anything and never progress, so + // we define it to match nothing instead. + this.matches = function() {}; + } else { + this.matches = function(reverse, pos) { + var line = fold(cm.getLine(pos.line)), len = query.length, match; + if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) + : (match = line.indexOf(query, pos.ch)) != -1) + return {from: Pos(pos.line, match), + to: Pos(pos.line, match + len)}; + }; + } + } else { this.matches = function(reverse, pos) { var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln)); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); @@ -66,10 +74,11 @@ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; - var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB}; + var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB); return {from: reverse ? end : start, to: reverse ? start : end}; } }; + } } } @@ -80,7 +89,7 @@ find: function(reverse) { var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to); function savePosAndFail(line) { - var pos = {line: line, ch: 0}; + var pos = Pos(line, 0); self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; @@ -88,17 +97,18 @@ for (;;) { if (this.pos = this.matches(reverse, pos)) { + if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); } this.atOccurrence = true; return this.pos.match || true; } if (reverse) { if (!pos.line) return savePosAndFail(0); - pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length}; + pos = Pos(pos.line-1, this.cm.getLine(pos.line-1).length); } else { var maxLine = this.cm.lineCount(); if (pos.line == maxLine - 1) return savePosAndFail(maxLine); - pos = {line: pos.line+1, ch: 0}; + pos = Pos(pos.line + 1, 0); } } }, @@ -107,13 +117,15 @@ to: function() {if (this.atOccurrence) return this.pos.to;}, replace: function(newText) { - var self = this; - if (this.atOccurrence) - self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to); + if (!this.atOccurrence) return; + var lines = CodeMirror.splitLines(newText); + this.cm.replaceRange(lines, this.pos.from, this.pos.to); + this.pos.to = Pos(this.pos.from.line + lines.length - 1, + lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); } }; CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { return new SearchCursor(this, query, pos, caseFold); }); -})(); +})(); \ No newline at end of file