Repository: vim-dist/webvim Branch: master Commit: 10719962d722 Files: 16 Total size: 139.0 KB Directory structure: gitextract_6tlduukb/ ├── .editorconfig ├── .gitignore ├── .tern-project ├── .vimrc ├── LICENSE ├── README.md ├── autoload/ │ └── plug.vim ├── config/ │ ├── abbrev.vim │ ├── autocmd.vim │ ├── mapping.vim │ └── setting.vim ├── fonts/ │ ├── 10-powerline-symbols.conf │ ├── PowerlineSymbols.otf │ └── install └── plugins/ ├── config.vim └── def.vim ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ ; .editorconfig root = true [*] end_of_line = lf insert_final_newline = true indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = true [**.json] indent_style = space indent_size = 2 [**.html] brace_style = expand ================================================ FILE: .gitignore ================================================ local.vim plugins/plugged/* nerdtree_plugin spell ================================================ FILE: .tern-project ================================================ { "libs" : ["ecma6", "browser", "requirejs"], "plugins": { "node" : {}, "es_modules" : {}, "requirejs" : {} }, "ecmaVersion": 6 } ================================================ FILE: .vimrc ================================================ " " WebVim Configuration entry point " " author: Bertrand Chevrier " source: https://github.com/krampstudio/dotvim " year : 2015 " " You won't find any configuration here directly, " please look at files under the config folder for global config " and under plugins for plugins configuration filetype plugin on let g:vimDir = $HOME.'/.vim' let g:hardcoreMode = 1 let s:pluginDir = g:vimDir.'/plugins/plugged' let s:pluginDef = g:vimDir.'/plugins/def.vim' let s:pluginConf = g:vimDir.'/plugins/config.vim' let s:configSetting = g:vimDir.'/config/setting.vim' let s:configMapping = g:vimDir.'/config/mapping.vim' let s:configAbbrev = g:vimDir.'/config/abbrev.vim' let s:configAutocmd = g:vimDir.'/config/autocmd.vim' let s:userConfig = g:vimDir.'/local.vim' if !isdirectory(s:pluginDir) " Welcome message when plugins are not yet installed echom " " echom "Welcome to WebVim" echom " > the vim IDE for web dev <" echom " " echom "Checking dependencies :" if (!executable('node') && !executable('nodejs')) || !executable('npm') echom " [ERR] node.js and npm are required, please install them before continuing." echom " " else echom " - nodejs : ok" echom " - npm : ok" echom " - eslint : " . (executable('eslint') ? "ok" : "no (optional)") echom " - jsonlint : " . (executable('jsonlint') ? "ok" : "no (optional)") echom " - csslint : " . (executable('csslint') ? "ok" : "no (optional)") echom " done." echom " " echom "We are going to install the plugins : " echom " 1. take a coffee" echom " 2. reload vim" echom " 3. Envoy WebVim" echom " " echom "Please note if you want to have the arrows keys and , disable the 'hardcoreMode' in the vimrc" echom " " exec ":source ".s:pluginDef "Install plugins on first run autocmd VimEnter * PlugInstall endif else " Loads the global config, mapping and settings exec ":source ".s:configSetting exec ":source ".s:configMapping exec ":source ".s:configAbbrev exec ":source ".s:configAutocmd " Loads plugins def and config exec ":source ".s:pluginDef exec ":source ".s:pluginConf " user configuration if filereadable(s:userConfig) exec ":source ".s:userConfig endif endif ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE http://www.gnu.org/licenses/gpl-3.0.txt 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 . ================================================ FILE: README.md ================================================ ![WebVim](resources/WebVim.png?v=2 "WebVim") =============================== WebVim is a Vim based distribution targeting JavaScript and Web development. It targets : - JavaScript development (ES5, ES6, node.js) - HTML5 - CSS3 and SCSS And contains the features you expect from a modern code editor : - syntax highlighting - syntax and error checking - autocompletion - multi cursor - git support - code format - support coding conventions (editorconfig) - hardcore mode (for real Vim users) - Emmet support - jsdoc generation (coming soon) - debugging (coming soon) - grunt/gulp support (coming soon) - all the awesomeness from Vim > The WebVim idea is to provide you a vim distribution: something that comes prepackaged, preconfigured, built on a kernel to serve a goal. WebVim is to vim what Debian is to Linux, a vim distribution for the web. ## Install __Only tested on Linux__ ### Dependencies (the long story) On Ubuntu (from 15.04) 1. A modern version of Vim ```sh apt-get install vim vim-runtime vim-gui-common ``` or compile a recent version with `xterm_clipboard` and `ruby` or `python` support. 2. Some tools to compile YouCompleteMe ```sh apt-get install build-essential cmake python-dev exuberant-ctags ``` 3. Node.js and npm ```sh curl -sL https://deb.nodesource.com/setup_0.12 | bash - apt-get install -y nodejs ``` 4. Some npm packages ```sh npm install -g eslint csslint jshint jsonlint handlebars ``` ### Dependencies (the short story) > Please report me what you did to make it work on your OS #### Fedora 23/24 ```sh sudo dnf install cmake python-devel npm vim npm install -g npm eslint csslint jshint jsonlint handlebars ``` ### Install it: ```sh git clone https://github.com/krampstudio/webvim.git ~/.vim ln -s ~/.vim/.vimrc ~/.vimrc ln -s ~/.vim/.tern-project ~/.tern-project vim ``` The plugins install can take some times, especially since there's a compilation made by YouCompleteMe. If you've the feeling the install has frozen, you can finish the install after by entering the command `:PlugInstall`. ## Hardcore mode The hardcore mode remap some keys to force you use Vim in a productive way: - no arrow keys for moving instead use the common Vim movement commands. - in insert mode, use `jk` to switch back to normal mode instead of `` Restricting commands is the best way to make your fingers learn. After one or two days, you should be more productive and have learned lots of Vim commands. You can disable the hardcore mode by setting the value of `g:hardcoreMode` to `0` in `.vimrc`. You can also change the mappings. ## Usage ### Vim WebVim is only a Vim distribution with plugins and configuration, so all common Vim commands and basic mapping are available. You must know how to use Vim before using this IDE. If you're not comfortable with Vim enough I suggest you to take the interactive Vim tutorial (run `vimtutor` in a terminal), and keep a [common usage cheat sheet](http://fprintf.net/vimCheatSheet.html) close to you until your fingers get all the mappings in memory. ### WebVim | | Command | Mode | Context | |--------------------------------------------------|-----------------------|:----:|------------------| | __Plugins__ | | Install Plugins | `:PlugInstall` | n | | | Update Plugins | `:PlugUpdate` | n | | | | | __Config__ | | Edit .vimrc | `ev` | n | | | Reload .vimrc | `sv` | n | | | | | __File Tree (NERDTree)__ | | Toggle Tree | `` | n | | | Open a node in a new tab | `t` | | Tree Node | | Change Root | `C` | | Tree Node | | Tree menu | `m` | | Tree Node | | Add a file | `a` | | Tree Menu | | Delete a file | `d` | | Tree Menu | | Move a file | `m` | | Tree Menu | | Copy a file | `c` | | Tree Menu | | Search in files (grep) | `g` | | Tree Menu | | Next match in grep | `:cn` | | Grep > Quickfix | | Move to left tab | `` | n | | | Move to right tab | `` | n | | | Change window (ie. tree to tab) | `` | | | | Help | `?` | | Tree | | Documentation | `:help NERDTree` | | | | | | __Comment__ | | Toggle comments | `` | nv | | | Comments | `cc` | nv | | | Sexy Comments | `cs` | nv | | | UnComments | `cu` | nv | | | Yank and Comments | `cy` | nv | | | Documentation | `:help NERDCommenter` | | | | | | __Align__ | | Start interactive alignment | `EasyAlign` | v | selection | | Align next paragraph on = | `a=` | n | | | Align next paragraph on : | `a:` | n | | | Align next paragraph on delimiter _x_ | `ax` | n | | | Right align selection on = | `a=` | v | | | Right align selection on : | `a:` | v | | | Right align selection on _x_ | `ax` | v | | | Documentation | `:help :EasyAlign` | | | | | | __Format__ | | Format the file | `` | n | js,json,html,css | | Format the selection | `` | n | js,json,html,css | | | | __Multiple Cursor__ | | Start multiple cursor | `` | v | Visual Block | | Multiple cursor insert | `i` | | multiple cursor | | Multiple cursor remove | `x` | | multiple cursor | | Leave multiple cursor | `` | | multiple cursor | | | | __Paste__ | | cycle backward through your history of yanks | `p` | nv | after paste `p` | | cycle forward through your history of yanks | `P` | nv | after paste `p` | | | | __AutoCompletion__ | | Select next proposal in menu | `` | i | complete menu | | Select previous proposal in menu | `` | i | complete menu | | | | __Syntax checking__ | | Checkers infos | `:SyntasticInfo` | n | | | Check | `:SyntasticCheck` | n | | | Toggle check | `:SyntasticToggleMode`| n | | | Error window | `:Errors` | n | | | Jump next error | `:lnext` | n | | | Jump previous error | `:lprev` | n | | | | | __JavaScript__ | | Get type | `gt` | n | under cursor | | Get documentation | `gd` | n | under cursor | | Go to | `go` | n | under cursor | | Jump to definition | `gf` | n | under cursor | | Go to references | `gr` | n | under cursor | | Rename | `r` | n | under cursor | | Jump to the source of a `require` | `gf` | n | node.js, cursor | | Edit the main file of a CJS module | `:Nedit module` | n | node.js | | Edit a file of a CJS module | `:Nedit module/foo.js`| n | node.js | | Edit projects main (from package.json) | `:Nedit` | n | node.js | | | | __Git__ | | git diff | `:Gdiff` | n | | | git status | `:Gstatus` | n | | | git commit | `:Gcommit` | n | | | git blame | `:Gblame` | n | | | git mv | `:Gmove` | n | | | git rm | `:Gremove` | n | | | Open the current file in Github | `:Gbrowse` | n | | | | | __Spell Check__ | | Enable checking | `set spell` | n | | | move to the next misspelled word | `]s` | n | | | move to the previous misspelled word | `[s` | n | | | add a word to the dictionary | `zg` | n | | | undo the addition of a word to the dictionary | `zug` | n | | | view spelling suggestions for a misspelled word | `z=` | n | | | | | __Search__ | | clear highlights | `` | n | | | | | __Editing__ | | Move line up | `-` | nv | | | Move line down | `_` | nv | | | Wrap in single quote | `'` | nv | | | Wrap in double quote | `"` | nv | | | | | __Emmet__ | | Expand abbreviation | `,` | i | html,css,scss | | | | _Next sections to come soon_ | | | _Modes_ : - `n` normal - `i` insert - `v` visual _Commands_ : - `:command` a Vim command - `:set something` can also be replaced by `:setlocal something` to apply it to the current buffer only - `a` or `a` a keyboard command - `` means `CTRL and `/` (this is the Vim notation) - `` means `Shift` and `left arrow` - `b` means `CTRL` and `a`, then `b` - `` is mapped to `,` - `` is mapped to `\` ## Plugins WebVim is only a distribution that contains plugins. The plugin authors have made the hard work. _Plugin authors rocks!_ ### Plugin - [vim-plug](https://github.com/junegunn/vim-plug) Minimalist Vim Plugin Manager ### User interface - [Mango](https://github.com/goatslacker/mango.vim) A nice color scheme - [VimAirline](https://github.com/bling/vim-airline) Lean and mean statusbars ### Manage your project - [NERDTree](https://github.com/scrooloose/nerdtree) Manage your project files - [VimFugitive](https://github.com/tpope/vim-fugitive) Git integration - [VimGitGutter](https://github.com/airblade/vim-gitgutter) Git diff in the gutter - [EditorconfigVim](https://github.com/editorconfig/editorconfig-vim) Shared coding conventions ### Code writing - [NERDCommenter](https://github.com/scrooloose/nerdcommenter) Comments made easy - [VimTrailingWhitespace](https://github.com/bronson/vim-trailing-whitespace) Highlight trailing spaces - [Syntastic](https://github.com/scrooloose/syntastic) Syntax check and validation - [VimEasyAlign](https://github.com/junegunn/vim-easy-align) Realign pieces of code - [VimMultipleCursors](https://github.com/terryma/vim-multiple-cursors) Write on multiple lines easily - [VimJsBeautify](https://github.com/maksimr/vim-jsbeautify) Reformat JavaScript, HTML and JSON files - [VimYankStack](https://github.com/maxbrunsfeld/vim-yankstack) Iterate over yanked stack on paste - [VimSurround](https://github.com/tpope/vim-surround) Quoting and parenthesizing - [YouCompleteMe](https://github.com/Valloric/YouCompleteMe) Autocompletion engine - [VimNode](https://github.com/moll/vim-node) Navigate through node.js code/modules - [VimLint](https://github.com/syngan/vim-vimlint) Linter used by syntastic for VimL - [VimLParser](https://github.com/ynkdir/vim-vimlparser) VimL parser (required by VimLint) - [Emmet-vim](https://github.com/mattn/emmet-vim) Expanding abbreviations similar to [emmet](http://emmet.io/) ### Code reading - [VimJson](https://github.com/elzr/vim-json) JSON highlighting and quote concealing - [YaJS](https://github.com/othree/yajs.vim) JavaScript syntax (ES5 and ES6) - [JavaScriptLibrariesSyntax](https://github.com/othree/javascript-libraries-syntax.vim) Syntax highlighting for well-known JS libraries - [VimCSS3](https://github.com/hail2u/vim-css3-syntax) CSS3 syntax - [ScssSyntax](https://github.com/cakebaker/scss-syntax.vim) SCSS syntax - [HTML5](https://github.com/othree/html5.vim) HTML5 syntax ## History - __1.3.0__ Fixed dependencies, tern via YCM, Emmet, new theme, nerdtree grep, use local linters - __1.2.0__ Fix #28, support new esint config files, update installe - __1.1.0__ Add user config, autocmd file, fix easyalign mapping, update Nerdtree config, better mouse support in insert mode - __1.0.0__ Becomes `webvim` with an install process, a better configuration system, better plugins neighborhood - __0.1.0__ A basic `dotvim` repository with my own Vim configuration ## Contributing Every contribution is more than welcomed. You can: - [report issues](https://github.com/krampstudio/webvim/issues) - Fix, improve the configuration, add new features. The best is to fork and submit a pull request - Test and adapt to other OS - Fix my English mistakes - Update the documentation - Create a better logo - [Offer me a coffee](https://liberapay.com/krampstudio/donate) [![Donate using Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/krampstudio/donate) ## License The content of this repository is licensed under the [GPLv3](http://www.gnu.org/licenses/gpl-3.0.txt) ================================================ FILE: autoload/plug.vim ================================================ " vim-plug: Vim plugin manager " ============================ " " Download plug.vim and put it in ~/.vim/autoload " " curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ " https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim " " Edit your .vimrc " " call plug#begin('~/.vim/plugged') " " " Make sure you use single quotes " " " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align " Plug 'junegunn/vim-easy-align' " " " Any valid git URL is allowed " Plug 'https://github.com/junegunn/vim-github-dashboard.git' " " " Group dependencies, vim-snippets depends on ultisnips " Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets' " " " On-demand loading " Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' } " Plug 'tpope/vim-fireplace', { 'for': 'clojure' } " " " Using a non-master branch " Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' } " " " Using a tagged release; wildcard allowed (requires git 1.9.2 or above) " Plug 'fatih/vim-go', { 'tag': '*' } " " " Plugin options " Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' } " " " Plugin outside ~/.vim/plugged with post-update hook " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' } " " " Unmanaged plugin (manually installed and updated) " Plug '~/my-prototype-plugin' " " " Add plugins to &runtimepath " call plug#end() " " Then reload .vimrc and :PlugInstall to install plugins. " " Plug options: " "| Option | Description | "| ----------------------- | ------------------------------------------------ | "| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use | "| `rtp` | Subdirectory that contains Vim plugin | "| `dir` | Custom directory for the plugin | "| `as` | Use different name for the plugin | "| `do` | Post-update hook (string or funcref) | "| `on` | On-demand loading: Commands or ``-mappings | "| `for` | On-demand loading: File types | "| `frozen` | Do not update unless explicitly specified | " " More information: https://github.com/junegunn/vim-plug " " " Copyright (c) 2016 Junegunn Choi " " MIT License " " Permission is hereby granted, free of charge, to any person obtaining " a copy of this software and associated documentation files (the " "Software"), to deal in the Software without restriction, including " without limitation the rights to use, copy, modify, merge, publish, " distribute, sublicense, and/or sell copies of the Software, and to " permit persons to whom the Software is furnished to do so, subject to " the following conditions: " " The above copyright notice and this permission notice shall be " included in all copies or substantial portions of the Software. " " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. if exists('g:loaded_plug') finish endif let g:loaded_plug = 1 let s:cpo_save = &cpo set cpo&vim let s:plug_src = 'https://github.com/junegunn/vim-plug.git' let s:plug_tab = get(s:, 'plug_tab', -1) let s:plug_buf = get(s:, 'plug_buf', -1) let s:mac_gui = has('gui_macvim') && has('gui_running') let s:is_win = has('win32') || has('win64') let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win let s:me = resolve(expand(':p')) let s:base_spec = { 'branch': 'master', 'frozen': 0 } let s:TYPE = { \ 'string': type(''), \ 'list': type([]), \ 'dict': type({}), \ 'funcref': type(function('call')) \ } let s:loaded = get(s:, 'loaded', {}) let s:triggers = get(s:, 'triggers', {}) function! plug#begin(...) if a:0 > 0 let s:plug_home_org = a:1 let home = s:path(fnamemodify(expand(a:1), ':p')) elseif exists('g:plug_home') let home = s:path(g:plug_home) elseif !empty(&rtp) let home = s:path(split(&rtp, ',')[0]) . '/plugged' else return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.') endif let g:plug_home = home let g:plugs = {} let g:plugs_order = [] let s:triggers = {} call s:define_commands() return 1 endfunction function! s:define_commands() command! -nargs=+ -bar Plug call plug#() if !executable('git') return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.') endif command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(0, []) command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(0, []) command! -nargs=0 -bar -bang PlugClean call s:clean(0) command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif command! -nargs=0 -bar PlugStatus call s:status() command! -nargs=0 -bar PlugDiff call s:diff() command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(0, ) endfunction function! s:to_a(v) return type(a:v) == s:TYPE.list ? a:v : [a:v] endfunction function! s:to_s(v) return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n" endfunction function! s:glob(from, pattern) return s:lines(globpath(a:from, a:pattern)) endfunction function! s:source(from, ...) let found = 0 for pattern in a:000 for vim in s:glob(a:from, pattern) execute 'source' s:esc(vim) let found = 1 endfor endfor return found endfunction function! s:assoc(dict, key, val) let a:dict[a:key] = add(get(a:dict, a:key, []), a:val) endfunction function! s:ask(message, ...) call inputsave() echohl WarningMsg let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) ')) echohl None call inputrestore() echo "\r" return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0 endfunction function! s:ask_no_interrupt(...) try return call('s:ask', a:000) catch return 0 endtry endfunction function! plug#end() if !exists('g:plugs') return s:err('Call plug#begin() first') endif if exists('#PlugLOD') augroup PlugLOD autocmd! augroup END augroup! PlugLOD endif let lod = { 'ft': {}, 'map': {}, 'cmd': {} } filetype off for name in g:plugs_order if !has_key(g:plugs, name) continue endif let plug = g:plugs[name] if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for') let s:loaded[name] = 1 continue endif if has_key(plug, 'on') let s:triggers[name] = { 'map': [], 'cmd': [] } for cmd in s:to_a(plug.on) if cmd =~? '^.\+' if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i')) call s:assoc(lod.map, cmd, name) endif call add(s:triggers[name].map, cmd) elseif cmd =~# '^[A-Z]' if exists(':'.cmd) != 2 call s:assoc(lod.cmd, cmd, name) endif call add(s:triggers[name].cmd, cmd) else call s:err('Invalid `on` option: '.cmd. \ '. Should start with an uppercase letter or ``.') endif endfor endif if has_key(plug, 'for') let types = s:to_a(plug.for) if !empty(types) augroup filetypedetect call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim') augroup END endif for type in types call s:assoc(lod.ft, type, name) endfor endif endfor for [cmd, names] in items(lod.cmd) execute printf( \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "", , , , %s)', \ cmd, string(cmd), string(names)) endfor for [map, names] in items(lod.map) for [mode, map_prefix, key_prefix] in \ [['i', '', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']] execute printf( \ '%snoremap %s %s:call lod_map(%s, %s, "%s")', \ mode, map, map_prefix, string(map), string(names), key_prefix) endfor endfor for [ft, names] in items(lod.ft) augroup PlugLOD execute printf('autocmd FileType %s call lod_ft(%s, %s)', \ ft, string(ft), string(names)) augroup END endfor call s:reorg_rtp() filetype plugin indent on if has('vim_starting') if has('syntax') && !exists('g:syntax_on') syntax enable end else call s:reload_plugins() endif endfunction function! s:loaded_names() return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)') endfunction function! s:load_plugin(spec) call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim') endfunction function! s:reload_plugins() for name in s:loaded_names() call s:load_plugin(g:plugs[name]) endfor endfunction function! s:trim(str) return substitute(a:str, '[\/]\+$', '', '') endfunction function! s:version_requirement(val, min) for idx in range(0, len(a:min) - 1) let v = get(a:val, idx, 0) if v < a:min[idx] | return 0 elseif v > a:min[idx] | return 1 endif endfor return 1 endfunction function! s:git_version_requirement(...) if !exists('s:git_version') let s:git_version = map(split(split(s:system('git --version'))[-1], '\.'), 'str2nr(v:val)') endif return s:version_requirement(s:git_version, a:000) endfunction function! s:progress_opt(base) return a:base && !s:is_win && \ s:git_version_requirement(1, 7, 1) ? '--progress' : '' endfunction if s:is_win function! s:rtp(spec) return s:path(a:spec.dir . get(a:spec, 'rtp', '')) endfunction function! s:path(path) return s:trim(substitute(a:path, '/', '\', 'g')) endfunction function! s:dirpath(path) return s:path(a:path) . '\' endfunction function! s:is_local_plug(repo) return a:repo =~? '^[a-z]:\|^[%~]' endfunction else function! s:rtp(spec) return s:dirpath(a:spec.dir . get(a:spec, 'rtp', '')) endfunction function! s:path(path) return s:trim(a:path) endfunction function! s:dirpath(path) return substitute(a:path, '[/\\]*$', '/', '') endfunction function! s:is_local_plug(repo) return a:repo[0] =~ '[/$~]' endfunction endif function! s:err(msg) echohl ErrorMsg echom '[vim-plug] '.a:msg echohl None endfunction function! s:warn(cmd, msg) echohl WarningMsg execute a:cmd 'a:msg' echohl None endfunction function! s:esc(path) return escape(a:path, ' ') endfunction function! s:escrtp(path) return escape(a:path, ' ,') endfunction function! s:remove_rtp() for name in s:loaded_names() let rtp = s:rtp(g:plugs[name]) execute 'set rtp-='.s:escrtp(rtp) let after = globpath(rtp, 'after') if isdirectory(after) execute 'set rtp-='.s:escrtp(after) endif endfor endfunction function! s:reorg_rtp() if !empty(s:first_rtp) execute 'set rtp-='.s:first_rtp execute 'set rtp-='.s:last_rtp endif " &rtp is modified from outside if exists('s:prtp') && s:prtp !=# &rtp call s:remove_rtp() unlet! s:middle endif let s:middle = get(s:, 'middle', &rtp) let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])') let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)') let rtp = join(map(rtps, 'escape(v:val, ",")'), ',') \ . ','.s:middle.',' \ . join(map(afters, 'escape(v:val, ",")'), ',') let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g') let s:prtp = &rtp if !empty(s:first_rtp) execute 'set rtp^='.s:first_rtp execute 'set rtp+='.s:last_rtp endif endfunction function! s:doautocmd(...) if exists('#'.join(a:000, '#')) execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) endif endfunction function! s:dobufread(names) for name in a:names let path = s:rtp(g:plugs[name]).'/**' for dir in ['ftdetect', 'ftplugin'] if len(finddir(dir, path)) return s:doautocmd('BufRead') endif endfor endfor endfunction function! plug#load(...) if a:0 == 0 return s:err('Argument missing: plugin name(s) required') endif if !exists('g:plugs') return s:err('plug#begin was not called') endif let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)') if !empty(unknowns) let s = len(unknowns) > 1 ? 's' : '' return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', '))) end for name in a:000 call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) endfor call s:dobufread(a:000) return 1 endfunction function! s:remove_triggers(name) if !has_key(s:triggers, a:name) return endif for cmd in s:triggers[a:name].cmd execute 'silent! delc' cmd endfor for map in s:triggers[a:name].map execute 'silent! unmap' map execute 'silent! iunmap' map endfor call remove(s:triggers, a:name) endfunction function! s:lod(names, types, ...) for name in a:names call s:remove_triggers(name) let s:loaded[name] = 1 endfor call s:reorg_rtp() for name in a:names let rtp = s:rtp(g:plugs[name]) for dir in a:types call s:source(rtp, dir.'/**/*.vim') endfor if a:0 if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2)) execute 'runtime' a:1 endif call s:source(rtp, a:2) endif call s:doautocmd('User', name) endfor endfunction function! s:lod_ft(pat, names) let syn = 'syntax/'.a:pat.'.vim' call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn) execute 'autocmd! PlugLOD FileType' a:pat call s:doautocmd('filetypeplugin', 'FileType') call s:doautocmd('filetypeindent', 'FileType') endfunction function! s:lod_cmd(cmd, bang, l1, l2, args, names) call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) call s:dobufread(a:names) execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) endfunction function! s:lod_map(map, names, prefix) call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) call s:dobufread(a:names) let extra = '' while 1 let c = getchar(0) if c == 0 break endif let extra .= nr2char(c) endwhile if v:count call feedkeys(v:count, 'n') endif call feedkeys('"'.v:register, 'n') if mode(1) == 'no' call feedkeys(v:operator) endif call feedkeys(a:prefix . substitute(a:map, '^', "\", '') . extra) endfunction function! plug#(repo, ...) if a:0 > 1 return s:err('Invalid number of arguments (1..2)') endif try let repo = s:trim(a:repo) let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec let name = get(opts, 'as', fnamemodify(repo, ':t:s?\.git$??')) let spec = extend(s:infer_properties(name, repo), opts) if !has_key(g:plugs, name) call add(g:plugs_order, name) endif let g:plugs[name] = spec let s:loaded[name] = get(s:loaded, name, 0) catch return s:err(v:exception) endtry endfunction function! s:parse_options(arg) let opts = copy(s:base_spec) let type = type(a:arg) if type == s:TYPE.string let opts.tag = a:arg elseif type == s:TYPE.dict call extend(opts, a:arg) if has_key(opts, 'dir') let opts.dir = s:dirpath(expand(opts.dir)) endif else throw 'Invalid argument type (expected: string or dictionary)' endif return opts endfunction function! s:infer_properties(name, repo) let repo = a:repo if s:is_local_plug(repo) return { 'dir': s:dirpath(expand(repo)) } else if repo =~ ':' let uri = repo else if repo !~ '/' let repo = 'vim-scripts/'. repo endif let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git') let uri = printf(fmt, repo) endif let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') ) return { 'dir': dir, 'uri': uri } endif endfunction function! s:install(force, names) call s:update_impl(0, a:force, a:names) endfunction function! s:update(force, names) call s:update_impl(1, a:force, a:names) endfunction function! plug#helptags() if !exists('g:plugs') return s:err('plug#begin was not called') endif for spec in values(g:plugs) let docd = join([spec.dir, 'doc'], '/') if isdirectory(docd) silent! execute 'helptags' s:esc(docd) endif endfor return 1 endfunction function! s:syntax() syntax clear syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX syn match plugNumber /[0-9]\+[0-9.]*/ contained syn match plugBracket /[[\]]/ contained syn match plugX /x/ contained syn match plugDash /^-/ syn match plugPlus /^+/ syn match plugStar /^*/ syn match plugMessage /\(^- \)\@<=.*/ syn match plugName /\(^- \)\@<=[^ ]*:/ syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/ syn match plugTag /(tag: [^)]\+)/ syn match plugInstall /\(^+ \)\@<=[^:]*/ syn match plugUpdate /\(^* \)\@<=[^:]*/ syn match plugCommit /^ \X*[0-9a-f]\{7} .*/ contains=plugRelDate,plugEdge,plugTag syn match plugEdge /^ \X\+$/ syn match plugEdge /^ \X*/ contained nextgroup=plugSha syn match plugSha /[0-9a-f]\{7}/ contained syn match plugRelDate /([^)]*)$/ contained syn match plugNotLoaded /(not loaded)$/ syn match plugError /^x.*/ syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/ syn match plugH2 /^.*:\n-\+$/ syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean hi def link plug1 Title hi def link plug2 Repeat hi def link plugH2 Type hi def link plugX Exception hi def link plugBracket Structure hi def link plugNumber Number hi def link plugDash Special hi def link plugPlus Constant hi def link plugStar Boolean hi def link plugMessage Function hi def link plugName Label hi def link plugInstall Function hi def link plugUpdate Type hi def link plugError Error hi def link plugDeleted Ignore hi def link plugRelDate Comment hi def link plugEdge PreProc hi def link plugSha Identifier hi def link plugTag Constant hi def link plugNotLoaded Comment endfunction function! s:lpad(str, len) return a:str . repeat(' ', a:len - len(a:str)) endfunction function! s:lines(msg) return split(a:msg, "[\r\n]") endfunction function! s:lastline(msg) return get(s:lines(a:msg), -1, '') endfunction function! s:new_window() execute get(g:, 'plug_window', 'vertical topleft new') endfunction function! s:plug_window_exists() let buflist = tabpagebuflist(s:plug_tab) return !empty(buflist) && index(buflist, s:plug_buf) >= 0 endfunction function! s:switch_in() if !s:plug_window_exists() return 0 endif if winbufnr(0) != s:plug_buf let s:pos = [tabpagenr(), winnr(), winsaveview()] execute 'normal!' s:plug_tab.'gt' let winnr = bufwinnr(s:plug_buf) execute winnr.'wincmd w' call add(s:pos, winsaveview()) else let s:pos = [winsaveview()] endif setlocal modifiable return 1 endfunction function! s:switch_out(...) call winrestview(s:pos[-1]) setlocal nomodifiable if a:0 > 0 execute a:1 endif if len(s:pos) > 1 execute 'normal!' s:pos[0].'gt' execute s:pos[1] 'wincmd w' call winrestview(s:pos[2]) endif endfunction function! s:finish_bindings() nnoremap R :call retry() nnoremap D :PlugDiff nnoremap S :PlugStatus nnoremap U :call status_update() xnoremap U :call status_update() nnoremap ]] :silent! call section('') nnoremap [[ :silent! call section('b') endfunction function! s:prepare(...) if empty(getcwd()) throw 'Invalid current working directory. Cannot proceed.' endif for evar in ['$GIT_DIR', '$GIT_WORK_TREE'] if exists(evar) throw evar.' detected. Cannot proceed.' endif endfor call s:job_abort() if s:switch_in() normal q endif call s:new_window() nnoremap q :if b:plug_preview==1pcendifbd if a:0 == 0 call s:finish_bindings() endif let b:plug_preview = -1 let s:plug_tab = tabpagenr() let s:plug_buf = winbufnr(0) call s:assign_name() for k in ['', 'L', 'o', 'X', 'd', 'dd'] execute 'silent! unmap ' k endfor setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable setf vim-plug if exists('g:syntax_on') call s:syntax() endif endfunction function! s:assign_name() " Assign buffer name let prefix = '[Plugins]' let name = prefix let idx = 2 while bufexists(name) let name = printf('%s (%s)', prefix, idx) let idx = idx + 1 endwhile silent! execute 'f' fnameescape(name) endfunction function! s:chsh(swap) let prev = [&shell, &shellredir] if !s:is_win && a:swap set shell=sh shellredir=>%s\ 2>&1 endif return prev endfunction function! s:bang(cmd, ...) try let [sh, shrd] = s:chsh(a:0) " FIXME: Escaping is incomplete. We could use shellescape with eval, " but it won't work on Windows. let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd let g:_plug_bang = '!'.escape(cmd, '#!%') execute "normal! :execute g:_plug_bang\\" finally unlet g:_plug_bang let [&shell, &shellredir] = [sh, shrd] endtry return v:shell_error ? 'Exit status: ' . v:shell_error : '' endfunction function! s:regress_bar() let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '') call s:progress_bar(2, bar, len(bar)) endfunction function! s:is_updated(dir) return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir)) endfunction function! s:do(pull, force, todo) for [name, spec] in items(a:todo) if !isdirectory(spec.dir) continue endif let installed = has_key(s:update.new, name) let updated = installed ? 0 : \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir)) if a:force || installed || updated execute 'cd' s:esc(spec.dir) call append(3, '- Post-update hook for '. name .' ... ') let error = '' let type = type(spec.do) if type == s:TYPE.string if spec.do[0] == ':' call s:load_plugin(spec) execute spec.do[1:] else let error = s:bang(spec.do) endif elseif type == s:TYPE.funcref try let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged') call spec.do({ 'name': name, 'status': status, 'force': a:force }) catch let error = v:exception endtry else let error = 'Invalid hook type' endif call s:switch_in() call setline(4, empty(error) ? (getline(4) . 'OK') \ : ('x' . getline(4)[1:] . error)) if !empty(error) call add(s:update.errors, name) call s:regress_bar() endif cd - endif endfor endfunction function! s:hash_match(a, b) return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0 endfunction function! s:checkout(spec) let sha = a:spec.commit let output = s:system('git rev-parse HEAD', a:spec.dir) if !v:shell_error && !s:hash_match(sha, s:lines(output)[0]) let output = s:system( \ 'git fetch --depth 999999 && git checkout '.s:esc(sha), a:spec.dir) endif return output endfunction function! s:finish(pull) let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen')) if new_frozen let s = new_frozen > 1 ? 's' : '' call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s)) endif call append(3, '- Finishing ... ') | 4 redraw call plug#helptags() call plug#end() call setline(4, getline(4) . 'Done!') redraw let msgs = [] if !empty(s:update.errors) call add(msgs, "Press 'R' to retry.") endif if a:pull && len(s:update.new) < len(filter(getline(5, '$'), \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0")) call add(msgs, "Press 'D' to see the updated changes.") endif echo join(msgs, ' ') call s:finish_bindings() endfunction function! s:retry() if empty(s:update.errors) return endif echo call s:update_impl(s:update.pull, s:update.force, \ extend(copy(s:update.errors), [s:update.threads])) endfunction function! s:is_managed(name) return has_key(g:plugs[a:name], 'uri') endfunction function! s:names(...) return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')) endfunction function! s:check_ruby() silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'") if !exists('g:plug_ruby') redraw! return s:warn('echom', 'Warning: Ruby interface is broken') endif let ruby_version = split(g:plug_ruby, '\.') unlet g:plug_ruby return s:version_requirement(ruby_version, [1, 8, 7]) endfunction function! s:update_impl(pull, force, args) abort let args = copy(a:args) let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ? \ remove(args, -1) : get(g:, 'plug_threads', 16) let managed = filter(copy(g:plugs), 's:is_managed(v:key)') let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') : \ filter(managed, 'index(args, v:key) >= 0') if empty(todo) return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install')) endif if !s:is_win && s:git_version_requirement(2, 3) let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : '' let $GIT_TERMINAL_PROMPT = 0 for plug in values(todo) let plug.uri = substitute(plug.uri, \ '^https://git::@github\.com', 'https://github.com', '') endfor endif if !isdirectory(g:plug_home) try call mkdir(g:plug_home, 'p') catch return s:err(printf('Invalid plug directory: %s. '. \ 'Try to call plug#begin with a valid directory', g:plug_home)) endtry endif if has('nvim') && !exists('*jobwait') && threads > 1 call s:warn('echom', '[vim-plug] Update Neovim for parallel installer') endif let python = (has('python') || has('python3')) && (!s:nvim || has('vim_starting')) let ruby = has('ruby') && !s:nvim && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && s:check_ruby() let s:update = { \ 'start': reltime(), \ 'all': todo, \ 'todo': copy(todo), \ 'errors': [], \ 'pull': a:pull, \ 'force': a:force, \ 'new': {}, \ 'threads': (python || ruby || s:nvim) ? min([len(todo), threads]) : 1, \ 'bar': '', \ 'fin': 0 \ } call s:prepare(1) call append(0, ['', '']) normal! 2G silent! redraw let s:clone_opt = get(g:, 'plug_shallow', 1) ? \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : '' " Python version requirement (>= 2.7) if python && !has('python3') && !ruby && !s:nvim && s:update.threads > 1 redir => pyv silent python import platform; print platform.python_version() redir END let python = s:version_requirement( \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6]) endif if (python || ruby) && s:update.threads > 1 try let imd = &imd if s:mac_gui set noimd endif if ruby call s:update_ruby() else call s:update_python() endif catch let lines = getline(4, '$') let printed = {} silent! 4,$d _ for line in lines let name = s:extract_name(line, '.', '') if empty(name) || !has_key(printed, name) call append('$', line) if !empty(name) let printed[name] = 1 if line[0] == 'x' && index(s:update.errors, name) < 0 call add(s:update.errors, name) end endif endif endfor finally let &imd = imd call s:update_finish() endtry else call s:update_vim() endif endfunction function! s:log4(name, msg) call setline(4, printf('- %s (%s)', a:msg, a:name)) redraw endfunction function! s:update_finish() if exists('s:git_terminal_prompt') let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt endif if s:switch_in() call append(3, '- Updating ...') | 4 for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))')) let pos = s:logpos(name) if !pos continue endif if has_key(spec, 'commit') call s:log4(name, 'Checking out '.spec.commit) let out = s:checkout(spec) elseif has_key(spec, 'tag') let tag = spec.tag if tag =~ '\*' let tags = s:lines(s:system('git tag --list '.string(tag).' --sort -version:refname 2>&1', spec.dir)) if !v:shell_error && !empty(tags) let tag = tags[0] call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag)) call append(3, '') endif endif call s:log4(name, 'Checking out '.tag) let out = s:system('git checkout -q '.s:esc(tag).' 2>&1', spec.dir) else let branch = s:esc(get(spec, 'branch', 'master')) call s:log4(name, 'Merging origin/'.branch) let out = s:system('git checkout -q '.branch.' 2>&1' \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir) endif if !v:shell_error && filereadable(spec.dir.'/.gitmodules') && \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir)) call s:log4(name, 'Updating submodules. This may take a while.') let out .= s:bang('git submodule update --init --recursive 2>&1', spec.dir) endif let msg = printf('%s %s: %s', v:shell_error ? 'x': '-', name, s:lastline(out)) if v:shell_error call add(s:update.errors, name) call s:regress_bar() silent execute pos 'd _' call append(4, msg) | 4 elseif !empty(out) call setline(pos, msg) endif redraw endfor silent 4 d _ call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) call s:finish(s:update.pull) call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.') call s:switch_out('normal! gg') endif endfunction function! s:job_abort() if !s:nvim || !exists('s:jobs') return endif for [name, j] in items(s:jobs) silent! call jobstop(j.jobid) if j.new call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir)) endif endfor let s:jobs = {} endfunction " When a:event == 'stdout', data = list of strings " When a:event == 'exit', data = returncode function! s:job_handler(job_id, data, event) abort if !s:plug_window_exists() " plug window closed return s:job_abort() endif if a:event == 'stdout' let complete = empty(a:data[-1]) let lines = map(filter(a:data, 'len(v:val) > 0'), 'split(v:val, "[\r\n]")[-1]') call extend(self.lines, lines) let self.result = join(self.lines, "\n") if !complete call remove(self.lines, -1) endif " To reduce the number of buffer updates let self.tick = get(self, 'tick', -1) + 1 if self.tick % len(s:jobs) == 0 call s:log(self.new ? '+' : '*', self.name, self.result) endif elseif a:event == 'exit' let self.running = 0 if a:data != 0 let self.error = 1 endif call s:reap(self.name) call s:tick() endif endfunction function! s:spawn(name, cmd, opts) let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [], 'result': '', \ 'new': get(a:opts, 'new', 0), \ 'on_stdout': function('s:job_handler'), \ 'on_exit' : function('s:job_handler'), \ } let s:jobs[a:name] = job if s:nvim let argv = [ 'sh', '-c', \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) ] let jid = jobstart(argv, job) if jid > 0 let job.jobid = jid else let job.running = 0 let job.error = 1 let job.result = jid < 0 ? 'sh is not executable' : \ 'Invalid arguments (or job table is full)' endif else let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd] let job.result = call('s:system', params) let job.error = v:shell_error != 0 let job.running = 0 endif endfunction function! s:reap(name) let job = s:jobs[a:name] if job.error call add(s:update.errors, a:name) elseif get(job, 'new', 0) let s:update.new[a:name] = 1 endif let s:update.bar .= job.error ? 'x' : '=' call s:log(job.error ? 'x' : '-', a:name, empty(job.result) ? 'OK' : job.result) call s:bar() call remove(s:jobs, a:name) endfunction function! s:bar() if s:switch_in() let total = len(s:update.all) call setline(1, (s:update.pull ? 'Updating' : 'Installing'). \ ' plugins ('.len(s:update.bar).'/'.total.')') call s:progress_bar(2, s:update.bar, total) call s:switch_out() endif endfunction function! s:logpos(name) for i in range(4, line('$')) if getline(i) =~# '^[-+x*] '.a:name.':' return i endif endfor endfunction function! s:log(bullet, name, lines) if s:switch_in() let pos = s:logpos(a:name) if pos > 0 silent execute pos 'd _' if pos > winheight('.') let pos = 4 endif else let pos = 4 endif call append(pos - 1, s:format_message(a:bullet, a:name, a:lines)) call s:switch_out() endif endfunction function! s:update_vim() let s:jobs = {} call s:bar() call s:tick() endfunction function! s:tick() let pull = s:update.pull let prog = s:progress_opt(s:nvim) while 1 " Without TCO, Vim stack is bound to explode if empty(s:update.todo) if empty(s:jobs) && !s:update.fin let s:update.fin = 1 call s:update_finish() endif return endif let name = keys(s:update.todo)[0] let spec = remove(s:update.todo, name) let new = !isdirectory(spec.dir) call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...') redraw let has_tag = has_key(spec, 'tag') if !new let [error, _] = s:git_validate(spec, 0) if empty(error) if pull let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : '' call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir }) else let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 } endif else let s:jobs[name] = { 'running': 0, 'result': error, 'error': 1 } endif else call s:spawn(name, \ printf('git clone %s %s %s %s 2>&1', \ has_tag ? '' : s:clone_opt, \ prog, \ s:shellesc(spec.uri), \ s:shellesc(s:trim(spec.dir))), { 'new': 1 }) endif if !s:jobs[name].running call s:reap(name) endif if len(s:jobs) >= s:update.threads break endif endwhile endfunction function! s:update_python() let py_exe = has('python') ? 'python' : 'python3' execute py_exe "<< EOF" import datetime import functools import os try: import queue except ImportError: import Queue as queue import random import re import shutil import signal import subprocess import tempfile import threading as thr import time import traceback import vim G_NVIM = vim.eval("has('nvim')") == '1' G_PULL = vim.eval('s:update.pull') == '1' G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1 G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)')) G_CLONE_OPT = vim.eval('s:clone_opt') G_PROGRESS = vim.eval('s:progress_opt(1)') G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads')) G_STOP = thr.Event() G_IS_WIN = vim.eval('s:is_win') == '1' class PlugError(Exception): def __init__(self, msg): self.msg = msg class CmdTimedOut(PlugError): pass class CmdFailed(PlugError): pass class InvalidURI(PlugError): pass class Action(object): INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-'] class Buffer(object): def __init__(self, lock, num_plugs, is_pull): self.bar = '' self.event = 'Updating' if is_pull else 'Installing' self.lock = lock self.maxy = int(vim.eval('winheight(".")')) self.num_plugs = num_plugs def __where(self, name): """ Find first line with name in current buffer. Return line num. """ found, lnum = False, 0 matcher = re.compile('^[-+x*] {0}:'.format(name)) for line in vim.current.buffer: if matcher.search(line) is not None: found = True break lnum += 1 if not found: lnum = -1 return lnum def header(self): curbuf = vim.current.buffer curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs) num_spaces = self.num_plugs - len(self.bar) curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ') with self.lock: vim.command('normal! 2G') vim.command('redraw') def write(self, action, name, lines): first, rest = lines[0], lines[1:] msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)] msg.extend([' ' + line for line in rest]) try: if action == Action.ERROR: self.bar += 'x' vim.command("call add(s:update.errors, '{0}')".format(name)) elif action == Action.DONE: self.bar += '=' curbuf = vim.current.buffer lnum = self.__where(name) if lnum != -1: # Found matching line num del curbuf[lnum] if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]): lnum = 3 else: lnum = 3 curbuf.append(msg, lnum) self.header() except vim.error: pass class Command(object): CD = 'cd /d' if G_IS_WIN else 'cd' def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None): self.cmd = cmd if cmd_dir: self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd) self.timeout = timeout self.callback = cb if cb else (lambda msg: None) self.clean = clean if clean else (lambda: None) self.proc = None @property def alive(self): """ Returns true only if command still running. """ return self.proc and self.proc.poll() is None def execute(self, ntries=3): """ Execute the command with ntries if CmdTimedOut. Returns the output of the command if no Exception. """ attempt, finished, limit = 0, False, self.timeout while not finished: try: attempt += 1 result = self.try_command() finished = True return result except CmdTimedOut: if attempt != ntries: self.notify_retry() self.timeout += limit else: raise def notify_retry(self): """ Retry required for command, notify user. """ for count in range(3, 0, -1): if G_STOP.is_set(): raise KeyboardInterrupt msg = 'Timeout. Will retry in {0} second{1} ...'.format( count, 's' if count != 1 else '') self.callback([msg]) time.sleep(1) self.callback(['Retrying ...']) def try_command(self): """ Execute a cmd & poll for callback. Returns list of output. Raises CmdFailed -> return code for Popen isn't 0 Raises CmdTimedOut -> command exceeded timeout without new output """ first_line = True try: tfile = tempfile.NamedTemporaryFile(mode='w+b') preexec_fn = not G_IS_WIN and os.setsid or None self.proc = subprocess.Popen(self.cmd, stdout=tfile, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, preexec_fn=preexec_fn) thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,)) thrd.start() thread_not_started = True while thread_not_started: try: thrd.join(0.1) thread_not_started = False except RuntimeError: pass while self.alive: if G_STOP.is_set(): raise KeyboardInterrupt if first_line or random.random() < G_LOG_PROB: first_line = False line = '' if G_IS_WIN else nonblock_read(tfile.name) if line: self.callback([line]) time_diff = time.time() - os.path.getmtime(tfile.name) if time_diff > self.timeout: raise CmdTimedOut(['Timeout!']) thrd.join(0.5) tfile.seek(0) result = [line.decode('utf-8', 'replace').rstrip() for line in tfile] if self.proc.returncode != 0: raise CmdFailed([''] + result) return result except: self.terminate() raise def terminate(self): """ Terminate process and cleanup. """ if self.alive: if G_IS_WIN: os.kill(self.proc.pid, signal.SIGINT) else: os.killpg(self.proc.pid, signal.SIGTERM) self.clean() class Plugin(object): def __init__(self, name, args, buf_q, lock): self.name = name self.args = args self.buf_q = buf_q self.lock = lock self.tag = args.get('tag', 0) def manage(self): try: if os.path.exists(self.args['dir']): self.update() else: self.install() with self.lock: thread_vim_command("let s:update.new['{0}'] = 1".format(self.name)) except PlugError as exc: self.write(Action.ERROR, self.name, exc.msg) except KeyboardInterrupt: G_STOP.set() self.write(Action.ERROR, self.name, ['Interrupted!']) except: # Any exception except those above print stack trace msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip()) self.write(Action.ERROR, self.name, msg.split('\n')) raise def install(self): target = self.args['dir'] if target[-1] == '\\': target = target[0:-1] def clean(target): def _clean(): try: shutil.rmtree(target) except OSError: pass return _clean self.write(Action.INSTALL, self.name, ['Installing ...']) callback = functools.partial(self.write, Action.INSTALL, self.name) cmd = 'git clone {0} {1} {2} {3} 2>&1'.format( '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'], esc(target)) com = Command(cmd, None, G_TIMEOUT, callback, clean(target)) result = com.execute(G_RETRIES) self.write(Action.DONE, self.name, result[-1:]) def repo_uri(self): cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url' command = Command(cmd, self.args['dir'], G_TIMEOUT,) result = command.execute(G_RETRIES) return result[-1] def update(self): match = re.compile(r'git::?@') actual_uri = re.sub(match, '', self.repo_uri()) expect_uri = re.sub(match, '', self.args['uri']) if actual_uri != expect_uri: msg = ['', 'Invalid URI: {0}'.format(actual_uri), 'Expected {0}'.format(expect_uri), 'PlugClean required.'] raise InvalidURI(msg) if G_PULL: self.write(Action.UPDATE, self.name, ['Updating ...']) callback = functools.partial(self.write, Action.UPDATE, self.name) fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else '' cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS) com = Command(cmd, self.args['dir'], G_TIMEOUT, callback) result = com.execute(G_RETRIES) self.write(Action.DONE, self.name, result[-1:]) else: self.write(Action.DONE, self.name, ['Already installed']) def write(self, action, name, msg): self.buf_q.put((action, name, msg)) class PlugThread(thr.Thread): def __init__(self, tname, args): super(PlugThread, self).__init__() self.tname = tname self.args = args def run(self): thr.current_thread().name = self.tname buf_q, work_q, lock = self.args try: while not G_STOP.is_set(): name, args = work_q.get_nowait() plug = Plugin(name, args, buf_q, lock) plug.manage() work_q.task_done() except queue.Empty: pass class RefreshThread(thr.Thread): def __init__(self, lock): super(RefreshThread, self).__init__() self.lock = lock self.running = True def run(self): while self.running: with self.lock: thread_vim_command('noautocmd normal! a') time.sleep(0.33) def stop(self): self.running = False if G_NVIM: def thread_vim_command(cmd): vim.session.threadsafe_call(lambda: vim.command(cmd)) else: def thread_vim_command(cmd): vim.command(cmd) def esc(name): return '"' + name.replace('"', '\"') + '"' def nonblock_read(fname): """ Read a file with nonblock flag. Return the last line. """ fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK) buf = os.read(fread, 100000).decode('utf-8', 'replace') os.close(fread) line = buf.rstrip('\r\n') left = max(line.rfind('\r'), line.rfind('\n')) if left != -1: left += 1 line = line[left:] return line def main(): thr.current_thread().name = 'main' nthreads = int(vim.eval('s:update.threads')) plugs = vim.eval('s:update.todo') mac_gui = vim.eval('s:mac_gui') == '1' lock = thr.Lock() buf = Buffer(lock, len(plugs), G_PULL) buf_q, work_q = queue.Queue(), queue.Queue() for work in plugs.items(): work_q.put(work) start_cnt = thr.active_count() for num in range(nthreads): tname = 'PlugT-{0:02}'.format(num) thread = PlugThread(tname, (buf_q, work_q, lock)) thread.start() if mac_gui: rthread = RefreshThread(lock) rthread.start() while not buf_q.empty() or thr.active_count() != start_cnt: try: action, name, msg = buf_q.get(True, 0.25) buf.write(action, name, ['OK'] if not msg else msg) buf_q.task_done() except queue.Empty: pass except KeyboardInterrupt: G_STOP.set() if mac_gui: rthread.stop() rthread.join() main() EOF endfunction function! s:update_ruby() ruby << EOF module PlugStream SEP = ["\r", "\n", nil] def get_line buffer = '' loop do char = readchar rescue return if SEP.include? char.chr buffer << $/ break else buffer << char end end buffer end end unless defined?(PlugStream) def esc arg %["#{arg.gsub('"', '\"')}"] end def killall pid pids = [pid] if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil } else unless `which pgrep 2> /dev/null`.empty? children = pids until children.empty? children = children.map { |pid| `pgrep -P #{pid}`.lines.map { |l| l.chomp } }.flatten pids += children end end pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil } end end require 'thread' require 'fileutils' require 'timeout' running = true iswin = VIM::evaluate('s:is_win').to_i == 1 pull = VIM::evaluate('s:update.pull').to_i == 1 base = VIM::evaluate('g:plug_home') all = VIM::evaluate('s:update.todo') limit = VIM::evaluate('get(g:, "plug_timeout", 60)') tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1 nthr = VIM::evaluate('s:update.threads').to_i maxy = VIM::evaluate('winheight(".")').to_i cd = iswin ? 'cd /d' : 'cd' tot = VIM::evaluate('len(s:update.todo)') || 0 bar = '' skip = 'Already installed' mtx = Mutex.new take1 = proc { mtx.synchronize { running && all.shift } } logh = proc { cnt = bar.length $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})" $curbuf[2] = '[' + bar.ljust(tot) + ']' VIM::command('normal! 2G') VIM::command('redraw') } where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } } log = proc { |name, result, type| mtx.synchronize do ing = ![true, false].include?(type) bar += type ? '=' : 'x' unless ing b = case type when :install then '+' when :update then '*' when true, nil then '-' else VIM::command("call add(s:update.errors, '#{name}')") 'x' end result = if type || type.nil? ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"] elsif result =~ /^Interrupted|^Timeout/ ["#{b} #{name}: #{result}"] else ["#{b} #{name}"] + result.lines.map { |l| " " << l } end if lnum = where.call(name) $curbuf.delete lnum lnum = 4 if ing && lnum > maxy end result.each_with_index do |line, offset| $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp) end logh.call end } bt = proc { |cmd, name, type, cleanup| tried = timeout = 0 begin tried += 1 timeout += limit fd = nil data = '' if iswin Timeout::timeout(timeout) do tmp = VIM::evaluate('tempname()') system("(#{cmd}) > #{tmp}") data = File.read(tmp).chomp File.unlink tmp rescue nil end else fd = IO.popen(cmd).extend(PlugStream) first_line = true log_prob = 1.0 / nthr while line = Timeout::timeout(timeout) { fd.get_line } data << line log.call name, line.chomp, type if name && (first_line || rand < log_prob) first_line = false end fd.close end [$? == 0, data.chomp] rescue Timeout::Error, Interrupt => e if fd && !fd.closed? killall fd.pid fd.close end cleanup.call if cleanup if e.is_a?(Timeout::Error) && tried < tries 3.downto(1) do |countdown| s = countdown > 1 ? 's' : '' log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type sleep 1 end log.call name, 'Retrying ...', type retry end [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"] end } main = Thread.current threads = [] watcher = Thread.new { while VIM::evaluate('getchar(1)') sleep 0.1 end mtx.synchronize do running = false threads.each { |t| t.raise Interrupt } end threads.each { |t| t.join rescue nil } main.kill } refresh = Thread.new { while true mtx.synchronize do break unless running VIM::command('noautocmd normal! a') end sleep 0.2 end } if VIM::evaluate('s:mac_gui') == 1 clone_opt = VIM::evaluate('s:clone_opt') progress = VIM::evaluate('s:progress_opt(1)') nthr.times do mtx.synchronize do threads << Thread.new { while pair = take1.call name = pair.first dir, uri, tag = pair.last.values_at *%w[dir uri tag] exists = File.directory? dir ok, result = if exists chdir = "#{cd} #{iswin ? dir : esc(dir)}" ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil current_uri = data.lines.to_a.last if !ret if data =~ /^Interrupted|^Timeout/ [false, data] else [false, [data.chomp, "PlugClean required."].join($/)] end elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '') [false, ["Invalid URI: #{current_uri}", "Expected: #{uri}", "PlugClean required."].join($/)] else if pull log.call name, 'Updating ...', :update fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : '' bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil else [true, skip] end end else d = esc dir.sub(%r{[\\/]+$}, '') log.call name, 'Installing ...', :install bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc { FileUtils.rm_rf dir } end mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok log.call name, result, ok end } if running end end threads.each { |t| t.join rescue nil } logh.call refresh.kill if refresh watcher.kill EOF endfunction function! s:shellesc(arg) return '"'.escape(a:arg, '"').'"' endfunction function! s:glob_dir(path) return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)') endfunction function! s:progress_bar(line, bar, total) call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']') endfunction function! s:compare_git_uri(a, b) let a = substitute(a:a, 'git:\{1,2}@', '', '') let b = substitute(a:b, 'git:\{1,2}@', '', '') return a ==# b endfunction function! s:format_message(bullet, name, message) if a:bullet != 'x' return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))] else let lines = map(s:lines(a:message), '" ".v:val') return extend([printf('x %s:', a:name)], lines) endif endfunction function! s:with_cd(cmd, dir) return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd) endfunction function! s:system(cmd, ...) try let [sh, shrd] = s:chsh(1) let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd return system(s:is_win ? '('.cmd.')' : cmd) finally let [&shell, &shellredir] = [sh, shrd] endtry endfunction function! s:system_chomp(...) let ret = call('s:system', a:000) return v:shell_error ? '' : substitute(ret, '\n$', '', '') endfunction function! s:git_validate(spec, check_branch) let err = '' if isdirectory(a:spec.dir) let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir)) let remote = result[-1] if v:shell_error let err = join([remote, 'PlugClean required.'], "\n") elseif !s:compare_git_uri(remote, a:spec.uri) let err = join(['Invalid URI: '.remote, \ 'Expected: '.a:spec.uri, \ 'PlugClean required.'], "\n") elseif a:check_branch && has_key(a:spec, 'commit') let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir)) let sha = result[-1] if v:shell_error let err = join(add(result, 'PlugClean required.'), "\n") elseif !s:hash_match(sha, a:spec.commit) let err = join([printf('Invalid HEAD (expected: %s, actual: %s)', \ a:spec.commit[:6], sha[:6]), \ 'PlugUpdate required.'], "\n") endif elseif a:check_branch let branch = result[0] " Check tag if has_key(a:spec, 'tag') let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir) if a:spec.tag !=# tag let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.', \ (empty(tag) ? 'N/A' : tag), a:spec.tag) endif " Check branch elseif a:spec.branch !=# branch let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', \ branch, a:spec.branch) endif if empty(err) let commits = len(s:lines(s:system(printf('git rev-list origin/%s..HEAD', a:spec.branch), a:spec.dir))) if !v:shell_error && commits let err = join([printf('Diverged from origin/%s by %d commit(s).', a:spec.branch, commits), \ 'Reinstall after PlugClean.'], "\n") endif endif endif else let err = 'Not found' endif return [err, err =~# 'PlugClean'] endfunction function! s:rm_rf(dir) if isdirectory(a:dir) call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir)) endif endfunction function! s:clean(force) call s:prepare() call append(0, 'Searching for invalid plugins in '.g:plug_home) call append(1, '') " List of valid directories let dirs = [] let errs = {} let [cnt, total] = [0, len(g:plugs)] for [name, spec] in items(g:plugs) if !s:is_managed(name) call add(dirs, spec.dir) else let [err, clean] = s:git_validate(spec, 1) if clean let errs[spec.dir] = s:lines(err)[0] else call add(dirs, spec.dir) endif endif let cnt += 1 call s:progress_bar(2, repeat('=', cnt), total) normal! 2G redraw endfor let allowed = {} for dir in dirs let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1 let allowed[dir] = 1 for child in s:glob_dir(dir) let allowed[child] = 1 endfor endfor let todo = [] let found = sort(s:glob_dir(g:plug_home)) while !empty(found) let f = remove(found, 0) if !has_key(allowed, f) && isdirectory(f) call add(todo, f) call append(line('$'), '- ' . f) if has_key(errs, f) call append(line('$'), ' ' . errs[f]) endif let found = filter(found, 'stridx(v:val, f) != 0') end endwhile 4 redraw if empty(todo) call append(line('$'), 'Already clean.') else let s:clean_count = 0 call append(3, ['Directories to delete:', '']) redraw! if a:force || s:ask_no_interrupt('Delete all directories?') call s:delete([6, line('$')], 1) else call setline(4, 'Cancelled.') nnoremap d :set opfunc=delete_opg@ nmap dd d_ xnoremap d :call delete_op(visualmode(), 1) echo 'Delete the lines (d{motion}) to delete the corresponding directories' endif endif 4 setlocal nomodifiable endfunction function! s:delete_op(type, ...) call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0) endfunction function! s:delete(range, force) let [l1, l2] = a:range let force = a:force while l1 <= l2 let line = getline(l1) if line =~ '^- ' && isdirectory(line[2:]) execute l1 redraw! let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1) let force = force || answer > 1 if answer call s:rm_rf(line[2:]) setlocal modifiable call setline(l1, '~'.line[1:]) let s:clean_count += 1 call setline(4, printf('Removed %d directories.', s:clean_count)) setlocal nomodifiable endif endif let l1 += 1 endwhile endfunction function! s:upgrade() echo 'Downloading the latest version of vim-plug' redraw let tmp = tempname() let new = tmp . '/plug.vim' try let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp)) if v:shell_error return s:err('Error upgrading vim-plug: '. out) endif if readfile(s:me) ==# readfile(new) echo 'vim-plug is already up-to-date' return 0 else call rename(s:me, s:me . '.old') call rename(new, s:me) unlet g:loaded_plug echo 'vim-plug has been upgraded' return 1 endif finally silent! call s:rm_rf(tmp) endtry endfunction function! s:upgrade_specs() for spec in values(g:plugs) let spec.frozen = get(spec, 'frozen', 0) endfor endfunction function! s:status() call s:prepare() call append(0, 'Checking plugins') call append(1, '') let ecnt = 0 let unloaded = 0 let [cnt, total] = [0, len(g:plugs)] for [name, spec] in items(g:plugs) if has_key(spec, 'uri') if isdirectory(spec.dir) let [err, _] = s:git_validate(spec, 1) let [valid, msg] = [empty(err), empty(err) ? 'OK' : err] else let [valid, msg] = [0, 'Not found. Try PlugInstall.'] endif else if isdirectory(spec.dir) let [valid, msg] = [1, 'OK'] else let [valid, msg] = [0, 'Not found.'] endif endif let cnt += 1 let ecnt += !valid " `s:loaded` entry can be missing if PlugUpgraded if valid && get(s:loaded, name, -1) == 0 let unloaded = 1 let msg .= ' (not loaded)' endif call s:progress_bar(2, repeat('=', cnt), total) call append(3, s:format_message(valid ? '-' : 'x', name, msg)) normal! 2G redraw endfor call setline(1, 'Finished. '.ecnt.' error(s).') normal! gg setlocal nomodifiable if unloaded echo "Press 'L' on each line to load plugin, or 'U' to update" nnoremap L :call status_load(line('.')) xnoremap L :call status_load(line('.')) end endfunction function! s:extract_name(str, prefix, suffix) return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$') endfunction function! s:status_load(lnum) let line = getline(a:lnum) let name = s:extract_name(line, '-', '(not loaded)') if !empty(name) call plug#load(name) setlocal modifiable call setline(a:lnum, substitute(line, ' (not loaded)$', '', '')) setlocal nomodifiable endif endfunction function! s:status_update() range let lines = getline(a:firstline, a:lastline) let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)') if !empty(names) echo execute 'PlugUpdate' join(names) endif endfunction function! s:is_preview_window_open() silent! wincmd P if &previewwindow wincmd p return 1 endif endfunction function! s:find_name(lnum) for lnum in reverse(range(1, a:lnum)) let line = getline(lnum) if empty(line) return '' endif let name = s:extract_name(line, '-', '') if !empty(name) return name endif endfor return '' endfunction function! s:preview_commit() if b:plug_preview < 0 let b:plug_preview = !s:is_preview_window_open() endif let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7}') if empty(sha) return endif let name = s:find_name(line('.')) if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir) return endif if exists('g:plug_pwindow') && !s:is_preview_window_open() execute g:plug_pwindow execute 'e' sha else execute 'pedit' sha wincmd P endif setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable execute 'silent %!cd' s:shellesc(g:plugs[name].dir) '&& git show --no-color --pretty=medium' sha setlocal nomodifiable nnoremap q :q wincmd p endfunction function! s:section(flags) call search('\(^[x-] \)\@<=[^:]\+:', a:flags) endfunction function! s:format_git_log(line) let indent = ' ' let tokens = split(a:line, nr2char(1)) if len(tokens) != 5 return indent.substitute(a:line, '\s*$', '', '') endif let [graph, sha, refs, subject, date] = tokens let tag = matchstr(refs, 'tag: [^,)]\+') let tag = empty(tag) ? ' ' : ' ('.tag.') ' return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date) endfunction function! s:append_ul(lnum, text) call append(a:lnum, ['', a:text, repeat('-', len(a:text))]) endfunction function! s:diff() call s:prepare() call append(0, ['Collecting changes ...', '']) let cnts = [0, 0] let bar = '' let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)') call s:progress_bar(2, bar, len(total)) for origin in [1, 0] let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))')))) if empty(plugs) continue endif call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:') for [k, v] in plugs let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..' let diff = s:system_chomp('git log --graph --color=never --pretty=format:"%x01%h%x01%d%x01%s%x01%cr" '.s:shellesc(range), v.dir) if !empty(diff) let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : '' call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)'))) let cnts[origin] += 1 endif let bar .= '=' call s:progress_bar(2, bar, len(total)) normal! 2G redraw endfor if !cnts[origin] call append(5, ['', 'N/A']) endif endfor call setline(1, printf('%d plugin(s) updated.', cnts[0]) \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : '')) if cnts[0] || cnts[1] nnoremap :silent! call preview_commit() nnoremap o :silent! call preview_commit() endif if cnts[0] nnoremap X :call revert() echo "Press 'X' on each block to revert the update" endif normal! gg setlocal nomodifiable endfunction function! s:revert() if search('^Pending updates', 'bnW') return endif let name = s:find_name(line('.')) if empty(name) || !has_key(g:plugs, name) || \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y' return endif call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir) setlocal modifiable normal! "_dap setlocal nomodifiable echo 'Reverted' endfunction function! s:snapshot(force, ...) abort call s:prepare() setf vim call append(0, ['" Generated by vim-plug', \ '" '.strftime("%c"), \ '" :source this file in vim to restore the snapshot', \ '" or execute: vim -S snapshot.vim', \ '', '', 'PlugUpdate!']) 1 let anchor = line('$') - 3 let names = sort(keys(filter(copy(g:plugs), \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)'))) for name in reverse(names) let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir) if !empty(sha) call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha)) redraw endif endfor if a:0 > 0 let fn = expand(a:1) if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?')) return endif call writefile(getline(1, '$'), fn) echo 'Saved as '.a:1 silent execute 'e' s:esc(fn) setf vim endif endfunction function! s:split_rtp() return split(&rtp, '\\\@ " source: https://github.com/krampstudio/dotvim " year : 2015 " " nothing yet, you can suggest yours via PR ================================================ FILE: config/autocmd.vim ================================================ " " WebVim Configuration : autocommands " " author: Bertrand Chevrier " source: https://github.com/krampstudio/dotvim " year : 2015 " " Force filetype autocmd BufRead,BufNewFile .eslintrc setfiletype json autocmd BufRead,BufNewFile .jshintrc setfiletype json " Omni-Completion tip window to close when a selection is " made, these lines close it on movement in insert mode or when leaving " insert mode "autocmd CursorMovedI * if pumvisible() == 0|pclose|endif autocmd InsertLeave * if pumvisible() == 0|pclose|endif ================================================ FILE: config/mapping.vim ================================================ " " WebVim Configuration : global mapping " " author: Bertrand Chevrier " " leader let g:mapleader = "," let g:localmapleader = "\\" " move the current line below nnoremap - ddp " move the current line above nnoremap _ ddkP " switch tab nnoremap :tabn nnoremap :tabp " insert mode uppercase the current word " : go to normal mode " v : visual mode " iw : select the current word " U : uppercase selection " i : back to insert mode inoremap viwUi " remove last search highlight nnoremap :nohlsearch " Wrap a word in double quotes nnoremap " viwa"hbi"lel " Wrap a word in single quotes nnoremap ' viwa'hbi'lel " select inside parents onoremap in( :normal! f(vi( " select inside braces onoremap in{ :normal! f{vi{ " select inside brackets onoremap in[ :normal! f[vi[ " Open MYVIMRC in a vsplit nnoremap ev :split $MYVIMRC " Source MYVIMRC nnoremap sv :source $MYVIMRC if g:hardcoreMode == 1 " Leave insert mode (like ) and disable inoremap jk inoremap inoremap ^[ ^[ " Disable arrow keys nnoremap nnoremap nnoremap nnoremap inoremap inoremap inoremap inoremap endif ================================================ FILE: config/setting.vim ================================================ " " WebVim Configuration : global settings " " author: Bertrand Chevrier " source: https://github.com/krampstudio/dotvim " year : 2015 " " wrap end of line set wrap " show line numbers set number " syntax highlighting syntax on set background=dark set t_Co=256 colorscheme PaperColor "indent set smartindent set autoindent set copyindent set shiftwidth=4 set shiftround set backspace=indent,eol,start set smarttab set expandtab "search set showmatch set smartcase set hlsearch set incsearch " copy/paste "set paste set clipboard=unnamedplus " folding manual set foldmethod=manual " mouse set mouse=a " spell check, to be activated manually set spelllang=en_us set nospell ================================================ FILE: fonts/10-powerline-symbols.conf ================================================ monospace PowerlineSymbols Droid Sans Mono PowerlineSymbols Droid Sans Mono Slashed PowerlineSymbols Droid Sans Mono Dotted PowerlineSymbols DejaVu Sans Mono PowerlineSymbols DejaVu Sans Mono PowerlineSymbols Envy Code R PowerlineSymbols Inconsolata PowerlineSymbols Lucida Console PowerlineSymbols Monaco PowerlineSymbols Pragmata PowerlineSymbols PragmataPro PowerlineSymbols Menlo PowerlineSymbols Source Code Pro PowerlineSymbols Consolas PowerlineSymbols Anonymous pro PowerlineSymbols Bitstream Vera Sans Mono PowerlineSymbols Liberation Mono PowerlineSymbols Ubuntu Mono PowerlineSymbols Meslo LG L PowerlineSymbols Meslo LG L DZ PowerlineSymbols Meslo LG M PowerlineSymbols Meslo LG M DZ PowerlineSymbols Meslo LG S PowerlineSymbols Meslo LG S DZ PowerlineSymbols ================================================ FILE: fonts/install ================================================ #!/bin/sh current=$(dirname "$0") fontDir="$HOME/.fonts" fontFile="$current/PowerlineSymbols.otf" fontConfDir="$HOME/.fonts.conf.d" fontConfFile="$current/10-powerline-symbols.conf" echo "Installing Powerline Font for Airline plugin into user space $HOME" #Check fc-cache is installed command -v fc-cache >/dev/null 2>&1 || { echo >&2 "This script requires fc-cache to install the font, but it's not installed. Quiting"; exit 1; } [ -d "$fontDir" ] || mkdir "$fontDir" cp "$fontFile" "$fontDir" [ -d "$fontiConfDir" ] || mkdir "$fontConfDir" cp "$fontConfFile" "$fontConfDir" fc-cache -vf "$fontDir" exit 0 ================================================ FILE: plugins/config.vim ================================================ " " WebVim Configuration : Plugins configuration " " author: Bertrand Chevrier " source: https://github.com/krampstudio/dotvim " year : 2015-2019 " " TODO split by plugin ? " [> NERDTree <] " on vim enter opens nerd tree function! OpenNerdTree() let s:exclude = ['COMMIT_EDITMSG', 'MERGE_MSG'] if index(s:exclude, expand('%:t')) < 0 NERDTreeFind exec "normal! \\" endif endfunction autocmd VimEnter * call OpenNerdTree() " nerdtree window resize let g:NERDTreeWinSize = 35 " show hidden files let g:NERDTreeShowHidden=1 " single click to open nodes " let g:NERDTreeMouseMode=3 " ignored files let g:NERDTreeIgnore=['\.swp$', '\~$'] nnoremap :NERDTreeToggle " helps quiting when there's no buffers left but NerdTree function! CheckLeftBuffers() if tabpagenr('$') == 1 let i = 1 while i <= winnr('$') if getbufvar(winbufnr(i), '&buftype') == 'help' || \ getbufvar(winbufnr(i), '&buftype') == 'quickfix' || \ exists('t:NERDTreeBufName') && \ bufname(winbufnr(i)) == t:NERDTreeBufName || \ bufname(winbufnr(i)) == '__Tag_List__' let i += 1 else break endif endwhile if i == winnr('$') + 1 qall endif unlet i endif endfunction autocmd BufEnter * call CheckLeftBuffers() " git indicator in tree let g:NERDTreeIndicatorMapCustom = { \ "Modified" : "✹", \ "Staged" : "✚", \ "Untracked" : "✭", \ "Renamed" : "➜", \ "Unmerged" : "═", \ "Deleted" : "✖", \ "Dirty" : "✗", \ "Clean" : "✔︎", \ 'Ignored' : '☒', \ "Unknown" : "?" \ } " [> NERDCommenter <] noremap :call NERDComment(0, "Toggle") " [> Airline <] " status line always opened set laststatus=2 let g:airline#extensions#tabline#enabled = 1 " powerline font let g:airline_powerline_fonts=1 let g:airline_theme='papercolor' " [> EditorConfig <] " to avoid issues with fugitive let g:EditorConfig_exclude_patterns = ['fugitive://.*'] " [> Syntastic <] "" Syntax checkers let g:syntastic_check_on_open=1 let g:syntastic_enable_signs=1 let g:syntastic_php_checkers=['php', 'phpcs', 'phpmd'] let g:syntastic_html_checkers=['tidy'] let g:syntastic_vim_checkers=['vimlint'] let g:syntastic_json_checkers=['jsonlint'] let g:syntastic_yaml_checkers=['js-yaml'] let g:syntastic_sass_checkers=["sasslint"] let g:syntastic_scss_checkers=["sasslint"] let g:syntastic_css_checkers=['csslint'] let g:syntastic_handlebars_checkers=['handlebars'] let g:syntastic_tpl_checkers=['handlebars'] " get available js linters " it returns the mapping between a linter and the config files function! GetJslinters() return { \ 'eslint' : [ '.eslintrc', '.eslintrc.json', '.eslintrc.js', '.eslint.yml' ], \ 'jshint' : [ '.jshintrc'] \ } endfunction " check if the path to see if a linter config is present function! Jslinter(path, linters) let l:dir = fnamemodify(a:path, ':p:h') if(l:dir == '/') return [''] endif for l:linter in keys(a:linters) for l:linterConfig in a:linters[l:linter] if filereadable(l:dir . '/' . l:linterConfig) let l:localLinter = l:dir . '/node_modules/.bin/' . l:linter if executable(l:localLinter) return [l:linter, l:localLinter] endif return [l:linter, l:linter] endif endfor endfor return Jslinter(fnamemodify(l:dir, ':h'), a:linters) endfunction " set the jslinter into Syntastic function! SyntasticSetJsLinter() let l:availableLinters = GetJslinters() " look for linter config in the current folder let l:jslinter = Jslinter(expand('%:p'), l:availableLinters) if l:jslinter[0] == '' " otherwise look into the home dir let l:jslinter = Jslinter($HOME, l:availableLinters) endif " configure the linter if l:jslinter[0] != '' let g:syntastic_javascript_checkers=[l:jslinter[0]] if l:jslinter[0] != l:jslinter[1] exec 'let g:syntastic_javascript_' . l:jslinter[0] . '_exec = "' . l:jslinter[1] . '"' endif let g:syntastic_javascript_checkers=[l:jslinter[0]] endif endfunction call SyntasticSetJsLinter() " [> EasyAlign <] " select paragraph and start easyalign on the left nnoremap a vip(EasyAlign) " Start interactive align to the right vmap a (EasyAlign) let g:easy_align_ignore_groups = ['Comment'] let s:easy_align_delimiters_default = { \ ' ': { 'pattern': ' ', 'left_margin': 0, 'right_margin': 0, 'stick_to_left': 0 }, \ '=': { 'pattern': '===\|<=>\|\(&&\|||\|<<\|>>\)=\|=\~[#?]\?\|=>\|[:+/*!%^=><&|.-]\?=[#?]\?', \ 'left_margin': 1, 'right_margin': 1, 'stick_to_left': 0 }, \ ':': { 'pattern': ':', 'left_margin': 1, 'right_margin': 1, 'stick_to_left': 0 }, \ ',': { 'pattern': ',', 'left_margin': 0, 'right_margin': 1, 'stick_to_left': 1 }, \ '|': { 'pattern': '|', 'left_margin': 1, 'right_margin': 1, 'stick_to_left': 0 }, \ '.': { 'pattern': '\.', 'left_margin': 0, 'right_margin': 0, 'stick_to_left': 0 }, \ '#': { 'pattern': '#\+', 'delimiter_align': 'l', 'ignore_groups': ['!Comment'] }, \ '&': { 'pattern': '\\\@ multiple cursor <] let g:multi_cursor_use_default_mapping=0 let g:multi_cursor_next_key='' let g:multi_cursor_prev_key='' let g:multi_cursor_skip_key='' let g:multi_cursor_quit_key='' " [> JsBeautify <] " format selection autocmd FileType javascript vnoremap :call RangeJsBeautify() autocmd FileType json vnoremap :call RangeJsonBeautify() autocmd FileType html vnoremap :call RangeHtmlBeautify() autocmd FileType css vnoremap :call RangeCSSBeautify() " format the whole file autocmd FileType javascript nnoremap :call JsBeautify() autocmd FileType json nnoremap :call JsonBeautify() autocmd FileType html nnoremap :call HtmlBeautify() autocmd FileType css nnoremap :call CSSBeautify() " [> YankStack <] nmap p yankstack_substitute_older_paste nmap P yankstack_substitute_newer_paste " [> Javascript libraries syntax <] let g:used_javascript_libs = 'jquery,underscore,requirejs,chai,handlebars,d3,tape,react,vue,ramda' " [> JSON <] let g:vim_json_syntax_conceal = 0 " [> YCM shortcuts <] " function! Refactor() call inputsave() let g:newName = input("Enter the new variable name : ") call inputrestore() exec ":YcmCompleter RefactorRename " . g:newName endfunction nnoremap gt :YcmCompleter GetType nnoremap gd :YcmCompleter GetDoc nnoremap go :YcmCompleter GoTo nnoremap gf :YcmCompleter GoToDefinition nnoremap gr :YcmCompleter GoToReferences nnoremap r :call Refactor() " [> Emmet shortcuts <] " let g:user_emmet_install_global = 0 autocmd FileType html,tpl,hbs,css,scss EmmetInstall let g:user_emmet_leader_key='' ================================================ FILE: plugins/def.vim ================================================ function! InstallYCM(info) if a:info.status == 'installed' || a:info.force !./install.py !cd ./third_party/ycmd/third_party/tern_runtime && npm install endif endfunction " Start plugins definition call plug#begin($HOME.'/.vim/plugins/plugged') Plug 'scrooloose/nerdtree', { 'commit' : '84737f2ebe533ffac9ebc21da8d1f57216962641' } | Plug 'https://gist.github.com/1f40e70e615f2fa2212bf5423662277d.git', { 'dir' : g:vimDir . '/nerdtree_plugin' } | Plug 'Xuyuanp/nerdtree-git-plugin', { 'commit' : '325a1298b0c9d8a4c61388a2f9956a534a9068cd' } | Plug 'MarSoft/nerdtree-grep-plugin', { 'commit' : '09e446ebe4770687a6283905d5ff461ea268bc14' } Plug 'scrooloose/nerdcommenter', { 'commit' : '9a32fd2534427f7a1dcfe22e9c0ea6b67b6dbe78' } Plug 'NLKNguyen/papercolor-theme', { 'commit' : 'c4a4dfdc21c14f58c12d077242ae33b729c894b2' } Plug 'bling/vim-airline', { 'commit' : '1c3ae6077af76927f82f87e05a7b9fdfba47ce2c', 'do' : $HOME.'/.vim/fonts/install' } Plug 'vim-airline/vim-airline-themes', { 'commit' : '3bfe1d00d48f7c35b7c0dd7af86229c9e63e14a9' } Plug 'tpope/vim-fugitive', { 'commit' : '2564c37d0a2ade327d6381fef42d84d9fad1d057' } Plug 'tpope/vim-rhubarb', { 'commit' : '57a350e6327af0074c4bc0d30b62662dfdb993af' } Plug 'airblade/vim-gitgutter', { 'commit' : '7eeea63e62b1cc088a75c7a7c244fc774d82e5bb' } Plug 'editorconfig/editorconfig-vim', { 'commit' : '68f8136d2b018bfa9b23403e87d3d65bc942cbc3' } Plug 'bronson/vim-trailing-whitespace', { 'commit' : '733fb64337b6da4a51c85a43450cd620d8b617b5' } Plug 'scrooloose/syntastic', { 'commit' : '6ffba7395c562e152cb84bc8f7906de2b1ed0b8a' } Plug 'gcorne/vim-sass-lint', { 'commit' : 'b9ff33141294c7af143f12687e9b1cf9a3a54e0f' } Plug 'junegunn/vim-easy-align', { 'commit' : '0cb6b98fc155717b0a56c110551ac57d1d951ddb' } Plug 'terryma/vim-multiple-cursors', { 'commit' : '51d0717f63cc231f11b4b63ee5b611f589dce1b3' } Plug 'maksimr/vim-jsbeautify', { 'commit' : 'caffda66a2a8852ee132f95291115af67370c5e7', 'do' : 'git submodule update --init --recursive && npm install' } Plug 'maxbrunsfeld/vim-yankstack', { 'commit' : '157a659c1b101c899935d961774fb5c8f0775370' } Plug 'tpope/vim-surround', { 'commit' : 'e49d6c2459e0f5569ff2d533b4df995dd7f98313'} Plug 'elzr/vim-json', { 'commit' : '3727f089410e23ae113be6222e8a08dd2613ecf2'} Plug 'othree/yajs.vim', { 'commit' : '437be4ccf0e78fe54cb482657091cff9e8479488'} Plug 'othree/es.next.syntax.vim', { 'commit' : 'ad2d6a27073e43e41b8041b3655f2444a251c444'} Plug 'othree/javascript-libraries-syntax.vim', { 'commit' : '5ef435d8c28ebc3c9b52fb865f4c06db629857f7'} Plug 'hail2u/vim-css3-syntax', { 'commit' : '3e40dde46c6a3bc4f0339248b000bbe96e39dc2d'} Plug 'cakebaker/scss-syntax.vim', { 'commit' : '4461789d02f81fd328afbdf27d6404b6c763c25f'} Plug 'othree/html5.vim', { 'commit' : 'bc7faabe7a4dfc0d963d6d8a406c3b7284e2866f'} Plug 'Valloric/YouCompleteMe', { 'commit' : 'ddf18cc6ec3bb0108bb89ac366fd74394815f2c6', 'do': function('InstallYCM') } Plug 'moll/vim-node', { 'commit' : 'ede047791792b9530ba1ae73ed86e9671cdd96b8'} Plug 'syngan/vim-vimlint', { 'commit' : 'c8b9cd9d8a0fb6dc69667d32819aeef503cff55c'} Plug 'ynkdir/vim-vimlparser', { 'commit' : '2fff43c58968a18bc01bc8304df68bde01af04d9'} Plug 'mattn/emmet-vim', { 'commit' : 'd698f1658770ca5fa58c87e80421c8d65bbe9065'} Plug 'martinda/Jenkinsfile-vim-syntax' call plug#end()