diff options
author | Karel Kočí <cynerd@email.cz> | 2016-06-30 16:03:25 +0200 |
---|---|---|
committer | Karel Kočí <cynerd@email.cz> | 2016-06-30 16:03:25 +0200 |
commit | e573b3020c032400eed60b649a2cbf55266e6bb0 (patch) | |
tree | 8f572394ac8433529c7a8e70d160a2fbe8268b4e /vim/bundle/YouCompleteMe | |
parent | b8c667bd64b3edd38d56c63c5bd1db53a23b4499 (diff) | |
download | myconfigs-e573b3020c032400eed60b649a2cbf55266e6bb0.tar.gz myconfigs-e573b3020c032400eed60b649a2cbf55266e6bb0.tar.bz2 myconfigs-e573b3020c032400eed60b649a2cbf55266e6bb0.zip |
Add current configurations from old repository
Diffstat (limited to 'vim/bundle/YouCompleteMe')
91 files changed, 22118 insertions, 0 deletions
diff --git a/vim/bundle/YouCompleteMe/.github/ISSUE_TEMPLATE.md b/vim/bundle/YouCompleteMe/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..fa80b9c --- /dev/null +++ b/vim/bundle/YouCompleteMe/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,39 @@ +# Issue Prelude + +**Please complete these steps and check these boxes (by putting an `x` inside +the brackets) _before_ filing your issue:** + +- [ ] I have read and understood YCM's [CONTRIBUTING][cont] document. +- [ ] I have read and understood YCM's [CODE_OF_CONDUCT][code] document. +- [ ] I have read and understood YCM's [README][readme], **especially the + [Frequently Asked Questions][faq] section.** +- [ ] I have searched YCM's issue tracker to find issues similar to the one I'm + about to report and couldn't find an answer to my problem. ([Example Google + search.][search]) +- [ ] If filing a bug report, I have included the output of `vim --version`. +- [ ] If filing a bug report, I have included the output of `:YcmDebugInfo`. +- [ ] If filing a bug report, I have included the output of + `:YcmToggleLogs stderr`. +- [ ] If filing a bug report, I have included which OS (including specific OS + version) I am using. +- [ ] If filing a bug report, I have included a minimal test case that reproduces + my issue. +- [ ] **I understand this is an open-source project staffed by volunteers and + that any help I receive is a selfless, heartfelt _gift_ of their free time. I + know I am not entitled to anything and will be polite and courteous.** +- [ ] **I understand my issue may be closed if it becomes obvious I didn't + actually perform all of these steps.** + +Thank you for adhering to this process! It ensures your issue is resolved +quickly and that neither your nor our time is needlessly wasted. + +# Issue Details + +[If filing a bug report, please include **a list of steps** that describe how to +reproduce the bug you are experiencing. Also include test code if relevant.] + +[cont]: https://github.com/Valloric/YouCompleteMe/blob/master/CONTRIBUTING.md +[code]: https://github.com/Valloric/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md +[readme]: https://github.com/Valloric/YouCompleteMe/blob/master/README.md +[faq]: https://github.com/Valloric/YouCompleteMe/blob/master/README.md#faq +[search]: https://www.google.com/search?q=site%3Ahttps%3A%2F%2Fgithub.com%2FValloric%2FYouCompleteMe%2Fissues%20python%20mac diff --git a/vim/bundle/YouCompleteMe/.github/PULL_REQUEST_TEMPLATE.md b/vim/bundle/YouCompleteMe/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..ffcf4a5 --- /dev/null +++ b/vim/bundle/YouCompleteMe/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,20 @@ +# PR Prelude + +Thank you for working on YCM! :) + +**Please complete these steps and check these boxes (by putting an `x` inside +the brackets) _before_ filing your PR:** + +- [ ] I have read and understood YCM's [CONTRIBUTING][cont] document. +- [ ] I have read and understood YCM's [CODE_OF_CONDUCT][code] document. +- [ ] I have included tests for the changes in my PR. If not, I have included a + rationale for why I haven't. +- [ ] **I understand my PR may be closed if it becomes obvious I didn't + actually perform all of these steps.** + +# Why this change is necessary and useful + +[Please explain **in detail** why the changes in this PR are needed.] + +[cont]: https://github.com/Valloric/YouCompleteMe/blob/master/CONTRIBUTING.md +[code]: https://github.com/Valloric/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md diff --git a/vim/bundle/YouCompleteMe/.gitignore b/vim/bundle/YouCompleteMe/.gitignore new file mode 100644 index 0000000..80c1256 --- /dev/null +++ b/vim/bundle/YouCompleteMe/.gitignore @@ -0,0 +1,58 @@ +# Compiled Object files +*.slo +*.lo +*.o + +# Compiled Dynamic libraries +*.dll +*.so +*.dylib + +# Compiled Static libraries +*.lai +*.la +*.a + +# CMake +CMakeCache.txt +CMakeFiles +Makefile +cmake_install.cmake +install_manifest.txt + +# Python +*.py[cod] + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg + +# custom +ycm_core_tests + +# When we use the bcp tool to copy over the parts of boost we care about, it +# also copies some cruft files we don't need; this ignores them +cpp/BoostParts/libs/*/build +cpp/BoostParts/libs/*/test + +# These folders in cpp/llvm contain lots of upstream cruft we don't care +# about and would rather not have in our tree... +cpp/llvm/docs/* +cpp/llvm/tools/clang/www/* + +# ... but excluding these LLVMBuild.txt files breaks the build so we need to +# explicitely include them +!LLVMBuild.txt + +# Exclude auto generated vim doc tags. +doc/tags diff --git a/vim/bundle/YouCompleteMe/.gitmodules b/vim/bundle/YouCompleteMe/.gitmodules new file mode 100644 index 0000000..81b39d1 --- /dev/null +++ b/vim/bundle/YouCompleteMe/.gitmodules @@ -0,0 +1,6 @@ +[submodule "third_party/requests-futures"] + path = third_party/requests-futures + url = https://github.com/ross/requests-futures +[submodule "third_party/ycmd"] + path = third_party/ycmd + url = https://github.com/Valloric/ycmd diff --git a/vim/bundle/YouCompleteMe/.travis.yml b/vim/bundle/YouCompleteMe/.travis.yml new file mode 100644 index 0000000..34df1b2 --- /dev/null +++ b/vim/bundle/YouCompleteMe/.travis.yml @@ -0,0 +1,47 @@ +language: generic +os: + - linux + - osx +sudo: false +before_install: + - git submodule update --init --recursive +install: + # source because it sets up env vars on some platforms + - source ci/travis/travis_install.sh +script: ./run_tests.py +env: + matrix: + - YCM_PYTHON_VERSION=2.7 + - YCM_PYTHON_VERSION=2.6 + - YCM_PYTHON_VERSION=3.3 +matrix: + exclude: + - os: osx + env: YCM_PYTHON_VERSION=2.6 +addons: + apt: + sources: + # The Travis apt source whitelist can be found here: + # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json + - ubuntu-toolchain-r-test # for new libstdc++ + - george-edison55-precise-backports # for a more recent version of cmake (3.2.3) + packages: + - cmake-data + - cmake + - ninja-build + # Everything below is a Python build dep (though it depends on Python + # version). We need them because pyenv builds Python. + - libssl-dev + - zlib1g-dev + - libbz2-dev + - libreadline-dev + - libsqlite3-dev + - wget + - curl + - llvm + - libncurses5-dev + - libncursesw5-dev +cache: + directories: + - $HOME/.cache/pip # Python packages from pip + - $HOME/.pyenv # pyenv diff --git a/vim/bundle/YouCompleteMe/CODE_OF_CONDUCT.md b/vim/bundle/YouCompleteMe/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..e39575f --- /dev/null +++ b/vim/bundle/YouCompleteMe/CODE_OF_CONDUCT.md @@ -0,0 +1,50 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to +fairly and consistently applying these principles to every aspect of managing +this project. Project maintainers who do not follow or enforce the Code of +Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting a project maintainer at val@markovic.io. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. Maintainers are +obligated to maintain confidentiality with regard to the reporter of an +incident. + + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.3.0, available at +[http://contributor-covenant.org/version/1/3/0/][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/3/0/ diff --git a/vim/bundle/YouCompleteMe/CONTRIBUTING.md b/vim/bundle/YouCompleteMe/CONTRIBUTING.md new file mode 100644 index 0000000..d3e158f --- /dev/null +++ b/vim/bundle/YouCompleteMe/CONTRIBUTING.md @@ -0,0 +1,112 @@ +Writing good issue reports +========================== + +First things first: **the issue tracker is NOT for tech support**. It is for +reporting bugs and requesting features. If your issue amounts to "I can't get +YCM to work on my machine" and the reason why is obviously related to your +machine configuration and the problem would not be resolved with _reasonable_ +changes to the YCM codebase, then the issue is likely to be closed. + +**A good place to ask questions is the [ycm-users][] Google group**. Rule of +thumb: if you're not sure whether your problem is a real bug, ask on the group. + +**YCM compiles just fine**; [the build bots say so][build-bots]. If the bots are +green and YCM doesn't compile on your machine, then _your machine is the root +cause_. Now read the first paragraph again. + +Realize that quite literally _thousands_ of people have gotten YCM to work +successfully so if you can't, it's probably because you have a peculiar +system/Vim configuration or you didn't go through the docs carefully enough. +It's very unlikely to be caused by an actual bug in YCM because someone would +have already found it and reported it. + +This leads us to point #2: **make sure you have checked the docs before +reporting an issue**. The docs are extensive and cover a ton of things; there's +also an FAQ at the bottom that quite possibly addresses your problem. + +Further, **search the issue tracker for similar issues** before creating a new +one. There's no point in duplication; if an existing issue addresses your +problem, please comment there instead of creating a duplicate. + +You should also **search the archives of the [ycm-users][] mailing list**. + +Lastly, **make sure you are running the latest version of YCM**. The issue you +have encountered may have already been fixed. **Don't forget to recompile +ycm_core.so too** (usually by just running `install.py` again). + +OK, so we've reached this far. You need to create an issue. First realize that +the time it takes to fix your issue is a multiple of how long it takes the +developer to reproduce it. The easier it is to reproduce, the quicker it'll be +fixed. + +Here are the things you should do when creating an issue: + +1. **Write a step-by-step procedure that when performed repeatedly reproduces + your issue.** If we can't reproduce the issue, then we can't fix it. It's + that simple. +2. Put the following options in your vimrc: + + ```viml + let g:ycm_server_keep_logfiles = 1 + let g:ycm_server_log_level = 'debug' + ``` + + Run `:YcmToggleLogs stderr` in vim to open the logfile. Attach the contents + of this file to your issue. +3. Add the output of the `:YcmDebugInfo` command. +4. **Create a test case for your issue**. This is critical. Don't talk about how + "when I have X in my file" or similar, _create a file with X in it_ and put + the contents inside code blocks in your issue description. Try to make this + test file _as small as possible_. Don't just paste a huge, 500 line source + file you were editing and present that as a test. _Minimize_ the file so that + the problem is reproduced with the smallest possible amount of test data. +5. **Include your OS and OS version.** +6. **Include the output of `vim --version`.** + + +Creating good pull requests +=========================== + +1. **Follow the code style of the existing codebase.** + - The Python code **DOES NOT** follow PEP 8. This is not an oversight, this + is by choice. You can dislike this as much as you want, but you still need + to follow the existing style. Look at other Python files to see what the + style is. + - The C++ code has an automated formatter (`style_format.sh` that runs + `astyle`) but it's not perfect. Again, look at the other C++ files and + match the code style you see. + - Same thing for VimScript. Match the style of the existing code. + +2. **Your code needs to be well written and easy to maintain**. This is of the + _utmost_ importance. Other people will have to maintain your code so don't + just throw stuff against the wall until things kinda work. + +3. **Split your pull request into several smaller ones if possible.** This + makes it easier to review your changes, which means they will be merged + faster. + +4. **Write tests for your code**. If you're changing the VimScript code then + you don't have to since it's hard to test that code. This is also why you + should strive to implement your change in Python if at all possible (and if + it makes sense to do so). Python is also _much_ faster than VimScript. + +5. **Explain in detail why your pull request makes sense.** Ask yourself, would + this feature be helpful to others? Not just a few people, but a lot of YCM’s + users? See, good features are useful to many. If your feature is only useful + to you and _maybe_ a couple of others, then that’s not a good feature. + There is such a thing as “feature overload”. When software accumulates so + many features of which most are only useful to a handful, then that software + has become “bloated”. We don’t want that. + + Requests for features that are obscure or are helpful to but a few, or are + not part of YCM's "vision" will be rejected. Yes, even if you provide a + patch that completely implements it. + + Please include details on exactly what you would like to see, and why. The + why is important - it's not always clear why a feature is really useful. And + sometimes what you want can be done in a different way if the reason for the + change is known. _What goal is your change trying to accomplish?_ + + +[build-bots]: https://travis-ci.org/Valloric/YouCompleteMe +[ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users diff --git a/vim/bundle/YouCompleteMe/COPYING.txt b/vim/bundle/YouCompleteMe/COPYING.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/vim/bundle/YouCompleteMe/COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <http://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<http://www.gnu.org/licenses/>. + + 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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/vim/bundle/YouCompleteMe/README.md b/vim/bundle/YouCompleteMe/README.md new file mode 100644 index 0000000..fb8a9e7 --- /dev/null +++ b/vim/bundle/YouCompleteMe/README.md @@ -0,0 +1,2920 @@ +YouCompleteMe: a code-completion engine for Vim +=============================================== + +[![Build Status](https://travis-ci.org/Valloric/YouCompleteMe.svg?branch=master)](https://travis-ci.org/Valloric/YouCompleteMe) +[![Build status](https://ci.appveyor.com/api/projects/status/ag9uqwi8s6btwjd8/branch/master?svg=true)](https://ci.appveyor.com/project/Valloric/YouCompleteMe) + +- [Intro](#intro) +- [Installation](#installation) + - [Mac OS X](#mac-os-x) + - [Ubuntu Linux x64](#ubuntu-linux-x64) + - [Fedora Linux x64](#fedora-linux-x64) + - [Windows](#windows) + - [FreeBSD/OpenBSD](#freebsdopenbsd) + - [Full Installation Guide](#full-installation-guide) +- [Quick Feature Summary](#quick-feature-summary) +- [User Guide](#user-guide) + - [General Usage](#general-usage) + - [Client-Server Architecture](#client-server-architecture) + - [Completion String Ranking](#completion-string-ranking) + - [General Semantic Completion](#general-semantic-completion) + - [C-family Semantic Completion](#c-family-semantic-completion) + - [JavaScript Semantic Completion](#javascript-semantic-completion) + - [Rust Semantic Completion](#rust-semantic-completion) + - [Python Semantic Completion](#python-semantic-completion) + - [Semantic Completion for Other Languages](#semantic-completion-for-other-languages) + - [Writing New Semantic Completers](#writing-new-semantic-completers) + - [Diagnostic Display](#diagnostic-display) + - [Diagnostic Highlighting Groups](#diagnostic-highlighting-groups) +- [Commands](#commands) + - [YcmCompleter subcommands](#ycmcompleter-subcommands) + - [GoTo Commands](#goto-commands) + - [Semantic Information Commands](#semantic-information-commands) + - [Refactoring and FixIt Commands](#refactoring-and-fixit-commands) + - [Miscellaneous Commands](#miscellaneous-commands) +- [Functions](#functions) +- [Autocommands](#autocommands) +- [Options](#options) +- [FAQ](#faq) +- [Contributor Code of Conduct](#contributor-code-of-conduct) +- [Contact](#contact) +- [License](#license) + +Intro +----- + +YouCompleteMe is a fast, as-you-type, fuzzy-search code completion engine for +[Vim][]. It has several completion engines: + +- an identifier-based engine that works with every programming language, +- a [Clang][]-based engine that provides native semantic code + completion for C/C++/Objective-C/Objective-C++ (from now on referred to as + "the C-family languages"), +- a [Jedi][]-based completion engine for Python 2 and 3 (using the [JediHTTP][] wrapper), +- an [OmniSharp][]-based completion engine for C#, +- a combination of [Gocode][] and [Godef][] semantic engines for Go, +- a [TSServer][]-based completion engine for TypeScript, +- a [Tern][]-based completion engine for JavaScript, +- a [racer][]-based completion engine for Rust, +- and an omnifunc-based completer that uses data from Vim's omnicomplete system + to provide semantic completions for many other languages (Ruby, PHP etc.). + +![YouCompleteMe GIF demo](http://i.imgur.com/0OP4ood.gif) + +Here's an explanation of what happens in the short GIF demo above. + +First, realize that **no keyboard shortcuts had to be pressed** to get the list +of completion candidates at any point in the demo. The user just types and the +suggestions pop up by themselves. If the user doesn't find the completion +suggestions relevant and/or just wants to type, they can do so; the completion +engine will not interfere. + +When the user sees a useful completion string being offered, they press the TAB +key to accept it. This inserts the completion string. Repeated presses of the +TAB key cycle through the offered completions. + +If the offered completions are not relevant enough, the user can continue typing +to further filter out unwanted completions. + +A critical thing to notice is that the completion **filtering is NOT based on +the input being a string prefix of the completion** (but that works too). The +input needs to be a _[subsequence][] match_ of a completion. This is a fancy way +of saying that any input characters need to be present in a completion string in +the order in which they appear in the input. So `abc` is a subsequence of +`xaybgc`, but not of `xbyxaxxc`. After the filter, a complicated sorting system +ranks the completion strings so that the most relevant ones rise to the top of +the menu (so you usually need to press TAB just once). + +**All of the above works with any programming language** because of the +identifier-based completion engine. It collects all of the identifiers in the +current file and other files you visit (and your tags files) and searches them +when you type (identifiers are put into per-filetype groups). + +The demo also shows the semantic engine in use. When the user presses `.`, `->` +or `::` while typing in insert mode (for C++; different triggers are used for +other languages), the semantic engine is triggered (it can also be triggered +with a keyboard shortcut; see the rest of the docs). + +The last thing that you can see in the demo is YCM's diagnostic display features +(the little red X that shows up in the left gutter; inspired by [Syntastic][]) +if you are editing a C-family file. As Clang compiles your file and detects +warnings or errors, they will be presented in various ways. You don't need to +save your file or press any keyboard shortcut to trigger this, it "just happens" +in the background. + +In essence, YCM obsoletes the following Vim plugins because it has all of their +features plus extra: + +- clang_complete +- AutoComplPop +- Supertab +- neocomplcache + +**And that's not all...** + +YCM also provides [semantic IDE-like features](#quick-feature-summary) in a +number of languages, including: + +- finding declarations, definitions, usages, etc. of identifiers, +- displaying type information for classes, variables, functions etc., +- displaying documentation for methods, members, etc. in the preview window, +- fixing common coding errors, like missing semi-colons, typos, etc., +- semantic renaming of variables across files (JavaScript only). + +Features vary by file type, so make sure to check out the [file type feature +summary](#quick-feature-summary) and the +[full list of completer subcommands](#ycmcompleter-subcommands) to +find out what's available for your favourite languages. + +You'll also find that YCM has filepath completers (try typing `./` in a file) +and a completer that integrates with [UltiSnips][]. + +Installation +------------ + +### Mac OS X + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Install the latest version of [MacVim][]. Yes, MacVim. And yes, the _latest_. + +If you don't use the MacVim GUI, it is recommended to use the Vim binary that is +inside the MacVim.app package (`MacVim.app/Contents/MacOS/Vim`). To ensure it +works correctly copy the `mvim` script from the [MacVim][] download to your +local binary folder (for example `/usr/local/bin/mvim`) and then symlink it: + + ln -s /usr/local/bin/mvim vim + +Install YouCompleteMe with [Vundle][]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +**NOTE:** If you want C-family completion, you MUST have the latest Xcode +installed along with the latest Command Line Tools (they are installed +automatically when you run `clang` for the first time, or manually by running +`xcode-select --install`) + +Install CMake. Preferably with [Homebrew][brew], but here's the [stand-alone +CMake installer][cmake-download]. + +_If_ you have installed a Homebrew Python and/or Homebrew MacVim, see the _FAQ_ +for details. + +Compiling YCM **with** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer + +Compiling YCM **without** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py + +The following additional language support options are available: + +- C# support: install Mono with [Homebrew][brew] or by downloading the [Mono Mac + package][mono-install-osx] and add `--omnisharp-completer` when calling + `./install.py`. +- Go support: install [Go][go-install] and add `--gocode-completer` when calling + `./install.py`. +- TypeScript support: install [Node.js and npm][npm-install] then install the + TypeScript SDK with `npm install -g typescript`. +- JavaScript support: install [Node.js and npm][npm-install] and add + `--tern-completer` when calling `./install.py`. +- Rust support: install [Rust][rust-install] and add + `--racer-completer` when calling `./install.py`. + +To simply compile with everything enabled, there's a `--all` flag. So, to +install with all language features, ensure `xbuild`, `go`, `tsserver`, `node`, +`npm`, `rustc`, and `cargo` tools are installed and in your `PATH`, then +simply run: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +### Ubuntu Linux x64 + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Make sure you have Vim 7.3.598 with python2 or python3 support. Ubuntu 14.04 and +later have a Vim that's recent enough. You can see the version of Vim installed +by running `vim --version`. If the version is too old, you may need to [compile +Vim from source][vim-build] (don't worry, it's easy). + +Install YouCompleteMe with [Vundle][]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +Install development tools and CMake: `sudo apt-get install build-essential cmake` + +Make sure you have Python headers installed: `sudo apt-get install python-dev +python3-dev`. + +Compiling YCM **with** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer + +Compiling YCM **without** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py + +The following additional language support options are available: + +- C# support: install [Mono][mono-install-ubuntu] and add `--omnisharp-completer` + when calling `./install.py`. +- Go support: install [Go][go-install] and add `--gocode-completer` when calling + `./install.py`. +- TypeScript support: install [Node.js and npm][npm-install] then install the + TypeScript SDK with `npm install -g typescript`. +- JavaScript support: install [Node.js and npm][npm-install] and add + `--tern-completer` when calling `./install.py`. +- Rust support: install [Rust][rust-install] and add `--racer-completer` when + calling `./install.py`. + +To simply compile with everything enabled, there's a `--all` flag. So, to +install with all language features, ensure `xbuild`, `go`, `tsserver`, `node`, +`npm`, `rustc`, and `cargo` tools are installed and in your `PATH`, then +simply run: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +### Fedora Linux x64 + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Make sure you have Vim 7.3.598 with Python 2 or Python 3 support. Fedora 21 and +later have a Vim that's recent enough. You can see the version of Vim installed +by running `vim --version`. If the version is too old, you may need to [compile +Vim from source][vim-build] (don't worry, it's easy). + +Install YouCompleteMe with [Vundle][]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +Install development tools and CMake: `sudo dnf install automake gcc gcc-c++ kernel-devel cmake` + +Make sure you have Python headers installed: `sudo dnf install python-devel +python3-devel`. + +Compiling YCM **with** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer + +Compiling YCM **without** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py + +The following additional language support options are available: + +- C# support: install [Mono][mono-install-fedora] and add `--omnisharp-completer` + when calling `./install.py`. +- Go support: install [Go][go-install] and add `--gocode-completer` when calling + `./install.py`. +- TypeScript support: install [Node.js and npm][npm-install] then install the + TypeScript SDK with `npm install -g typescript`. +- JavaScript support: install [Node.js and npm][npm-install] and add + `--tern-completer` when calling `./install.py`. +- Rust support: install [Rust][rust-install] and add `--racer-completer` when + calling `./install.py`. + +To simply compile with everything enabled, there's a `--all` flag. So, to +install with all language features, ensure `xbuild`, `go`, `tsserver`, `node`, +`npm`, `rustc`, and `cargo` tools are installed and in your `PATH`, then +simply run: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +### Windows + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +**Important:** we assume that you are using the `cmd.exe` command prompt and +that you know how to add an executable to the PATH environment variable. + +Make sure you have at least Vim 7.3.598 with Python 2 or Python 3 support. You +can check the version and which Python is supported by typing `:version` inside +Vim. Look at the features included: `+python/dyn` for Python 2 and +`+python3/dyn` for Python 3. Take note of the Vim architecture, i.e. 32 or +64-bit. It will be important when choosing the Python installer. We recommend +using a 64-bit client. [Daily updated copies of 32-bit and 64-bit Vim with +Python 2 and Python 3 support][vim-win-download] are available. + +Install YouCompleteMe with [Vundle][]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +Download and install the following software: + +- [Python 2 or Python 3][python-win-download]. Be sure to pick the version +corresponding to your Vim architecture. It is _Windows x86_ for a 32-bit Vim and +_Windows x86-64_ for a 64-bit Vim. We recommend installing Python 3. +- [CMake][cmake-download]. Add CMake executable to the PATH environment +variable. +- [Visual Studio][visual-studio-download]. Download the community edition. +During setup, choose _Custom_ as the installation type and select the _Visual +C++_ component. +- [7-zip][7z-download]. Required to build YCM with semantic support for +C-family languages. + +Compiling YCM **with** semantic support for C-family languages: + + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + install.py --clang-completer + +Compiling YCM **without** semantic support for C-family languages: + + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + install.py + +The following additional language support options are available: + +- C# support: add `--omnisharp-completer` when calling `install.py`. + Be sure that [the build utility `msbuild` is in your PATH][add-msbuild-to-path]. +- Go support: install [Go][go-install] and add `--gocode-completer` when calling + `install.py`. +- TypeScript support: install [Node.js and npm][npm-install] then install the + TypeScript SDK with `npm install -g typescript`. +- JavaScript support: install [Node.js and npm][npm-install] and add + `--tern-completer` when calling `install.py`. +- Rust support: install [Rust][rust-install] and add `--racer-completer` when + calling `install.py`. + +To simply compile with everything enabled, there's a `--all` flag. So, to +install with all language features, ensure `msbuild`, `go`, `tsserver`, `node`, +`npm`, and `cargo` tools are installed and in your `PATH`, then simply run: + + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + python install.py --all + +You can specify the Microsoft Visual C++ (MSVC) version using the `--msvc` +option. YCM officially supports MSVC 11 (Visual Studio 2012), 12 (2013), and 14 +(2015). + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +### FreeBSD/OpenBSD + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. OpenBSD / FreeBSD are +not officially supported platforms by YCM. + +Make sure you have Vim 7.3.598 with Python 2 or Python 3 support. + +OpenBSD 5.5 and later have a Vim that's recent enough. You can see the version of +Vim installed by running `vim --version`. + +FreeBSD 10.x comes with clang compiler but not the libraries needed to install. + + pkg install llvm35 boost-all boost-python-libs clang35 + export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/llvm35/lib/ + +Install YouCompleteMe with [Vundle][]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +Install dependencies and CMake: `sudo pkg_add llvm boost cmake` + +Compiling YCM **with** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer --system-libclang --system-boost + +Compiling YCM **without** semantic support for C-family languages: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --system-boost + +The following additional language support options are available: + +- C# support: install Mono and add `--omnisharp-completer` when calling + `./install.py`. +- Go support: install [Go][go-install] and add `--gocode-completer` when calling + `./install.py`. +- TypeScript support: install [Node.js and npm][npm-install] then install the + TypeScript SDK with `npm install -g typescript`. +- JavaScript support: install [Node.js and npm][npm-install] and add + `--tern-completer` when calling `./install.py`. +- Rust support: install [Rust][rust-install] and add `--racer-completer` when + calling `./install.py`. + +To simply compile with everything enabled, there's a `--all` flag. So, to +install with all language features, ensure `xbuild`, `go`, `tsserver`, `node`, +`npm`, and `cargo` tools are installed and in your `PATH`, then simply run: + + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +### Full Installation Guide + +These are the steps necessary to get YCM working on a Unix OS and on Windows. + +**Note to Windows users:** we assume that you are running the `cmd.exe` command +prompt and that the needed executables are in the PATH environment variable. Do +not just copy the shell commands. Replace `~` by `%USERPROFILE%` in them and use +the right Vim home directory. It should be `vimfiles` by default instead of +`.vim`. + +See the _FAQ_ if you have any issues. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens +rarely), YCM will notify you to recompile it. You should then rerun the install +process. + +**Please follow the instructions carefully. Read EVERY WORD.** + +1. **Ensure that your version of Vim is _at least_ 7.3.598 _and_ that it has + support for Python 2 or Python 3 scripting**. + + Inside Vim, type `:version`. Look at the first two to three lines of output; + it should say `Vi IMproved X.Y`, where X.Y is the major version of vim. If + your version is greater than 7.3, then you're all set. If your version is + 7.3 then look below that where it says, `Included patches: 1-Z`, where Z + will be some number. That number needs to be 598 or higher. + + If your version of Vim is not recent enough, you may need to [compile Vim + from source][vim-build] (don't worry, it's easy). + + After you have made sure that you have Vim 7.3.598+, type the following in + Vim: `:echo has('python') || has('python3')`. The output should be 1. If + it's 0, then get a version of Vim with Python support. + + On Windows, check also if your Vim architecture is 32 or 64-bit. This is + critical because it must match the Python and the YCM libraries + architectures. We recommend using a 64-bit Vim. + +2. **Install YCM** with [Vundle][] (or [Pathogen][], but Vundle is a better + idea). With Vundle, this would mean adding a `Plugin + 'Valloric/YouCompleteMe'` line to your [vimrc][]. + + If you don't install YCM with Vundle, make sure you have run + `git submodule update --init --recursive` after checking out the YCM + repository (Vundle will do this for you) to fetch YCM's dependencies. + +3. [Complete this step ONLY if you care about semantic completion support for + C-family languages. Otherwise it's not necessary.] + + **Download the latest version of `libclang`**. Clang is an open-source + compiler that can compile C/C++/Objective-C/Objective-C++. The `libclang` + library it provides is used to power the YCM semantic completion engine for + those languages. YCM is designed to work with libclang version 3.8 or + higher. + + You can use the system libclang _only if you are sure it is version 3.8 or + higher_, otherwise don't. Even if it is, we recommend using the [official + binaries from llvm.org][clang-download] if at all possible. Make sure you + download the correct archive file for your OS. + + We **STRONGLY recommend AGAINST use** of the system libclang instead of + the upstream compiled binaries. Random things may break. Save yourself the + hassle and use the upstream pre-built libclang. + +4. **Compile the `ycm_core` library** that YCM needs. This library + is the C++ engine that YCM uses to get fast completions. + + You will need to have `cmake` installed in order to generate the required + makefiles. Linux users can install cmake with their package manager (`sudo + apt-get install cmake` for Ubuntu) whereas other users can [download and + install][cmake-download] cmake from its project site. Mac users can also get + it through [Homebrew][brew] with `brew install cmake`. + + On a Unix OS, you need to make sure you have Python headers installed. On a + Debian-like Linux distro, this would be `sudo apt-get install python-dev + python3-dev`. On Mac they should already be present. + + On Windows, you need to download and install [Python 2 or + Python 3][python-win-download]. Pick the version corresponding to your Vim + architecture. You will also need Microsoft Visual C++ (MSVC) to build YCM. + You can obtain it by installing [Visual Studio][visual-studio-download]. + MSVC 11 (Visual Studio 2012), 12 (2013), and 14 (2015) are officially + supported. + + Here we'll assume you installed YCM with Vundle. That means that the + top-level YCM directory is in `~/.vim/bundle/YouCompleteMe`. + + We'll create a new folder where build files will be placed. Run the + following: + + cd ~ + mkdir ycm_build + cd ycm_build + + Now we need to generate the makefiles. If you DON'T care about semantic + support for C-family languages, run the following command in the `ycm_build` + directory: + + cmake -G "<generator>" . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp + + where `<generator>` is `Unix Makefiles` on Unix systems and one of the + following Visual Studio generators on Windows: + + - `Visual Studio 11 Win64` + - `Visual Studio 12 Win64` + - `Visual Studio 14 Win64` + + Remove the `Win64` part in these generators if your Vim architecture is + 32-bit. + + For those who want to use the system version of boost, you would pass + `-DUSE_SYSTEM_BOOST=ON` to cmake. This may be necessary on some systems + where the bundled version of boost doesn't compile out of the box. + + NOTE: We **STRONGLY recommend AGAINST use** of the system boost instead + of the bundled version of boost. Random things may break. Save yourself + the hassle and use the bundled version of boost. + + If you DO care about semantic support for C-family languages, then your + `cmake` call will be a bit more complicated. We'll assume you downloaded a + binary distribution of LLVM+Clang from llvm.org in step 3 and that you + extracted the archive file to folder `~/ycm_temp/llvm_root_dir` (with `bin`, + `lib`, `include` etc. folders right inside that folder). On Windows, you can + extract the files from the LLVM+Clang installer using [7-zip][7z-download]. + + NOTE: This _only_ works with a _downloaded_ LLVM binary package, not a + custom-built LLVM! See docs below for `EXTERNAL_LIBCLANG_PATH` when using a + custom LLVM build. + + With that in mind, run the following command in the `ycm_build` directory: + + cmake -G "<generator>" -DPATH_TO_LLVM_ROOT=~/ycm_temp/llvm_root_dir . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp + + where `<generator>` is replaced like above. + + Now that configuration files have been generated, compile the libraries + using this command: + + cmake --build . --target ycm_core --config Release + + The `--config Release` part is specific to Windows and will be ignored on a + Unix OS. + + For those who want to use the system version of libclang, you would pass + `-DUSE_SYSTEM_LIBCLANG=ON` to cmake _instead of_ the + `-DPATH_TO_LLVM_ROOT=...` flag. + + NOTE: We **STRONGLY recommend AGAINST use** of the system libclang instead + of the upstream compiled binaries. Random things may break. Save yourself + the hassle and use the upstream pre-built libclang. + + You could also force the use of a custom libclang library with + `-DEXTERNAL_LIBCLANG_PATH=/path/to/libclang.so` flag (the library would end + with `.dylib` on a Mac). Again, this flag would be used _instead of_ the + other flags. **If you compiled LLVM from source, this is the flag you should + be using.** + + Running the `cmake` command will also place the `libclang.[so|dylib|dll]` in + the `YouCompleteMe/third_party/ycmd` folder for you if you compiled with + clang support (it needs to be there for YCM to work). + +5. Set up support for additional languages, as desired: + + - C# support: install [Mono on non-Windows platforms][mono-install]. Navigate + to `YouCompleteMe/third_party/ycmd/third_party/OmniSharpServer` and run + `msbuild` (Windows) or `xbuild` (other platforms, using Mono) depending on + your platform. On Windows, be sure that [the build utility `msbuild` is in + your PATH][add-msbuild-to-path]. + + - Go support: install [Go][go-install] and add it to your path. Navigate to + `YouCompleteMe/third_party/ycmd/third_party/gocode` and run `go build`. + + - TypeScript support: as with the quick installation, simply `npm install -g + typescript` after successfully installing [Node.js and npm][npm-install]. + + - JavaScript support: install [Node.js and npm][npm-install]. Then navigate to + `YouCompleteMe/third_party/ycmd/third_party/tern_runtime` and run `npm install + --production` + + - Rust support: install [Rust][rust-install]. Navigate to + `YouCompleteMe/third_party/ycmd/third_party/racerd` and run + `cargo build --release`. + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's all +in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +Quick Feature Summary +----- + +### General (all languages) + +* Super-fast identifier completer including tags files and syntax elements +* Intelligent suggestion ranking and filtering +* File and path suggestions +* Suggestions from Vim's OmniFunc +* UltiSnips snippet suggestions + +### C-family languages (C, C++, Objective C, Objective C++) + +* Semantic auto-completion +* Real-time diagnostic display +* Go to include/declaration/definition (`GoTo`, etc.) +* Semantic type information for identifiers (`GetType`) +* Automatically fix certain errors (`FixIt`) +* View documentation comments for identifiers (`GetDoc`) + +### C♯ + +* Semantic auto-completion +* Real-time diagnostic display +* Go to declaration/definition (`GoTo`, etc.) +* Semantic type information for identifiers (`GetType`) +* Automatically fix certain errors (`FixIt`) +* Management of OmniSharp server instance +* View documentation comments for identifiers (`GetDoc`) + +### Python + +* Intelligent auto-completion +* Go to declaration/definition, find references (`GoTo`, `GoToReferences`) +* View documentation comments for identifiers (`GetDoc`) +* Restart [JediHTTP][] server using a different Python interpreter + +### Go + +* Semantic auto-completion +* Go to definition (`GoTo`) +* Management of `gocode` server instance + +### TypeScript + +* Semantic auto-completion +* Renaming symbols (`RefactorRename <new name>`) +* Go to definition, find references (`GoToDefinition`, `GoToReferences`) +* Semantic type information for identifiers (`GetType`) +* View documentation comments for identifiers (`GetDoc`) + +### JavaScript + +* Intelligent auto-completion +* Renaming variables (`RefactorRename <new name>`) +* Go to definition, find references (`GoToDefinition`, `GoToReferences`) +* Type information for identifiers (`GetType`) +* View documentation comments for identifiers (`GetDoc`) +* Management of `Tern` server instance + +### Rust + +* Semantic auto-completion +* Go to definition (`GoTo`, `GoToDefinition`, and `GoToDeclaration` are + identical) +* Management of `racer` server instance + +User Guide +---------- + +### General Usage + +- If the offered completions are too broad, keep typing characters; YCM will + continue refining the offered completions based on your input. +- Filtering is "smart-case" sensitive; if you are typing only lowercase letters, + then it's case-insensitive. If your input contains uppercase letters, then the + uppercase letters in your query must match uppercase letters in the completion + strings (the lowercase letters still match both). So, "foo" matches "Foo" and + "foo", "Foo" matches "Foo" and "FOO" but not "foo". +- Use the TAB key to accept a completion and continue pressing TAB to cycle + through the completions. Use Shift-TAB to cycle backwards. Note that if you're + using console Vim (that is, not Gvim or MacVim) then it's likely that the + Shift-TAB binding will not work because the console will not pass it to Vim. + You can remap the keys; see the _[Options][]_ section below. + +Knowing a little bit about how YCM works internally will prevent confusion. YCM +has several completion engines: an identifier-based completer that collects all +of the identifiers in the current file and other files you visit (and your tags +files) and searches them when you type (identifiers are put into per-filetype +groups). + +There are also several semantic engines in YCM. There's a libclang-based +completer that provides semantic completion for C-family languages. There's a +Jedi-based completer for semantic completion for Python. There's also an +omnifunc-based completer that uses data from Vim's omnicomplete system to +provide semantic completions when no native completer exists for that language +in YCM. + +There are also other completion engines, like the UltiSnips completer and the +filepath completer. + +YCM automatically detects which completion engine would be the best in any +situation. On occasion, it queries several of them at once, merges the +outputs and presents the results to you. + +### Client-Server Architecture + +YCM has a client-server architecture; the Vim part of YCM is only a thin client +that talks to the [ycmd HTTP+JSON server][ycmd] that has the vast majority of +YCM logic and functionality. The server is started and stopped automatically as +you start and stop Vim. + +### Completion String Ranking + +The subsequence filter removes any completions that do not match the input, but +then the sorting system kicks in. It's actually very complicated and uses lots +of factors, but suffice it to say that "word boundary" (WB) subsequence +character matches are "worth" more than non-WB matches. In effect, this means +given an input of "gua", the completion "getUserAccount" would be ranked higher +in the list than the "Fooguxa" completion (both of which are subsequence +matches). A word-boundary character are all capital characters, characters +preceded by an underscore and the first letter character in the completion +string. + +### General Semantic Completion + +- You can use Ctrl+Space to trigger the completion suggestions anywhere, even + without a string prefix. This is useful to see which top-level functions are + available for use. + +### C-family Semantic Completion + +YCM looks for a `.ycm_extra_conf.py` file in the directory of the opened file or +in any directory above it in the hierarchy (recursively); when the file is +found, it is loaded (only once!) as a Python module. YCM calls a `FlagsForFile` +method in that module which should provide it with the information necessary to +compile the current file. You can also provide a path to a global +`.ycm_extra_conf.py` file, which will be used as a fallback. To prevent the +execution of malicious code from a file you didn't write YCM will ask you once +per `.ycm_extra_conf.py` if it is safe to load. This can be disabled and you can +white-/blacklist files. See the _Options_ section for more details. + +This system was designed this way so that the user can perform any arbitrary +sequence of operations to produce a list of compilation flags YCM should hand +to Clang. + +[See YCM's own `.ycm_extra_conf.py`][flags_example] for details on how this +works. You should be able to use it _as a starting point_. **Don't** just +copy/paste that file somewhere and expect things to magically work; **your project +needs different flags**. Hint: just replace the strings in the `flags` variable +with compilation flags necessary for your project. That should be enough for 99% +of projects. + +Yes, [Clang's `CompilationDatabase` system][compdb] is also supported. Again, +see the above linked example file. You can get CMake to generate this file for +you by adding `set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )` to your project's +`CMakeLists.txt` file (if using CMake). If you're not using CMake, you could use +something like [Bear][] to generate the `compile_commands.json` file. + +Consider using [YCM-Generator][ygen] to generate the `ycm_extra_conf.py` file. + +If Clang encounters errors when compiling the header files that your file +includes, then it's probably going to take a long time to get completions. When +the completion menu finally appears, it's going to have a large number of +unrelated completion strings (type/function names that are not actually +members). This is because Clang fails to build a precompiled preamble for your +file if there are any errors in the included headers and that preamble is key to +getting fast completions. + +Call the `:YcmDiags` command to see if any errors or warnings were detected in +your file. + +### JavaScript Semantic Completion + +#### Quick start + +1. Ensure that you have enabled the Tern completer. See the + [installation guide](#installation) for details. + +2. Create a `.tern-project` file in the root directory of your JavaScript + project, by following the [instructions][tern-project] in the [Tern][] + documentation. + +3. Make sure that Vim's working directory is a descendent of that directory (or + that directory itself) when working with JavaScript files. + +#### Explanation + +JavaScript completion is based on [Tern][]. This completion engine requires a +file named [`.tern-project`][tern-project] to exist in the current working +directory or a directory which is an ancestor of the current working directory +when the tern server is started. YCM starts the Tern server the first time a +JavaScript file is edited, so Vim's working directory at that time needs to be a +descendent of the directory containing the `.tern-project` file (or that +directory itself). + +Alternatively, as described in the [Tern documentation][tern-docs], a global +`.tern-config` file may be used. + +Multiple Tern servers, are not supported. To switch to a different +JavaScript project, you can do one of the following: + +- start a new instance of Vim from the new project's directory +- change Vim's working directory (`:cd /path/to/new/project`) and restart the + [ycmd server][ycmd] (`:YcmRestartServer`) +- change Vim's working directory (`:cd /path/to/new/project`), open a JavaScript + file (or set filetype to JavaScript) and restart the Tern server using YCM + completer subcommands `:YcmCompleter StopServer` and `:YcmCompleter + StartServer`. + +#### Tips and tricks + +This section contains some advice for configuring `.tern-project` and working +with JavaScript files. The canonical reference for correctly configuring Tern is +the [Tern documentation][tern-docs]. Any issues, improvements, advice, etc. +should be sought from the [Tern][] project. For example, see the [list of tern +plugins](http://ternjs.net/doc/manual.html#plugins) for the list of plugins +which can be enabled in the `plugins` section of the `.tern-project` file. + +##### Configuring Tern for node support + +The following simple example `.tern-project` file enables nodejs support: + +```json +{ + "plugins": { + "node": {} + } +} + +``` + +##### Configuring Tern for requirejs support + +The Tern requirejs plugin requires that all included "libraries" are rooted +under the same base directory. If that's not the case for your projects, then it +is possible to make it work with appropriate symbolic links. For example, create +a directory `ext_lib` within your project and populate it with symlinks to your +libraries. Then set up the `.tern-project` something like this: + +```json + +{ + "plugins": { + "requirejs": { + "baseURL": "./ext_lib", + } + } +} +``` + +Then, given the following structure: + +``` +./ext_lib/mylib (symlink) +./ext_lib/anotherlib (symlink) +``` + +Can be used as follows: + +```javascript +define( [ 'mylib/file1', 'anotherlib/anotherfile' ], function( f1, f2 ) { + // etc. +} ); +``` + +### Rust Semantic Completion + +Completions and GoTo commands within the current crate and its dependencies +should work out of the box with no additional configuration (provided that you +built YCM with the `--racer-completer` flag; see the [*Installation* +section](#installation) for details). For semantic analysis inclusive of the +standard library, you must have a local copy of [the rust source +code][rust-src]. You also need to set the following option so YouCompleteMe can +locate it. + +```viml +" In this example, the rust source code zip has been extracted to +" /usr/local/rust/rustc-1.5.0 +let g:ycm_rust_src_path = '/usr/local/rust/rustc-1.5.0/src' +``` + +### Python Semantic Completion + +Completion and GoTo commands work out of the box with no additional +configuration. Those features are provided by the [jedi][] library which +supports a variety of Python versions (2.6, 2.7, 3.2+) as long as it +runs in the corresponding Python interpreter. By default YCM runs [jedi][] with +the same Python interpreter used by the [ycmd server][ycmd], so if you would like to +use a different interpreter, use the following option specifying the Python +binary to use. For example, to provide Python 3 completion in your project, set: + +```viml +let g:ycm_python_binary_path = '/usr/bin/python3' +``` + +If the value of `g:ycm_python_binary_path` is an absolute path like above it +will be used as-is, but if it's an executable name it will be searched through +the PATH. So for example if you set: + +```viml +let g:ycm_python_binary_path = 'python' +``` + +YCM will use the first `python` executable it finds in the PATH to run +[jedi][]. This means that if you are in a virtual environment and you start vim +in that directory, the first `python` that YCM will find will be the one in the +virtual environment, so [jedi][] will be able to provide completions for every +package you have in the virtual environment. + +### Semantic Completion for Other Languages + +Python, C#, Go, Rust, and TypeScript are supported natively by YouCompleteMe +using the [Jedi][], [Omnisharp][], [Gocode][], [racer][], and [TSServer][] +engines, respectively. Check the [installation](#installation) section for +instructions to enable these features if desired. + +YCM will use your `omnifunc` (see `:h omnifunc` in Vim) as a source for semantic +completions if it does not have a native semantic completion engine for your +file's filetype. Vim comes with okayish omnifuncs for various languages like +Ruby, PHP etc. It depends on the language. + +You can get stellar omnifuncs for Java and Ruby with [Eclim][]. Just make sure +you have the _latest_ Eclim installed and configured (this means Eclim `>= 2.2.*` +and Eclipse `>= 4.2.*`). + +After installing Eclim remember to create a new Eclipse project within your +application by typing `:ProjectCreate <path-to-your-project> -n ruby` (or `-n java`) +inside vim and don't forget to have `let g:EclimCompletionMethod = 'omnifunc'` +in your vimrc. This will make YCM and Eclim play nice; YCM will use Eclim's omnifuncs +as the data source for semantic completions and provide the auto-triggering +and subsequence-based matching (and other YCM features) on top of it. + +### Writing New Semantic Completers + +You have two options here: writing an `omnifunc` for Vim's omnicomplete system +that YCM will then use through its omni-completer, or a custom completer for YCM +using the [Completer API][completer-api]. + +Here are the differences between the two approaches: + +- You have to use VimScript to write the omnifunc, but get to use Python to + write for the Completer API; this by itself should make you want to use the + API. +- The Completer API is a _much_ more powerful way to integrate with YCM and it + provides a wider set of features. For instance, you can make your Completer + query your semantic back-end in an asynchronous fashion, thus not blocking + Vim's GUI thread while your completion system is processing stuff. This is + impossible with VimScript. All of YCM's completers use the Completer API. +- Performance with the Completer API is better since Python executes faster than + VimScript. + +If you want to use the `omnifunc` system, see the relevant Vim docs with `:h +complete-functions`. For the Completer API, see [the API docs][completer-api]. + +If you want to upstream your completer into YCM's source, you should use the +Completer API. + +### Diagnostic Display + +YCM will display diagnostic notifications for C-family and C# languages if you +compiled YCM with Clang and Omnisharp support, respectively. Since YCM continuously +recompiles your file as you type, you'll get notified of errors and warnings +in your file as fast as possible. + +Here are the various pieces of the diagnostic UI: + +- Icons show up in the Vim gutter on lines that have a diagnostic. +- Regions of text related to diagnostics are highlighted (by default, a red + wavy underline in `gvim` and a red background in `vim`). +- Moving the cursor to a line with a diagnostic echoes the diagnostic text. +- Vim's location list is automatically populated with diagnostic data (off by + default, see options). + +The new diagnostics (if any) will be displayed the next time you press any key +on the keyboard. So if you stop typing and just wait for the new diagnostics to +come in, that _will not work_. You need to press some key for the GUI to update. + +Having to press a key to get the updates is unfortunate, but cannot be changed +due to the way Vim internals operate; there is no way that a background task can +update Vim's GUI after it has finished running. You _have to_ press a key. This +will make YCM check for any pending diagnostics updates. + +You _can_ force a full, blocking compilation cycle with the +`:YcmForceCompileAndDiagnostics` command (you may want to map that command to a +key; try putting `nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>` in your +vimrc). Calling this command will force YCM to immediately recompile your file +and display any new diagnostics it encounters. Do note that recompilation with +this command may take a while and during this time the Vim GUI _will_ be +blocked. + +YCM will display a short diagnostic message when you move your cursor to the +line with the error. You can get a detailed diagnostic message with the +`<leader>d` key mapping (can be changed in the options) YCM provides when your +cursor is on the line with the diagnostic. + +You can also see the full diagnostic message for all the diagnostics in the +current file in Vim's `locationlist`, which can be opened with the `:lopen` and +`:lclose` commands (make sure you have set `let +g:ycm_always_populate_location_list = 1` in your vimrc). A good way to toggle +the display of the `locationlist` with a single key mapping is provided by +another (very small) Vim plugin called [ListToggle][] (which also makes it +possible to change the height of the `locationlist` window), also written by +yours truly. + +#### Diagnostic Highlighting Groups + +You can change the styling for the highlighting groups YCM uses. For the signs +in the Vim gutter, the relevant groups are: + +- `YcmErrorSign`, which falls back to group `SyntasticErrorSign` and then + `error` if they exist +- `YcmWarningSign`, which falls back to group `SyntasticWarningSign` and then + `todo` if they exist + +You can also style the line that has the warning/error with these groups: + +- `YcmErrorLine`, which falls back to group `SyntasticErrorLine` if it exists +- `YcmWarningLine`, which falls back to group `SyntasticWarningLine` if it + exists + +Note that the line highlighting groups only work when gutter signs are turned +on. + +The syntax groups used to highlight regions of text with errors/warnings: +- `YcmErrorSection`, which falls back to group `SyntasticError` if it exists and + then `SpellBad` +- `YcmWarningSection`, which falls back to group `SyntasticWarning` if it exists + and then `SpellCap` + +Here's how you'd change the style for a group: + +```viml +highlight YcmErrorLine guibg=#3f0000 +``` + +Commands +-------- + +### The `:YcmRestartServer` command + +If the [ycmd completion server][ycmd] suddenly stops for some reason, you can +restart it with this command. + +### The `:YcmForceCompileAndDiagnostics` command + +Calling this command will force YCM to immediately recompile your file +and display any new diagnostics it encounters. Do note that recompilation with +this command may take a while and during this time the Vim GUI _will_ be +blocked. + +You may want to map this command to a key; try putting `nnoremap <F5> +:YcmForceCompileAndDiagnostics<CR>` in your vimrc. + +### The `:YcmDiags` command + +Calling this command will fill Vim's `locationlist` with errors or warnings if +any were detected in your file and then open it. If a given error or warning can +be fixed by a call to `:YcmCompleter FixIt`, then ` (FixIt available)` is +appended to the error or warning text. See the `FixIt` completer subcommand for +more information. + +NOTE: The absense of ` (FixIt available)` does not strictly imply a fix-it is +not available as not all completers are able to provide this indication. For +example, the c-sharp completer provides many fix-its but does not add this +additional indication. + +The `g:ycm_open_loclist_on_ycm_diags` option can be used to prevent the location +list from opening, but still have it filled with new diagnostic data. See the +_Options_ section for details. + +### The `:YcmShowDetailedDiagnostic` command + +This command shows the full diagnostic text when the user's cursor is on the +line with the diagnostic. + +### The `:YcmDebugInfo` command + +This will print out various debug information for the current file. Useful to +see what compile commands will be used for the file if you're using the semantic +completion engine. + +### The `:YcmToggleLogs` command + +This command automatically opens in windows the stdout and stderr logfiles +written by the [ycmd server][ycmd]. If one or both logfiles are already opened, +they are automatically closed. `stderr` or `stdout` can be specified as an +argument of this command to only open the corresponding logfile instead of both. +If this logfile is already opened, it will be closed. Only for debugging +purpose. + +### The `:YcmCompleter` command + +This command gives access to a number of additional [IDE-like +features](#quick-feature-summary) in YCM, for things like semantic GoTo, type +information, FixIt and refactoring. + +Technically the command invokes completer-specific commands. If the first +argument is of the form `ft=...` the completer for that file type will be used +(for example `ft=cpp`), else the native completer of the current buffer will be +used. +Call `YcmCompleter` without further arguments for a list of the +commands you can call for the current completer. + +See the [file type feature summary](#quick-feature-summary) for an overview of +the features available for each file type. See the _YcmCompleter subcommands_ +section for more information on the available subcommands and their usage. + +YcmCompleter Subcommands +------------------------ + +NOTE: See the docs for the `YcmCompleter` command before tackling this section. + +The invoked subcommand is automatically routed to the currently active semantic +completer, so `:YcmCompleter GoToDefinition` will invoke the `GoToDefinition` +subcommand on the Python semantic completer if the currently active file is a +Python one and on the Clang completer if the currently active file is a +C/C++/Objective-C one. + +You may also want to map the subcommands to something less verbose; for +instance, `nnoremap <leader>jd :YcmCompleter GoTo<CR>` +maps the `<leader>jd` sequence to the longer subcommand invocation. + +### GoTo Commands + +These commands are useful for jumping around and exploring code. When moving +the cursor, the subcommands add entries to Vim's `jumplist` so you can use +`CTRL-O` to jump back to where you where before invoking the command (and +`CTRL-I` to jump forward; see `:h jumplist` for details). If there is more +than one destination, the quickfix list (see `:h quickfix`) is populated with +the available locations and opened to full width at the bottom of the screen. +You can change this behavior by using [the `YcmQuickFixOpened` +autocommand](#the-ycmquickfixopened-autocommand). + +#### The `GoToInclude` subcommand + +Looks up the current line for a header and jumps to it. + +Supported in filetypes: `c, cpp, objc, objcpp` + +#### The `GoToDeclaration` subcommand + +Looks up the symbol under the cursor and jumps to its declaration. + +Supported in filetypes: `c, cpp, objc, objcpp, cs, go, python, rust` + +#### The `GoToDefinition` subcommand + +Looks up the symbol under the cursor and jumps to its definition. + +NOTE: For C-family languages **this only works in certain situations**, namely when +the definition of the symbol is in the current translation unit. A translation +unit consists of the file you are editing and all the files you are including +with `#include` directives (directly or indirectly) in that file. + +Supported in filetypes: `c, cpp, objc, objcpp, cs, go, javascript, python, +rust, typescript` + +#### The `GoTo` subcommand + +This command tries to perform the "most sensible" GoTo operation it can. +Currently, this means that it tries to look up the symbol under the cursor and +jumps to its definition if possible; if the definition is not accessible from +the current translation unit, jumps to the symbol's declaration. For +C/C++/Objective-C, it first tries to look up the current line for a header and +jump to it. For C#, implementations are also considered and preferred. + +Supported in filetypes: `c, cpp, objc, objcpp, cs, go, javascript, python, rust` + +#### The `GoToImprecise` subcommand + +WARNING: This command trades correctness for speed! + +Same as the `GoTo` command except that it doesn't recompile the file with +libclang before looking up nodes in the AST. This can be very useful when you're +editing files that take long to compile but you know that you haven't made any +changes since the last parse that would lead to incorrect jumps. When you're +just browsing around your codebase, this command can spare you quite a bit of +latency. + +Supported in filetypes: `c, cpp, objc, objcpp` + +#### The `GoToReferences` subcommand + +This command attempts to find all of the references within the project to the +identifier under the cursor and populates the quickfix list with those +locations. + +Supported in filetypes: `javascript, python, typescript` + +#### The `GoToImplementation` subcommand + +Looks up the symbol under the cursor and jumps to its implementation (i.e. +non-interface). If there are multiple implementations, instead provides a list +of implementations to choose from. + +Supported in filetypes: `cs` + +#### The `GoToImplementationElseDeclaration` subcommand + +Looks up the symbol under the cursor and jumps to its implementation if one, +else jump to its declaration. If there are multiple implementations, instead +provides a list of implementations to choose from. + +Supported in filetypes: `cs` + +### Semantic Information Commands + +These commands are useful for finding static information about the code, such +as the types of variables, viewing declarations and documentation strings. + +#### The `GetType` subcommand + +Echos the type of the variable or method under the cursor, and where it differs, +the derived type. + +For example: + +```c++ + std::string s; +``` + +Invoking this command on `s` returns `std::string => std::basic_string<char>` + +NOTE: Due to limitations of `libclang`, invoking this command on the word +`auto` typically returns `auto`. However, invoking it on a usage of the variable +with inferred type returns the correct type, but typically it is repeated due to +`libclang` returning that the types differ. + +For example: + +```c++ +const char *s = "String"; +auto x = &s; // invoking on x or auto returns "auto"; + // invoking on s returns "const char *" +std::cout << *x; // invoking on x returns "const char ** => const char **" +``` + +NOTE: Causes re-parsing of the current translation unit. + +Supported in filetypes: `c, cpp, objc, objcpp, javascript, typescript` + +#### The `GetParent` subcommand + +Echos the semantic parent of the point under the cursor. + +The semantic parent is the item that semantically contains the given position. + +For example: + +```c++ +class C { + void f(); +}; + +void C::f() { + +} +``` + +In the out-of-line definition of `C::f`, the semantic parent is the class `C`, +of which this function is a member. + +In the example above, both declarations of `C::f` have `C` as their semantic +context, while the lexical context of the first `C::f` is `C` and the lexical +context of the second `C::f` is the translation unit. + +For global declarations, the semantic parent is the translation unit. + +NOTE: Causes re-parsing of the current translation unit. + +Supported in filetypes: `c, cpp, objc, objcpp` + +#### The `GetDoc` subcommand + +Displays the preview window populated with quick info about the identifier +under the cursor. Depending on the file type, this includes things like: + +* The type or declaration of identifier, +* Doxygen/javadoc comments, +* Python docstrings, +* etc. + +Supported in filetypes: `c, cpp, objc, objcpp, cs, python, typescript, +javascript` + +### Refactoring and FixIt Commands + +These commands make changes to your source code in order to perform refactoring +or code correction. YouCompleteMe does not perform any action which cannot be +undone, and never saves or writes files to the disk. + +#### The `FixIt` subcommand + +Where available, attempts to make changes to the buffer to correct the +diagnostic closest to the cursor position. + +Completers which provide diagnostics may also provide trivial modifications to +the source in order to correct the diagnostic. Examples include syntax errors +such as missing trailing semi-colons, spurious characters, or other errors which +the semantic engine can deterministically suggest corrections. + +If no fix-it is available for the current line, or there is no diagnostic on the +current line, this command has no effect on the current buffer. If any +modifications are made, the number of changes made to the buffer is echo'd and +the user may use the editor's undo command to revert. + +When a diagnostic is available, and `g:ycm_echo_current_diagnostic` is set to 1, +then the text ` (FixIt)` is appended to the echo'd diagnostic when the +completer is able to add this indication. The text ` (FixIt available)` is +also appended to the diagnostic text in the output of the `:YcmDiags` command +for any diagnostics with available fix-its (where the completer can provide this +indication). + +NOTE: Causes re-parsing of the current translation unit. + +NOTE: After applying a fix-it, the diagnostics UI is not immediately updated. +This is due to a technical restriction in Vim. Moving the cursor, or issuing +the `:YcmForceCompileAndDiagnostics` command will refresh the diagnostics. +Repeated invocations of the `FixIt` command on a given line, however, _do_ apply +all diagnostics as expected without requiring refreshing of the diagnostics UI. +This is particularly useful where there are multiple diagnostics on one line, or +where after fixing one diagnostic, another fix-it is available. + +Supported in filetypes: `c, cpp, objc, objcpp, cs` + +#### The `RefactorRename <new name>` subcommand + +In supported file types, this command attempts to perform a semantic rename of +the identifier under the cursor. This includes renaming declarations, +definitions and usages of the identifier, or any other language-appropriate +action. The specific behavior is defined by the semantic engine in use. + +Similar to `FixIt`, this command applies automatic modifications to your source +files. Rename operations may involve changes to multiple files, which may or may +not be open in Vim buffers at the time. YouCompleteMe handles all of this for +you. The behavior is described in [the following section](#multi-file-refactor). + +Supported in filetypes: `javascript` (variables only), `typescript` + +#### Multi-file Refactor + +When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts +to apply those modifications to any existing open, visible buffer in the current +tab. If no such buffer can be found, YouCompleteMe opens the file in a new +small horizontal split at the top of the current window, applies the change, +and then *hides* the window. NOTE: The buffer remains open, and must be +manually saved. A confirmation dialog is opened prior to doing this to remind +you that this is about to happen. + +Once the modifications have been made, the quickfix list (see `:help quickfix`) +is opened and populated with the locations of all modifications. This can be +used to review all automatic changes made. Typically, use the `CTRL-W +<enter>` combination to open the selected file in a new split. It is possible +to customize how the quickfix window is opened by using [the `YcmQuickFixOpened` +autocommand](#the-ycmquickfixopened-autocommand). + +The buffers are *not* saved automatically. That is, you must save the modified +buffers manually after reviewing the changes from the quickfix list. Changes +can be undone using Vim's powerful undo features (see `:help undo`). Note +that Vim's undo is per-buffer, so to undo all changes, the undo commands must +be applied in each modified buffer separately. + +NOTE: While applying modifications, Vim may find files which are already open +and have a swap file. The command is aborted if you select Abort or Quit in any +such prompts. This leaves the Refactor operation partially complete and must be +manually corrected using Vim's undo features. The quickfix list is *not* +populated in this case. Inspect `:buffers` or equivalent (see `:help buffers`) +to see the buffers that were opened by the command. + +### Miscellaneous Commands + +These commands are for general administration, rather than IDE-like features. +They cover things like the semantic engine server instance and compilation +flags. + +#### The `ClearCompilationFlagCache` subcommand + +YCM caches the flags it gets from the `FlagsForFile` function in your +`ycm_extra_conf.py` file if you return them with the `do_cache` parameter set to +`True`. The cache is in memory and is never invalidated (unless you restart Vim +of course). + +This command clears that cache entirely. YCM will then re-query your +`FlagsForFile` function as needed in the future. + +Supported in filetypes: `c, cpp, objc, objcpp` + +#### The `StartServer` subcommand + +Starts the semantic-engine-as-localhost-server for those semantic engines that +work as separate servers that YCM talks to. + +Supported in filetypes: `cs, go, javascript, rust` + +#### The `StopServer` subcommand + +Stops the semantic-engine-as-localhost-server for those semantic engines that +work as separate servers that YCM talks to. + +Supported in filetypes: `cs, go, javascript, rust` + +#### The `RestartServer` subcommand + +Restarts the semantic-engine-as-localhost-server for those semantic engines that +work as separate servers that YCM talks to. + +An additional optional argument may be supplied for Python, specifying the +python binary to use to restart the Python semantic engine. + +```viml +:YcmCompleter RestartServer /usr/bin/python3.4 +``` + +Supported in filetypes: `cs, python, rust` + +#### The `ReloadSolution` subcommand + +Instruct the Omnisharp server to clear its cache and reload all files from disk. +This is useful when files are added, removed, or renamed in the solution, files +are changed outside of Vim, or whenever Omnisharp cache is out-of-sync. + +Supported in filetypes: `cs` + +Functions +-------- + +### The `youcompleteme#GetErrorCount` function + +Get the number of YCM Diagnostic errors. If no errors are present, this function +returns 0. + +For example: +```viml + call youcompleteme#GetErrorCount() +``` + +Both this function and `youcompleteme#GetWarningCount` can be useful when +integrating YCM with other Vim plugins. For example, a [lightline][] user could +add a diagnostics section to their statusline which would display the number of +errors and warnings. + +### The `youcompleteme#GetWarningCount` function + +Get the number of YCM Diagnostic warnings. If no warnings are present, this +function returns 0. + +For example: +```viml + call youcompleteme#GetWarningCount() +``` + +Autocommands +------------ + +### The `YcmQuickFixOpened` autocommand + +This `User` autocommand is fired when YCM opens the quickfix window in response +to the `GoTo*` and `RefactorRename` subcommands. By default, the quickfix window +is opened to full width at the bottom of the screen and its height is set to fit +all entries. This behavior can be overridden by using the `YcmQuickFixOpened` +autocommand. For instance: +```viml +function s:CustomizeYcmQuickFixWindow() + " Move the window at the top of the screen. + execute "wincmd K" + " Set the window height to 5. + execute "5wincmd _" +endfunction + +autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow() +``` + +Options +------- + +All options have reasonable defaults so if the plug-in works after installation +you don't need to change any options. These options can be configured in your +[vimrc script][vimrc] by including a line like this: + +```viml +let g:ycm_min_num_of_chars_for_completion = 1 +``` + +Note that after changing an option in your [vimrc script] [vimrc] you have to +restart Vim for the changes to take effect. + +### The `g:ycm_min_num_of_chars_for_completion` option + +This option controls the number of characters the user needs to type before +identifier-based completion suggestions are triggered. For example, if the +option is set to `2`, then when the user types a second alphanumeric character +after a whitespace character, completion suggestions will be triggered. This +option is NOT used for semantic completion. + +Setting this option to a high number like `99` effectively turns off the +identifier completion engine and just leaves the semantic engine. + +Default: `2` + +```viml +let g:ycm_min_num_of_chars_for_completion = 2 +``` + +### The `g:ycm_min_num_identifier_candidate_chars` option + +This option controls the minimum number of characters that a completion +candidate coming from the identifier completer must have to be shown in the +popup menu. + +A special value of `0` means there is no limit. + +NOTE: This option only applies to the identifier completer; it has no effect on +the various semantic completers. + +Default: `0` + +```viml +let g:ycm_min_num_identifier_candidate_chars = 0 +``` + +### The `g:ycm_auto_trigger` option + +When set to `0`, this option turns off YCM's identifier completer (the +as-you-type popup) _and_ the semantic triggers (the popup you'd get after typing +`.` or `->` in say C++). You can still force semantic completion with the +`<C-Space>` shortcut. + +If you want to just turn off the identifier completer but keep the semantic +triggers, you should set `g:ycm_min_num_of_chars_for_completion` to a high +number like `99`. + +Default: `1` + +```viml +let g:ycm_auto_trigger = 1 +``` + +### The `g:ycm_filetype_whitelist` option + +This option controls for which Vim filetypes (see `:h filetype`) should YCM be +turned on. The option value should be a Vim dictionary with keys being filetype +strings (like `python`, `cpp` etc) and values being unimportant (the dictionary +is used like a hash set, meaning that only the keys matter). + +The `*` key is special and matches all filetypes. By default, the whitelist +contains only this `*` key. + +YCM also has a `g:ycm_filetype_blacklist` option that lists filetypes for which +YCM shouldn't be turned on. YCM will work only in filetypes that both the +whitelist and the blacklist allow (the blacklist "allows" a filetype by _not_ +having it as a key). + +For example, let's assume you want YCM to work in files with the `cpp` filetype. +The filetype should then be present in the whitelist either directly (`cpp` key +in the whitelist) or indirectly through the special `*` key. It should _not_ be +present in the blacklist. + +Filetypes that are blocked by the either of the lists will be completely ignored +by YCM, meaning that neither the identifier-based completion engine nor the +semantic engine will operate in them. + +You can get the filetype of the current file in Vim with `:set ft?`. + +Default: `{'*' : 1}` + +```viml +let g:ycm_filetype_whitelist = { '*': 1 } +``` + +### The `g:ycm_filetype_blacklist` option + +This option controls for which Vim filetypes (see `:h filetype`) should YCM be +turned off. The option value should be a Vim dictionary with keys being filetype +strings (like `python`, `cpp` etc) and values being unimportant (the dictionary +is used like a hash set, meaning that only the keys matter). + +See the `g:ycm_filetype_whitelist` option for more details on how this works. + +Default: `[see next line]` + +```viml +let g:ycm_filetype_blacklist = { + \ 'tagbar' : 1, + \ 'qf' : 1, + \ 'notes' : 1, + \ 'markdown' : 1, + \ 'unite' : 1, + \ 'text' : 1, + \ 'vimwiki' : 1, + \ 'pandoc' : 1, + \ 'infolog' : 1, + \ 'mail' : 1 + \} +``` + +### The `g:ycm_filetype_specific_completion_to_disable` option + +This option controls for which Vim filetypes (see `:h filetype`) should the YCM +semantic completion engine be turned off. The option value should be a Vim +dictionary with keys being filetype strings (like `python`, `cpp` etc) and +values being unimportant (the dictionary is used like a hash set, meaning that +only the keys matter). The listed filetypes will be ignored by the YCM semantic +completion engine, but the identifier-based completion engine will still trigger +in files of those filetypes. + +Note that even if semantic completion is not turned off for a specific filetype, +you will not get semantic completion if the semantic engine does not support +that filetype. + +You can get the filetype of the current file in Vim with `:set ft?`. + +Default: `[see next line]` + +```viml +let g:ycm_filetype_specific_completion_to_disable = { + \ 'gitcommit': 1 + \} +``` + +### The `g:ycm_show_diagnostics_ui` option + +When set, this option turns on YCM's diagnostic display features. See the +_Diagnostic display_ section in the _User Manual_ for more details. + +Specific parts of the diagnostics UI (like the gutter signs, text highlighting, +diagnostic echo and auto location list population) can be individually turned on +or off. See the other options below for details. + +Note that YCM's diagnostics UI is only supported for C-family languages. + +When set, this option also makes YCM remove all Syntastic checkers set for the +`c`, `cpp`, `objc` and `objcpp` filetypes since this would conflict with YCM's +own diagnostics UI. + +If you're using YCM's identifier completer in C-family languages but cannot use +the clang-based semantic completer for those languages _and_ want to use the GCC +Syntastic checkers, unset this option. + +Default: `1` + +```viml +let g:ycm_show_diagnostics_ui = 1 +``` + +### The `g:ycm_error_symbol` option + +YCM will use the value of this option as the symbol for errors in the Vim +gutter. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the `g:syntastic_error_symbol` option +before using this option's default. + +Default: `>>` + +```viml +let g:ycm_error_symbol = '>>' +``` + +### The `g:ycm_warning_symbol` option + +YCM will use the value of this option as the symbol for warnings in the Vim +gutter. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the `g:syntastic_warning_symbol` option +before using this option's default. + +Default: `>>` + +```viml +let g:ycm_warning_symbol = '>>' +``` + +### The `g:ycm_enable_diagnostic_signs` option + +When this option is set, YCM will put icons in Vim's gutter on lines that have a +diagnostic set. Turning this off will also turn off the `YcmErrorLine` and +`YcmWarningLine` highlighting. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the `g:syntastic_enable_signs` option +before using this option's default. + +Default: `1` + +```viml +let g:ycm_enable_diagnostic_signs = 1 +``` + +### The `g:ycm_enable_diagnostic_highlighting` option + +When this option is set, YCM will highlight regions of text that are related to +the diagnostic that is present on a line, if any. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the `g:syntastic_enable_highlighting` +option before using this option's default. + +Default: `1` + +```viml +let g:ycm_enable_diagnostic_highlighting = 1 +``` + +### The `g:ycm_echo_current_diagnostic` option + +When this option is set, YCM will echo the text of the diagnostic present on the +current line when you move your cursor to that line. If a `FixIt` is available +for the current diagnostic, then ` (FixIt)` is appended. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the `g:syntastic_echo_current_error` +option before using this option's default. + +Default: `1` + +```viml +let g:ycm_echo_current_diagnostic = 1 +``` + +### The `g:ycm_always_populate_location_list` option + +When this option is set, YCM will populate the location list automatically every +time it gets new diagnostic data. This option is off by default so as not to +interfere with other data you might have placed in the location list. + +See `:help location-list` in Vim to learn more about the location list. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the +`g:syntastic_always_populate_loc_list` option before using this option's +default. + +Default: `0` + +```viml +let g:ycm_always_populate_location_list = 0 +``` + +### The `g:ycm_open_loclist_on_ycm_diags` option + +When this option is set, `:YcmDiags` will automatically open the location list +after forcing a compilation and filling the list with diagnostic data. + +See `:help location-list` in Vim to learn more about the location list. + +Default: `1` + +```viml +let g:ycm_open_loclist_on_ycm_diags = 1 +``` + +### The `g:ycm_allow_changing_updatetime` option + +When this option is set to `1`, YCM will change the `updatetime` Vim option to +`2000` (see `:h updatetime`). This may conflict with some other plugins you have +(but it's unlikely). The `updatetime` option is the number of milliseconds that +have to pass before Vim's `CursorHold` (see `:h CursorHold`) event fires. YCM +runs the completion engines' "file comprehension" systems in the background on +every such event; the identifier-based engine collects the identifiers whereas +the semantic engine compiles the file to build an AST. + +The Vim default of `4000` for `updatetime` is a bit long, so YCM reduces +this. Set this option to `0` to force YCM to leave your `updatetime` setting +alone. + +Default: `1` + +```viml +let g:ycm_allow_changing_updatetime = 1 +``` + +### The `g:ycm_complete_in_comments` option + +When this option is set to `1`, YCM will show the completion menu even when +typing inside comments. + +Default: `0` + +```viml +let g:ycm_complete_in_comments = 0 +``` + +### The `g:ycm_complete_in_strings` option + +When this option is set to `1`, YCM will show the completion menu even when +typing inside strings. + +Note that this is turned on by default so that you can use the filename +completion inside strings. This is very useful for instance in C-family files +where typing `#include "` will trigger the start of filename completion. If you +turn off this option, you will turn off filename completion in such situations +as well. + +Default: `1` + +```viml +let g:ycm_complete_in_strings = 1 +``` + +### The `g:ycm_collect_identifiers_from_comments_and_strings` option + +When this option is set to `1`, YCM's identifier completer will also collect +identifiers from strings and comments. Otherwise, the text in comments and +strings will be ignored. + +Default: `0` + +```viml +let g:ycm_collect_identifiers_from_comments_and_strings = 0 +``` + +### The `g:ycm_collect_identifiers_from_tags_files` option + +When this option is set to `1`, YCM's identifier completer will also collect +identifiers from tags files. The list of tags files to examine is retrieved from +the `tagfiles()` Vim function which examines the `tags` Vim option. See `:h +'tags'` for details. + +YCM will re-index your tags files if it detects that they have been modified. + +The only supported tag format is the [Exuberant Ctags format][ctags-format]. The +format from "plain" ctags is NOT supported. Ctags needs to be called with the +`--fields=+l` option (that's a lowercase `L`, not a one) because YCM needs the +`language:<lang>` field in the tags output. + +See the _FAQ_ for pointers if YCM does not appear to read your tag files. + +This option is off by default because it makes Vim slower if your tags are on a +network directory. + +Default: `0` + +```viml +let g:ycm_collect_identifiers_from_tags_files = 0 +``` + +### The `g:ycm_seed_identifiers_with_syntax` option + +When this option is set to `1`, YCM's identifier completer will seed its +identifier database with the keywords of the programming language you're +writing. + +Since the keywords are extracted from the Vim syntax file for the filetype, all +keywords may not be collected, depending on how the syntax file was written. +Usually at least 95% of the keywords are successfully extracted. + +Default: `0` + +```viml +let g:ycm_seed_identifiers_with_syntax = 0 +``` + +### The `g:ycm_extra_conf_vim_data` option + +If you're using semantic completion for C-family files, this option might come +handy; it's a way of sending data from Vim to your `FlagsForFile` function in +your `.ycm_extra_conf.py` file. + +This option is supposed to be a list of VimScript expression strings that are +evaluated for every request to the [ycmd server][ycmd] and then passed to your +`FlagsForFile` function as a `client_data` keyword argument. + +For instance, if you set this option to `['v:version']`, your `FlagsForFile` +function will be called like this: + +```python +# The '704' value is of course contingent on Vim 7.4; in 7.3 it would be '703' +FlagsForFile(filename, client_data = {'v:version': 704}) +``` + +So the `client_data` parameter is a dictionary mapping Vim expression strings to +their values at the time of the request. + +The correct way to define parameters for your `FlagsForFile` function: + +```python +def FlagsForFile(filename, **kwargs): +``` + +You can then get to `client_data` with `kwargs['client_data']`. + +Default: `[]` + +```viml +let g:ycm_extra_conf_vim_data = [] +``` + +### The `g:ycm_server_python_interpreter` option + +YCM will by default search for an appropriate Python interpreter on your system. +You can use this option to override that behavior and force the use of a +specific interpreter of your choosing. + +NOTE: This interpreter is only used for the [ycmd server][ycmd]. The YCM client +running inside Vim always uses the Python interpreter that's embedded inside +Vim. + +Default: `''` + +```viml +let g:ycm_server_python_interpreter = '' +``` + +### The `g:ycm_server_keep_logfiles` option + +When this option is set to `1`, the [ycmd completion server][ycmd] will keep the +logfiles around after shutting down (they are deleted on shutdown by default). + +To see where the logfiles are, call `:YcmDebugInfo`. + +Default: `0` + +```viml +let g:ycm_server_keep_logfiles = 0 +``` + +### The `g:ycm_server_log_level` option + +The logging level that the [ycmd completion server][ycmd] uses. Valid values are +the following, from most verbose to least verbose: +- `debug` +- `info` +- `warning` +- `error` +- `critical` + +Note that `debug` is _very_ verbose. + +Default: `info` + +```viml +let g:ycm_server_log_level = 'info' +``` + +### The `g:ycm_auto_start_csharp_server` option + +When set to `1`, the OmniSharp server will be automatically started (once per +Vim session) when you open a C# file. + +Default: `1` + +```viml +let g:ycm_auto_start_csharp_server = 1 +``` + +### The `g:ycm_auto_stop_csharp_server` option + +When set to `1`, the OmniSharp server will be automatically stopped upon +closing Vim. + +Default: `1` + +```viml +let g:ycm_auto_stop_csharp_server = 1 +``` + +### The `g:ycm_csharp_server_port` option + +When g:ycm_auto_start_csharp_server is set to `1`, specifies the port for +the OmniSharp server to listen on. When set to `0` uses an unused port provided +by the OS. + +Default: `0` + +```viml +let g:ycm_csharp_server_port = 0 +``` + +### The `g:ycm_csharp_insert_namespace_expr` option + +By default, when YCM inserts a namespace, it will insert the `using` statement +under the nearest `using` statement. You may prefer that the `using` statement is +inserted somewhere, for example, to preserve sorting. If so, you can set this +option to override this behavior. + +When this option is set, instead of inserting the `using` statement itself, YCM +will set the global variable `g:ycm_namespace_to_insert` to the namespace to +insert, and then evaluate this option's value as an expression. The option's +expression is responsible for inserting the namespace - the default insertion +will not occur. + +Default: '' + +```viml +let g:ycm_csharp_insert_namespace_expr = '' +``` + +### The `g:ycm_add_preview_to_completeopt` option + +When this option is set to `1`, YCM will add the `preview` string to Vim's +`completeopt` option (see `:h completeopt`). If your `completeopt` option +already has `preview` set, there will be no effect. You can see the current +state of your `completeopt` setting with `:set completeopt?` (yes, the question +mark is important). + +When `preview` is present in `completeopt`, YCM will use the `preview` window at +the top of the file to store detailed information about the current completion +candidate (but only if the candidate came from the semantic engine). For +instance, it would show the full function prototype and all the function +overloads in the window if the current completion is a function name. + +Default: `0` + +```viml +let g:ycm_add_preview_to_completeopt = 0 +``` + +### The `g:ycm_autoclose_preview_window_after_completion` option + +When this option is set to `1`, YCM will auto-close the `preview` window after +the user accepts the offered completion string. If there is no `preview` window +triggered because there is no `preview` string in `completeopt`, this option is +irrelevant. See the `g:ycm_add_preview_to_completeopt` option for more details. + +Default: `0` + +```viml +let g:ycm_autoclose_preview_window_after_completion = 0 +``` + +### The `g:ycm_autoclose_preview_window_after_insertion` option + +When this option is set to `1`, YCM will auto-close the `preview` window after +the user leaves insert mode. This option is irrelevant if +`g:ycm_autoclose_preview_window_after_completion` is set or if no `preview` +window is triggered. See the `g:ycm_add_preview_to_completeopt` option for more +details. + +Default: `0` + +```viml +let g:ycm_autoclose_preview_window_after_insertion = 0 +``` + +### The `g:ycm_max_diagnostics_to_display` option + +This option controls the maximum number of diagnostics shown to the user when +errors or warnings are detected in the file. This option is only relevant if you +are using the C-family semantic completion engine. + +Default: `30` + +```viml +let g:ycm_max_diagnostics_to_display = 30 +``` + +### The `g:ycm_key_list_select_completion` option + +This option controls the key mappings used to select the first completion +string. Invoking any of them repeatedly cycles forward through the completion +list. + +Some users like adding `<Enter>` to this list. + +Default: `['<TAB>', '<Down>']` + +```viml +let g:ycm_key_list_select_completion = ['<TAB>', '<Down>'] +``` + +### The `g:ycm_key_list_previous_completion` option + +This option controls the key mappings used to select the previous completion +string. Invoking any of them repeatedly cycles backwards through the completion +list. + +Note that one of the defaults is `<S-TAB>` which means Shift-TAB. That mapping +will probably only work in GUI Vim (Gvim or MacVim) and not in plain console Vim +because the terminal usually does not forward modifier key combinations to Vim. + +Default: `['<S-TAB>', '<Up>']` + +```viml +let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>'] +``` + +### The `g:ycm_key_invoke_completion` option + +This option controls the key mapping used to invoke the completion menu for +semantic completion. By default, semantic completion is trigged automatically +after typing `.`, `->` and `::` in insert mode (if semantic completion support +has been compiled in). This key mapping can be used to trigger semantic +completion anywhere. Useful for searching for top-level functions and classes. + +Console Vim (not Gvim or MacVim) passes `<Nul>` to Vim when the user types +`<C-Space>` so YCM will make sure that `<Nul>` is used in the map command when +you're editing in console Vim, and `<C-Space>` in GUI Vim. This means that you +can just press `<C-Space>` in both console and GUI Vim and YCM will do the right +thing. + +Setting this option to an empty string will make sure no mapping is created. + +Default: `<C-Space>` + +```viml +let g:ycm_key_invoke_completion = '<C-Space>' +``` + +### The `g:ycm_key_detailed_diagnostics` option + +This option controls the key mapping used to show the full diagnostic text when +the user's cursor is on the line with the diagnostic. It basically calls +`:YcmShowDetailedDiagnostic`. + +Setting this option to an empty string will make sure no mapping is created. + +Default: `<leader>d` + +```viml +let g:ycm_key_detailed_diagnostics = '<leader>d' +``` + +### The `g:ycm_global_ycm_extra_conf` option + +Normally, YCM searches for a `.ycm_extra_conf.py` file for compilation flags +(see the User Guide for more details on how this works). This option specifies +a fallback path to a config file which is used if no `.ycm_extra_conf.py` is +found. + +You can place such a global file anywhere in your filesystem. + +Default: `''` + +```viml +let g:ycm_global_ycm_extra_conf = '' +``` + +### The `g:ycm_confirm_extra_conf` option + +When this option is set to `1` YCM will ask once per `.ycm_extra_conf.py` file +if it is safe to be loaded. This is to prevent execution of malicious code +from a `.ycm_extra_conf.py` file you didn't write. + +To selectively get YCM to ask/not ask about loading certain `.ycm_extra_conf.py` +files, see the `g:ycm_extra_conf_globlist` option. + +Default: `1` + +```viml +let g:ycm_confirm_extra_conf = 1 +``` + +### The `g:ycm_extra_conf_globlist` option + +This option is a list that may contain several globbing patterns. If a pattern +starts with a `!` all `.ycm_extra_conf.py` files matching that pattern will be +blacklisted, that is they won't be loaded and no confirmation dialog will be +shown. If a pattern does not start with a `!` all files matching that pattern +will be whitelisted. Note that this option is not used when confirmation is +disabled using `g:ycm_confirm_extra_conf` and that items earlier in the list +will take precedence over the later ones. + +Rules: + +* `*` matches everything +* `?` matches any single character +* `[seq]` matches any character in seq +* `[!seq]` matches any char not in seq + +Example: + +```viml +let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*'] +``` + +* The first rule will match everything contained in the `~/dev` directory so + `.ycm_extra_conf.py` files from there will be loaded. +* The second rule will match everything in the home directory so a + `.ycm_extra_conf.py` file from there won't be loaded. +* As the first rule takes precedence everything in the home directory excluding + the `~/dev` directory will be blacklisted. + +NOTE: The glob pattern is first expanded with Python's `os.path.expanduser()` +and then resolved with `os.path.abspath()` before being matched against the +filename. + +Default: `[]` + +```viml +let g:ycm_extra_conf_globlist = [] +``` + +### The `g:ycm_filepath_completion_use_working_dir` option + +By default, YCM's filepath completion will interpret relative paths like `../` +as being relative to the folder of the file of the currently active buffer. +Setting this option will force YCM to always interpret relative paths as being +relative to Vim's current working directory. + +Default: `0` + +```viml +let g:ycm_filepath_completion_use_working_dir = 0 +``` + +### The `g:ycm_semantic_triggers` option + +This option controls the character-based triggers for the various semantic +completion engines. The option holds a dictionary of key-values, where the keys +are Vim's filetype strings delimited by commas and values are lists of strings, +where the strings are the triggers. + +Setting key-value pairs on the dictionary _adds_ semantic triggers to the +internal default set (listed below). You cannot remove the default triggers, +only add new ones. + +A "trigger" is a sequence of one or more characters that trigger semantic +completion when typed. For instance, C++ (`cpp` filetype) has `.` listed as a +trigger. So when the user types `foo.`, the semantic engine will trigger and +serve `foo`'s list of member functions and variables. Since C++ also has `->` +listed as a trigger, the same thing would happen when the user typed `foo->`. + +It's also possible to use a regular expression as a trigger. You have to prefix +your trigger with `re!` to signify it's a regex trigger. For instance, +`re!\w+\.` would only trigger after the `\w+\.` regex matches. + +NOTE: The regex syntax is **NOT** Vim's, it's [Python's][python-re]. + +Default: `[see next line]` + +```viml +let g:ycm_semantic_triggers = { + \ 'c' : ['->', '.'], + \ 'objc' : ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s', + \ 're!\[.*\]\s'], + \ 'ocaml' : ['.', '#'], + \ 'cpp,objcpp' : ['->', '.', '::'], + \ 'perl' : ['->'], + \ 'php' : ['->', '::'], + \ 'cs,java,javascript,typescript,d,python,perl6,scala,vb,elixir,go' : ['.'], + \ 'ruby' : ['.', '::'], + \ 'lua' : ['.', ':'], + \ 'erlang' : [':'], + \ } +``` + +### The `g:ycm_cache_omnifunc` option + +Some omnicompletion engines do not work well with the YCM cache—in particular, +they might not produce all possible results for a given prefix. By unsetting +this option you can ensure that the omnicompletion engine is re-queried on every +keypress. That will ensure all completions will be presented, but might cause +stuttering and lagginess if the omnifunc is slow. + +Default: `1` + +```viml +let g:ycm_cache_omnifunc = 1 +``` + +### The `g:ycm_use_ultisnips_completer` option + +By default, YCM will query the UltiSnips plugin for possible completions of +snippet triggers. This option can turn that behavior off. + +Default: `1` + +```viml +let g:ycm_use_ultisnips_completer = 1 +``` + +### The `g:ycm_goto_buffer_command` option + +Defines where `GoTo*` commands result should be opened. +Can take one of the following values: +`[ 'same-buffer', 'horizontal-split', 'vertical-split', 'new-tab', + 'new-or-existing-tab' ]` +If this option is set to the `'same-buffer'` but current buffer can not +be switched (when buffer is modified and `nohidden` option is set), +then result will be opened in horizontal split. + +Default: `'same-buffer'` + +```viml +let g:ycm_goto_buffer_command = 'same-buffer' +``` + +### The `g:ycm_disable_for_files_larger_than_kb` option + +Defines the max size (in Kb) for a file to be considered for completion. If this +option is set to 0 then no check is made on the size of the file you're opening. + +Default: 1000 + +```viml +let g:ycm_disable_for_files_larger_than_kb = 1000 +``` + +### The `g:ycm_python_binary_path` option + +This option specifies the Python interpreter to use to run the [jedi][] +completion library. Specify the Python interpreter to use to get completions. +By default the Python under which [ycmd][] runs is used ([ycmd][] runs on +Python 2.6, 2.7 or 3.3+). + +Default: `''` + +```viml +let g:ycm_python_binary_path = 'python' +``` + +NOTE: the settings above will make YCM use the first `python` executable +found through the PATH. + +FAQ +--- + +### I used to be able to `import vim` in `.ycm_extra_conf.py`, but now can't + +YCM was rewritten to use a client-server architecture where most of the logic is +in the [ycmd server][ycmd]. So the magic `vim` module you could have previously +imported in your `.ycm_extra_conf.py` files doesn't exist anymore. + +To be fair, importing the magic `vim` module in extra conf files was never +supported in the first place; it only ever worked by accident and was never a +part of the extra conf API. + +But fear not, you should be able to tweak your extra conf files to continue +working by using the `g:ycm_extra_conf_vim_data` option. See the docs on that +option for details. + +### On very rare occasions Vim crashes when I tab through the completion menu + +That's a very rare Vim bug most users never encounter. It's fixed in Vim +7.4.72. Update to that version (or above) to resolve the issue. + +### I get `ImportError` exceptions that mention `PyInit_ycm_core` or `initycm_core` + +These errors are caused by building the YCM native libraries for Python 2 and +trying to load them into a Python 3 process (or the other way around). + +For instance, if building for Python 2 but loading in Python 3: + +``` +ImportError: dynamic module does not define init function (PyInit_ycm_core) +``` + +If building for Python 3 but loading in Python 2: + +``` +ImportError: dynamic module does not define init function (initycm_core) +``` + +Setting the `g:ycm_server_python_interpreter` option to force the use of a +specific Python interpreter for `ycmd` is usually the easiest way to solve the +problem. Common values for that option are `/usr/bin/python` and +`/usr/bin/python3`. + +### I get a linker warning regarding `libpython` on Mac when compiling YCM + +If the warning is `ld: warning: path '/usr/lib/libpython2.7.dylib' following -L +not a directory`, then feel free to ignore it; it's caused by a limitation of +CMake and is not an issue. Everything should still work fine. + +### I get a weird window at the top of my file when I use the semantic engine + +This is Vim's `preview` window. Vim uses it to show you extra information about +something if such information is available. YCM provides Vim with such extra +information. For instance, when you select a function in the completion list, +the `preview` window will hold that function's prototype and the prototypes of +any overloads of the function. It will stay there after you select the +completion so that you can use the information about the parameters and their +types to write the function call. + +If you would like this window to auto-close after you select a completion +string, set the `g:ycm_autoclose_preview_window_after_completion` option to `1` +in your `vimrc` file. Similarly, the `g:ycm_autoclose_preview_window_after_insertion` +option can be set to close the `preview` window after leaving insert mode. + +If you don't want this window to ever show up, add `set completeopt-=preview` to +your `vimrc`. Also make sure that the `g:ycm_add_preview_to_completeopt` option +is set to `0`. + +### It appears that YCM is not working + +In Vim, run `:messages` and carefully read the output. YCM will echo messages to +the message log if it encounters problems. It's likely you misconfigured +something and YCM is complaining about it. + +Also, you may want to run the `:YcmDebugInfo` command; it will make YCM spew out +various debugging information, including the [ycmd][] logfile paths and the +compile flags for the current file if the file is a C-family language file and +you have compiled in Clang support. Logfiles can be automatically opened in the +editor using the `:YcmToggleLogs` command. + +### Sometimes it takes much longer to get semantic completions than normal + +This means that libclang (which YCM uses for C-family semantic completion) +failed to pre-compile your file's preamble. In other words, there was an error +compiling some of the source code you pulled in through your header files. I +suggest calling the `:YcmDiags` command to see what they were. + +Bottom line, if libclang can't pre-compile your file's preamble because there +were errors in it, you're going to get slow completions because there's no AST +cache. + +### YCM auto-inserts completion strings I don't want! + +This means you probably have some mappings that interfere with YCM's internal +ones. Make sure you don't have something mapped to `<C-p>`, `<C-x>` or `<C-u>` +(in insert mode). + +YCM _never_ selects something for you; it just shows you a menu and the user has +to explicitly select something. If something is being selected automatically, +this means there's a bug or a misconfiguration somewhere. + +### I get a `E227: mapping already exists for <blah>` error when I start Vim + +This means that YCM tried to set up a key mapping but failed because you already +had something mapped to that key combination. The `<blah>` part of the message +will tell you what was the key combination that failed. + +Look in the _Options_ section and see if any of the default mappings conflict +with your own. Then change that option value to something else so that the +conflict goes away. + +### I get `'GLIBC_2.XX' not found (required by libclang.so)` when starting Vim + +Your system is too old for the precompiled binaries from llvm.org. Compile +Clang on your machine and then link against the `libclang.so` you just produced. +See the full installation guide for help. + +### I'm trying to use a Homebrew Vim with YCM and I'm getting segfaults + +Something (I don't know what) is wrong with the way that Homebrew configures and +builds Vim. I recommend using [MacVim][]. Even if you don't like the MacVim GUI, +you can use the Vim binary that is inside the MacVim.app package (it's +`MacVim.app/Contents/MacOS/Vim`) and get the Vim console experience. + +### I have a Homebrew Python and/or MacVim; can't compile/SIGABRT when starting + +You should probably run `brew rm python; brew install python` to get the latest +fixes that should make YCM work with such a configuration. Also rebuild Macvim +then. If you still get problems with this, see [issue #18][issue18] for +suggestions. + +### Vim segfaults when I use the semantic completer in Ruby files + +This was caused by a Vim bug. Update your version of Vim (Vim 7.3.874 is known +to work, earlier versions may also fix this issue). + +### I get `LONG_BIT definition appears wrong for platform` when compiling + +Look at the output of your CMake call. There should be a line in it like the +following (with `.dylib` in place of `.so` on a Mac): + +``` +-- Found PythonLibs: /usr/lib/libpython2.7.so (Required is at least version "2.5") +``` + +That would be the **correct** output. An example of **incorrect** output would +be the following: + +``` +-- Found PythonLibs: /usr/lib/libpython2.7.so (found suitable version "2.5.1", minimum required is "2.5") +``` + +Notice how there's an extra bit of output there, the `found suitable version +"<version>"` part, where `<version>` is not the same as the version of the +dynamic library. In the example shown, the library is version 2.7 but the second +string is version `2.5.1`. + +This means that CMake found one version of Python headers and a different +version for the library. This is wrong. It can happen when you have multiple +versions of Python installed on your machine. + +You should probably add the following flags to your cmake call (again, `dylib` +instead of `so` on a Mac): + +``` +-DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/libpython2.7.so +``` + +This will force the paths to the Python include directory and the Python library +to use. You may need to set these flags to something else, but you need to make +sure you use the same version of Python that your Vim binary is built against, +which is highly likely to be the system's default Python. + +### I get `libpython2.7.a [...] relocation R_X86_64_32` when compiling + +The error is usually encountered when compiling YCM on Centos or RHEL. The full +error looks something like the following: + +``` +/usr/bin/ld: /usr/local/lib/libpython2.7.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC +``` + +It's possible to get a slightly different error that's similar to the one above. +Here's the problem and how you solve it: + +Your `libpython2.7.a` was not compiled with `-fPIC` so it can't be linked into +`ycm_core.so`. Use the `-DPYTHON_LIBRARY=` CMake flag to point it to a `.so` +version of libpython on your machine (for instance, +`-DPYTHON_LIBRARY=/usr/lib/libpython2.7.so`). Naturally, this means you'll have +to go through the full installation guide by hand. + +### I get `Vim: Caught deadly signal SEGV` on Vim startup + +This can happen on some Linux distros. If you encounter this situation, run Vim +under `gdb`. You'll probably see something like this in the output when Vim +crashes: + +``` +undefined symbol: clang_CompileCommands_dispose +``` + +This means that Vim is trying to load a `libclang.so` that is too old. You need +at least a 3.8 libclang. Just go through the installation guide and make sure +you are using a correct `libclang.so`. We recommend downloading prebuilt +binaries from llvm.org. + + +### I get `Fatal Python error: PyThreadState_Get: no current thread` on startup + +This is caused by linking a static version of `libpython` into ycmd's +`ycm_core.so`. This leads to multiple copies of the python interpreter loaded +when `python` loads `ycmd_core.so` and this messes up python's global state. +The details aren't important. + +The solution is that the version of Python linked and run against must be built +with either `--enable-shared` or `--enable-framework` (on OS X). +This is achieved as follows (NOTE: for Mac, replace `--enable-shared` +with `--enable-framework`): + +- When building python from source: `./configure --enable-shared {options}` +- When building python from pyenv: + `PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install {version}` + + +## `install.py` says python must be compiled with `--enable-framework`. Wat? + +See the previous answer for how to ensure your python is built to support +dynamic modules. + +### YCM does not read identifiers from my tags files + +First, put `let g:ycm_collect_identifiers_from_tags_files = 1` in your vimrc. + +Make sure you are using [Exuberant Ctags][exuberant-ctags] to produce your tags +files since the only supported tag format is the [Exuberant Ctags +format][ctags-format]. The format from "plain" ctags is NOT supported. The +output of `ctags --version` should list "Exuberant Ctags". + +Ctags needs to be called with the `--fields=+l` (that's a lowercase `L`, not a +one) option because YCM needs the `language:<lang>` field in the tags output. + +NOTE: [Exuberant Ctags][exuberant-ctags] by default sets language tag for `*.h` +files as `C++`. If you have C (not C++) project, consider +giving parameter `--langmap=c:.c.h` to ctags to see tags from `*.h` files. + +NOTE: Mac OS X comes with "plain" ctags installed by default. `brew install +ctags` will get you the Exuberant Ctags version. + +Also make sure that your Vim `tags` option is set correctly. See `:h 'tags'` for +details. If you want to see which tag files YCM will read for a given buffer, +run `:echo tagfiles()` with the relevant buffer active. Note that that function +will only list tag files that already exist. + +### `CTRL-U` in insert mode does not work + +YCM keeps you in a `completefunc` completion mode when you're typing in insert +mode and Vim disables `<C-U>` in completion mode as a "feature." Sadly there's +nothing I can do about this. + +### YCM conflicts with UltiSnips TAB key usage + +YCM comes with support for UltiSnips (snippet suggestions in the popup menu), +but you'll have to change the UltiSnips mappings. See `:h UltiSnips-triggers` in +Vim for details. You'll probably want to change some/all of the following +options: + +```viml +g:UltiSnipsExpandTrigger +g:UltiSnipsJumpForwardTrigger +g:UltiSnipsJumpBackwardTrigger +``` + +### Why isn't YCM just written in plain VimScript, FFS? + +Because of the identifier completion engine and subsequence-based filtering. +Let's say you have _many_ dozens of files open in a single Vim instance (I often +do); the identifier-based engine then needs to store thousands (if not tens of +thousands) of identifiers in its internal data-structures. When the user types, +YCM needs to perform subsequence-based filtering on _all_ of those identifiers +(every single one!) in less than 10 milliseconds. + +I'm sorry, but that level of performance is just plain impossible to achieve +with VimScript. I've tried, and the language is just too slow. No, you can't get +acceptable performance even if you limit yourself to just the identifiers in the +current file and simple prefix-based filtering. + +### Why does YCM demand such a recent version of Vim? + +During YCM's development several show-stopper bugs were encountered in Vim. +Those needed to be fixed upstream (and were). A few months after those bugs were +fixed, Vim trunk landed the `pyeval()` function which improved YCM performance +even more since less time was spent serializing and deserializing data between +Vim and the embedded Python interpreter. A few critical bugfixes for `pyeval()` +landed in Vim 7.3.584 (and a few commits before that). + +### I get annoying messages in Vim's status area when I type + +If you're referring to the `User defined completion <bla bla> back at original` +and similar, then just update to Vim 7.4.314 (or later) and they'll go away. + +### Nasty bugs happen if I have the `vim-autoclose` plugin installed + +Use the [delimitMate][] plugin instead. It does the same thing without +conflicting with YCM. + +### Is there some sort of YCM mailing list? I have questions + +If you have questions about the plugin or need help, please use the +[ycm-users][] mailing list, _don't_ create issues on the tracker. The tracker is +for bug reports and feature requests. + +### I get an internal compiler error when installing + +This can be a problem on virtual servers with limited memory. A possible +solution is to add more swap memory. A more practical solution would be to force +the build script to run only one compile job at a time. You can do this by +setting the `YCM_CORES` environment variable to `1`. Example: + +``` +YCM_CORES=1 ./install.py --clang-completer +``` + +### I get weird errors when I press `Ctrl-C` in Vim + +_Never_ use `Ctrl-C` in Vim. + +Using `Ctrl-C` to exit insert mode in Vim is a bad idea. The main issue here is +that `Ctrl-C` in Vim doesn't just leave insert mode, it leaves it without +triggering `InsertLeave` autocommands (as per Vim docs). This is a bad idea and +is likely to break many other things and not just YCM. + +Bottom line, if you use `Ctrl-C` to exit insert mode in Vim, you're gonna have a +bad time. + +If pressing `<esc>` is too annoying (agreed, it is), we suggest mapping it to +something more convenient. On a QWERTY keyboard, a good pick for the `<esc>` map +is `inoremap jk <Esc>`. This is right on the home row, it's an incredibly rare +digraph in English and if you ever need to type those two chars in sequence in +insert mode, you just type `j`, then wait 500ms, then type `k`. + +### Why did YCM stop using Syntastic for diagnostics display? + +Previously, YCM would send any diagnostics it would receive from the libclang +semantic engine to Syntastic for display as signs in the gutter, red squiggles +etc. Today, YCM uses its own code to do that. + +Using Syntastic for this was always a kludge. Syntastic assumes its "checker" +plugins behave in a certain way; those assumptions have never fit YCM. For +instance, YCM continuously recompiles your code in the background for C-family +languages and tries to push new diagnostics to the user as fast as possible, +even while the user types. + +Syntastic assumes that a checker only runs on file save ("active" mode) or even +less frequently, when the user explicitly invokes it ("passive" mode). This +mismatch in assumptions causes performance problems since Syntastic code isn't +optimized for this use case of constant diagnostic refreshing. + +Poor support for this use case also led to crash bugs in Vim caused by +Syntastic-Vim interactions ([issue #593][issue-593]) and other problems, like +random Vim flickering. Attempts were made to resolve these issues in +Syntastic, but ultimately some of them failed (for various reasons). + +Implementing diagnostic display code directly in YCM resolves all of these +problems. Performance also improved substantially since the relevant code is now +written in Python instead of VimScript (which is very slow) and is tailored only +for YCM's use-cases. We were also able to introduce new features in this area +since we're now not limited to the Syntastic checker API. + +We've tried to implement this in the most backwards-compatible way possible; YCM +options that control diagnostic display fall back to Syntastic options that +control the same concepts if the user has those set. + +Still, some Syntastic-specific configuration you might have had might not +be supported by the new code. Please file issues on the tracker in such +cases; if we find the request to be reasonable, we'll find a way to address it. + +### Completion doesn't work with the C++ standard library headers + +This is caused by an issue with libclang that only affects some operating +systems. Compiling with `clang` the binary will use the correct default header +search paths but compiling with `libclang.so` (which YCM uses) does not. + +Mac OS X is normally affected, but there's a workaround in YCM for that specific +OS. If you're not running that OS but still have the same problem, continue +reading. + +The workaround is to call `echo | clang -v -E -x c++ -` and look at the +paths under the `#include <...> search starts here:` heading. You should take +those paths, prepend `-isystem` to each individual path and append them all to +the list of flags you return from your `FlagsForFile` function in your +`.ycm_extra_conf.py` file. + +See [issue #303][issue-303] for details. + +### When I open a JavaScript file, I get an annoying warning about `.tern-project` file + +Take a look at the [instructions for using the JavaScript +completer](#javascript-semantic-completion). + +If this is still really annoying, and you have a good reason not to have a +`.tern-project` file, create an empty `.tern-config` file in your home directory +and YCM will stop complaining. + +### When I start vim I get a runtime error saying `R6034 An application has made an attempt to load the C runtime library incorrectly.` + +[CMake and other things seem to screw up the PATH with their own msvcrXX.dll +versions.][identify-R6034-cause] Add the following to the very top of your vimrc +to remove these entries from the path. + +```python +python << EOF +import os +import re +path = os.environ['PATH'].split(';') + +def contains_msvcr_lib(folder): + try: + for item in os.listdir(folder): + if re.match(r'msvcr\d+\.dll', item): + return True + except: + pass + return False + +path = [folder for folder in path if not contains_msvcr_lib(folder)] +os.environ['PATH'] = ';'.join(path) +EOF +``` + +### I hear that YCM only supports Python 2, is that true? + +**No.** Both the Vim client and the [ycmd server][ycmd] run on Python 2 or 3. If +you work on a Python 3 project, you may need to set `g:ycm_python_binary_path` +to the Python interpreter you use for your project to get completions for that +version of Python. + +### On Windows I get `E887: Sorry, this command is disabled, the Python's site module could not be loaded` + +If you are running vim on Windows with Python 2.7.11, this is likely caused by +a [bug][vim_win-python2.7.11-bug]. Follow this [workaround] +[vim_win-python2.7.11-bug_workaround] or use a different version (Python 2.7.9 +does not suffer from the bug). + +### I can't complete python packages in a virtual environment. + +This means that the Python used to run [JediHTTP][] is not the Python of the +virtual environment you're in. To resolve this you either set +`g:ycm_python_binary_path` to the absolute path of the Python binary in your +virtual environment or since virtual environment will put that Python +executable first in your PATH when the virtual environment is active then if +you set `g:ycm_python_binary_path` to just `'python'` it will be found as the +first Python and used to run [JediHTTP][]. + +Contributor Code of Conduct +--------------------------- + +Please note that this project is released with a [Contributor Code of +Conduct][ccoc]. By participating in this project you agree to abide by its +terms. + + +Contact +------- + +If you have questions about the plugin or need help, please use the +[ycm-users][] mailing list. + +If you have bug reports or feature suggestions, please use the [issue +tracker][tracker]. + +The latest version of the plugin is available at +<http://valloric.github.io/YouCompleteMe/>. + +The author's homepage is <http://val.markovic.io>. + + +License +------- + +This software is licensed under the [GPL v3 license][gpl]. +© 2015-2016 YouCompleteMe contributors + +[ycmd]: https://github.com/Valloric/ycmd +[Clang]: http://clang.llvm.org/ +[vundle]: https://github.com/VundleVim/Vundle.vim#about +[pathogen]: https://github.com/tpope/vim-pathogen#pathogenvim +[clang-download]: http://llvm.org/releases/download.html +[brew]: http://brew.sh +[cmake-download]: https://cmake.org/download/ +[macvim]: https://github.com/macvim-dev/macvim/releases +[vimrc]: http://vimhelp.appspot.com/starting.txt.html#vimrc +[gpl]: http://www.gnu.org/copyleft/gpl.html +[vim]: http://www.vim.org/ +[syntastic]: https://github.com/scrooloose/syntastic +[lightline]: https://github.com/itchyny/lightline.vim +[flags_example]: https://github.com/Valloric/ycmd/blob/master/cpp/ycm/.ycm_extra_conf.py +[compdb]: http://clang.llvm.org/docs/JSONCompilationDatabase.html +[subsequence]: https://en.wikipedia.org/wiki/Subsequence +[listtoggle]: https://github.com/Valloric/ListToggle +[vim-build]: https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source +[tracker]: https://github.com/Valloric/YouCompleteMe/issues?state=open +[issue18]: https://github.com/Valloric/YouCompleteMe/issues/18 +[delimitMate]: https://github.com/Raimondi/delimitMate +[completer-api]: https://github.com/Valloric/ycmd/blob/master/ycmd/completers/completer.py +[eclim]: http://eclim.org/ +[jedi]: https://github.com/davidhalter/jedi +[ultisnips]: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt +[exuberant-ctags]: http://ctags.sourceforge.net/ +[ctags-format]: http://ctags.sourceforge.net/FORMAT +[vundle-bug]: https://github.com/VundleVim/Vundle.vim/issues/48 +[ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users +[omnisharp]: https://github.com/OmniSharp/omnisharp-server +[issue-303]: https://github.com/Valloric/YouCompleteMe/issues/303 +[issue-593]: https://github.com/Valloric/YouCompleteMe/issues/593 +[issue-669]: https://github.com/Valloric/YouCompleteMe/issues/669 +[status-mes]: https://groups.google.com/forum/#!topic/vim_dev/WeBBjkXE8H8 +[python-re]: https://docs.python.org/2/library/re.html#regular-expression-syntax +[bear]: https://github.com/rizsotto/Bear +[Options]: https://github.com/Valloric/YouCompleteMe#options +[ygen]: https://github.com/rdnetto/YCM-Generator +[Gocode]: https://github.com/nsf/gocode +[Godef]: https://github.com/Manishearth/godef +[TSServer]: https://github.com/Microsoft/TypeScript/tree/master/src/server +[vim-win-download]: https://bintray.com/micbou/generic/vim +[python-win-download]: https://www.python.org/downloads/windows/ +[visual-studio-download]: https://www.visualstudio.com/products/free-developer-offers-vs.aspx +[7z-download]: http://www.7-zip.org/download.html +[mono-install-osx]: http://www.mono-project.com/docs/getting-started/install/mac/ +[mono-install-ubuntu]: http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives +[mono-install-fedora]: http://www.mono-project.com/docs/getting-started/install/linux/#centos-7-fedora-19-and-later-and-derivatives +[mono-install]: http://www.mono-project.com/docs/getting-started/install/ +[go-install]: https://golang.org/doc/install +[npm-install]: https://docs.npmjs.com/getting-started/installing-node +[Tern]: http://ternjs.net +[tern-project]: http://ternjs.net/doc/manual.html#configuration +[tern-docs]: http://ternjs.net/doc/manual.html#server +[racer]: https://github.com/phildawes/racer +[rust-install]: https://www.rust-lang.org/ +[rust-src]: https://www.rust-lang.org/downloads.html +[add-msbuild-to-path]: http://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1 +[identify-R6034-cause]: http://stackoverflow.com/questions/14552348/runtime-error-r6034-in-embedded-python-application/34696022 +[ccoc]: https://github.com/Valloric/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md +[JediHTTP]: https://github.com/vheon/JediHTTP +[vim_win-python2.7.11-bug]: https://github.com/vim/vim/issues/717 +[vim_win-python2.7.11-bug_workaround]: https://github.com/vim/vim-win32-installer/blob/master/appveyor.bat#L90 diff --git a/vim/bundle/YouCompleteMe/appveyor.yml b/vim/bundle/YouCompleteMe/appveyor.yml new file mode 100644 index 0000000..6ea7062 --- /dev/null +++ b/vim/bundle/YouCompleteMe/appveyor.yml @@ -0,0 +1,18 @@ +version: '{build}' +environment: + matrix: + - arch: 32 + python: 35 + # We only test Python 2.7 on 64 bits. + - arch: 64 + python: 27 + - arch: 64 + python: 35 +install: + - ci\appveyor\appveyor_install.bat +build_script: + - python run_tests.py +# Disable automatic tests +test: off +cache: + - '%LOCALAPPDATA%\pip\cache' # Python packages from pip diff --git a/vim/bundle/YouCompleteMe/autoload/youcompleteme.vim b/vim/bundle/YouCompleteMe/autoload/youcompleteme.vim new file mode 100644 index 0000000..37ed572 --- /dev/null +++ b/vim/bundle/YouCompleteMe/autoload/youcompleteme.vim @@ -0,0 +1,889 @@ +" Copyright (C) 2011, 2012 Google Inc. +" +" This file is part of YouCompleteMe. +" +" YouCompleteMe 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. +" +" YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +" This is basic vim plugin boilerplate +let s:save_cpo = &cpo +set cpo&vim + +" This needs to be called outside of a function +let s:script_folder_path = escape( expand( '<sfile>:p:h' ), '\' ) +let s:omnifunc_mode = 0 +let s:defer_omnifunc = 1 + +let s:old_cursor_position = [] +let s:cursor_moved = 0 +let s:moved_vertically_in_insert_mode = 0 +let s:previous_num_chars_on_current_line = strlen( getline('.') ) + + +function! s:UsingPython2() + " I'm willing to bet quite a bit that sooner or later, somebody will ask us to + " make it configurable which version of Python we use. + if has('python') + return 1 + endif + return 0 +endfunction + + +let s:using_python2 = s:UsingPython2() +let s:python_until_eof = s:using_python2 ? "python << EOF" : "python3 << EOF" +let s:python_command = s:using_python2 ? "py " : "py3 " + + +function! s:Pyeval( eval_string ) + if s:using_python2 + return pyeval( a:eval_string ) + endif + return py3eval( a:eval_string ) +endfunction + + +function! youcompleteme#Enable() + call s:SetUpBackwardsCompatibility() + + " This can be 0 if YCM libs are old or -1 if an exception occured while + " executing the function. + if s:SetUpPython() != 1 + return + endif + + call s:SetUpCommands() + call s:SetUpCpoptions() + call s:SetUpCompleteopt() + call s:SetUpKeyMappings() + + if g:ycm_show_diagnostics_ui + call s:TurnOffSyntasticForCFamily() + endif + + call s:SetUpSigns() + call s:SetUpSyntaxHighlighting() + + if g:ycm_allow_changing_updatetime && &updatetime > 2000 + set ut=2000 + endif + + call youcompleteme#EnableCursorMovedAutocommands() + augroup youcompleteme + autocmd! + " Note that these events will NOT trigger for the file vim is started with; + " so if you do "vim foo.cc", these events will not trigger when that buffer + " is read. This is because youcompleteme#Enable() is called on VimEnter and + " that happens *after" BufRead/BufEnter has already triggered for the + " initial file. + " We also need to trigger buf init code on the FileType event because when + " the user does :enew and then :set ft=something, we need to run buf init + " code again. + autocmd BufReadPre * call s:OnBufferReadPre( expand( '<afile>:p' ) ) + autocmd BufRead,BufEnter,FileType * call s:OnBufferVisit() + autocmd BufUnload * call s:OnBufferUnload( expand( '<afile>:p' ) ) + autocmd CursorHold,CursorHoldI * call s:OnCursorHold() + autocmd InsertLeave * call s:OnInsertLeave() + autocmd InsertEnter * call s:OnInsertEnter() + autocmd VimLeave * call s:OnVimLeave() + autocmd CompleteDone * call s:OnCompleteDone() + augroup END + + " Setting the omnifunc require us to ask the server if it has a Native + " Semantic Completer for the current buffer's filetype. When vim first start + " this mean that we have to wait for the server to be up and running which + " would block vim's GUI. To avoid this we defer setting the omnifunc the + " first time to when we enter Insert mode and then update it on every + " BufferVisit as normal. + if s:defer_omnifunc + augroup ycm_defer_omnifunc + autocmd! + autocmd InsertEnter * call s:SetOmnicompleteFunc() + \ | let s:defer_omnifunc = 0 + \ | autocmd! ycm_defer_omnifunc + augroup END + endif + + " Calling these once solves the problem of BufReadPre/BufRead/BufEnter not + " triggering for the first loaded file. This should be the last commands + " executed in this function! + call s:OnBufferReadPre( expand( '<afile>:p' ) ) + call s:OnBufferVisit() +endfunction + + +function! youcompleteme#EnableCursorMovedAutocommands() + augroup ycmcompletemecursormove + autocmd! + autocmd CursorMovedI * call s:OnCursorMovedInsertMode() + autocmd CursorMoved * call s:OnCursorMovedNormalMode() + augroup END +endfunction + + +function! youcompleteme#DisableCursorMovedAutocommands() + autocmd! ycmcompletemecursormove CursorMoved * + autocmd! ycmcompletemecursormove CursorMovedI * +endfunction + + +function! youcompleteme#GetErrorCount() + return s:Pyeval( 'ycm_state.GetErrorCount()' ) +endfunction + + +function! youcompleteme#GetWarningCount() + return s:Pyeval( 'ycm_state.GetWarningCount()' ) +endfunction + + +function! s:SetUpPython() abort + exec s:python_until_eof +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import + +import os +import sys +import traceback +import vim + +# Add python sources folder to the system path. +script_folder = vim.eval( 's:script_folder_path' ) +sys.path.insert( 0, os.path.join( script_folder, '..', 'python' ) ) + +from ycm.setup import SetUpSystemPaths, SetUpYCM + +# We enclose this code in a try/except block to avoid backtraces in Vim. +try: + SetUpSystemPaths() + + # Import the modules used in this file. + from ycm import base, vimsupport + + ycm_state = SetUpYCM() +except Exception as error: + # We don't use PostVimMessage or EchoText from the vimsupport module because + # importing this module may fail. + vim.command( 'redraw | echohl WarningMsg' ) + for line in traceback.format_exc().splitlines(): + vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) ) + + vim.command( "echo 'YouCompleteMe unavailable: {0}'" + .format( str( error ).replace( "'", "''" ) ) ) + vim.command( 'echohl None' ) + vim.command( 'return 0' ) +else: + vim.command( 'return 1' ) +EOF +endfunction + + +function! s:SetUpKeyMappings() + " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to + " exist and are now here purely for the sake of backwards compatibility; we + " don't want to break users if we can avoid it. + + if exists('g:ycm_key_select_completion') && + \ index(g:ycm_key_list_select_completion, + \ g:ycm_key_select_completion) == -1 + call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion) + endif + + if exists('g:ycm_key_previous_completion') && + \ index(g:ycm_key_list_previous_completion, + \ g:ycm_key_previous_completion) == -1 + call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion) + endif + + for key in g:ycm_key_list_select_completion + " With this command, when the completion window is visible, the tab key + " (default) will select the next candidate in the window. In vim, this also + " changes the typed-in text to that of the candidate completion. + exe 'inoremap <expr>' . key . + \ ' pumvisible() ? "\<C-n>" : "\' . key .'"' + endfor + + + for key in g:ycm_key_list_previous_completion + " This selects the previous candidate for shift-tab (default) + exe 'inoremap <expr>' . key . + \ ' pumvisible() ? "\<C-p>" : "\' . key .'"' + endfor + + if !empty( g:ycm_key_invoke_completion ) + let invoke_key = g:ycm_key_invoke_completion + + " Inside the console, <C-Space> is passed as <Nul> to Vim + if invoke_key ==# '<C-Space>' + imap <Nul> <C-Space> + endif + + " <c-x><c-o> trigger omni completion, <c-p> deselects the first completion + " candidate that vim selects by default + silent! exe 'inoremap <unique> ' . invoke_key . ' <C-X><C-O><C-P>' + endif + + if !empty( g:ycm_key_detailed_diagnostics ) + silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics . + \ ' :YcmShowDetailedDiagnostic<cr>' + endif +endfunction + + +function! s:SetUpSigns() + " We try to ensure backwards compatibility with Syntastic if the user has + " already defined styling for Syntastic highlight groups. + + if !hlexists( 'YcmErrorSign' ) + if hlexists( 'SyntasticErrorSign') + highlight link YcmErrorSign SyntasticErrorSign + else + highlight link YcmErrorSign error + endif + endif + + if !hlexists( 'YcmWarningSign' ) + if hlexists( 'SyntasticWarningSign') + highlight link YcmWarningSign SyntasticWarningSign + else + highlight link YcmWarningSign todo + endif + endif + + if !hlexists( 'YcmErrorLine' ) + highlight link YcmErrorLine SyntasticErrorLine + endif + + if !hlexists( 'YcmWarningLine' ) + highlight link YcmWarningLine SyntasticWarningLine + endif + + exe 'sign define YcmError text=' . g:ycm_error_symbol . + \ ' texthl=YcmErrorSign linehl=YcmErrorLine' + exe 'sign define YcmWarning text=' . g:ycm_warning_symbol . + \ ' texthl=YcmWarningSign linehl=YcmWarningLine' +endfunction + + +function! s:SetUpSyntaxHighlighting() + " We try to ensure backwards compatibility with Syntastic if the user has + " already defined styling for Syntastic highlight groups. + + if !hlexists( 'YcmErrorSection' ) + if hlexists( 'SyntasticError' ) + highlight link YcmErrorSection SyntasticError + else + highlight link YcmErrorSection SpellBad + endif + endif + + if !hlexists( 'YcmWarningSection' ) + if hlexists( 'SyntasticWarning' ) + highlight link YcmWarningSection SyntasticWarning + else + highlight link YcmWarningSection SpellCap + endif + endif +endfunction + + +function! s:SetUpBackwardsCompatibility() + let complete_in_comments_and_strings = + \ get( g:, 'ycm_complete_in_comments_and_strings', 0 ) + + if complete_in_comments_and_strings + let g:ycm_complete_in_strings = 1 + let g:ycm_complete_in_comments = 1 + endif + + " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist + if has_key( g:, 'ycm_filetypes_to_completely_ignore' ) + let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore + endif +endfunction + + +" Needed so that YCM is used instead of Syntastic +function! s:TurnOffSyntasticForCFamily() + let g:syntastic_cpp_checkers = [] + let g:syntastic_c_checkers = [] + let g:syntastic_objc_checkers = [] + let g:syntastic_objcpp_checkers = [] +endfunction + + +function! s:AllowedToCompleteInCurrentFile() + if empty( &filetype ) || + \ getbufvar( winbufnr( winnr() ), "&buftype" ) ==# 'nofile' || + \ &filetype ==# 'qf' + return 0 + endif + + if exists( 'b:ycm_largefile' ) + return 0 + endif + + let whitelist_allows = has_key( g:ycm_filetype_whitelist, '*' ) || + \ has_key( g:ycm_filetype_whitelist, &filetype ) + let blacklist_allows = !has_key( g:ycm_filetype_blacklist, &filetype ) + + return whitelist_allows && blacklist_allows +endfunction + + +function! s:SetUpCommands() + command! YcmRestartServer call s:RestartServer() + command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic() + command! YcmDebugInfo call s:DebugInfo() + command! -nargs=? -complete=custom,youcompleteme#LogsComplete + \ YcmToggleLogs call s:ToggleLogs(<f-args>) + command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete + \ YcmCompleter call s:CompleterCommand(<f-args>) + command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics() + command! YcmDiags call s:ShowDiagnostics() +endfunction + + +function! s:SetUpCpoptions() + " Without this flag in cpoptions, critical YCM mappings do not work. There's + " no way to not have this and have YCM working, so force the flag. + set cpoptions+=B + + " This prevents the display of "Pattern not found" & similar messages during + " completion. This is only available since Vim 7.4.314 + if s:Pyeval( 'vimsupport.VimVersionAtLeast("7.4.314")' ) + set shortmess+=c + endif +endfunction + + +function! s:SetUpCompleteopt() + " Some plugins (I'm looking at you, vim-notes) change completeopt by for + " instance adding 'longest'. This breaks YCM. So we force our settings. + " There's no two ways about this: if you want to use YCM then you have to + " have these completeopt settings, otherwise YCM won't work at all. + + " We need menuone in completeopt, otherwise when there's only one candidate + " for completion, the menu doesn't show up. + set completeopt-=menu + set completeopt+=menuone + + " This is unnecessary with our features. People use this option to insert + " the common prefix of all the matches and then add more differentiating chars + " so that they can select a more specific match. With our features, they + " don't need to insert the prefix; they just type the differentiating chars. + " Also, having this option set breaks the plugin. + set completeopt-=longest + + if g:ycm_add_preview_to_completeopt + set completeopt+=preview + endif +endfunction + + +" For various functions/use-cases, we want to keep track of whether the buffer +" has changed since the last time they were invoked. We keep the state of +" b:changedtick of the last time the specific function was called in +" b:ycm_changedtick. +function! s:SetUpYcmChangedTick() + let b:ycm_changedtick = + \ get( b:, 'ycm_changedtick', { + \ 'file_ready_to_parse' : -1, + \ } ) +endfunction + + +function! s:OnVimLeave() + exec s:python_command "ycm_state.OnVimLeave()" +endfunction + + +function! s:OnCompleteDone() + exec s:python_command "ycm_state.OnCompleteDone()" +endfunction + + +function! s:OnBufferReadPre(filename) + let threshold = g:ycm_disable_for_files_larger_than_kb * 1024 + + if threshold > 0 && getfsize( a:filename ) > threshold + echohl WarningMsg | + \ echomsg "YouCompleteMe is disabled in this buffer; " . + \ "the file exceeded the max size (see YCM options)." | + \ echohl None + let b:ycm_largefile = 1 + endif +endfunction + +function! s:OnBufferVisit() + " We need to do this even when we are not allowed to complete in the current + " file because we might be allowed to complete in the future! The canonical + " example is creating a new buffer with :enew and then setting a filetype. + call s:SetUpYcmChangedTick() + + if !s:AllowedToCompleteInCurrentFile() + return + endif + + call s:SetUpCompleteopt() + call s:SetCompleteFunc() + + if !s:defer_omnifunc + call s:SetOmnicompleteFunc() + endif + + exec s:python_command "ycm_state.OnBufferVisit()" + call s:OnFileReadyToParse() +endfunction + + +function! s:OnBufferUnload( deleted_buffer_file ) + if !s:AllowedToCompleteInCurrentFile() || empty( a:deleted_buffer_file ) + return + endif + + exec s:python_command "ycm_state.OnBufferUnload(" + \ "vim.eval( 'a:deleted_buffer_file' ) )" +endfunction + + +function! s:OnCursorHold() + if !s:AllowedToCompleteInCurrentFile() + return + endif + + call s:SetUpCompleteopt() + call s:OnFileReadyToParse() +endfunction + + +function! s:OnFileReadyToParse() + " We need to call this just in case there is no b:ycm_changetick; this can + " happen for special buffers. + call s:SetUpYcmChangedTick() + + " Order is important here; we need to extract any information before + " reparsing the file again. If we sent the new parse request first, then + " the response would always be pending when we called + " HandleFileParseRequest. + exec s:python_command "ycm_state.HandleFileParseRequest()" + + let buffer_changed = b:changedtick != b:ycm_changedtick.file_ready_to_parse + if buffer_changed + exec s:python_command "ycm_state.OnFileReadyToParse()" + endif + let b:ycm_changedtick.file_ready_to_parse = b:changedtick +endfunction + + +function! s:SetCompleteFunc() + let &completefunc = 'youcompleteme#Complete' + let &l:completefunc = 'youcompleteme#Complete' +endfunction + + +function! s:SetOmnicompleteFunc() + if s:Pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' ) + let &omnifunc = 'youcompleteme#OmniComplete' + let &l:omnifunc = 'youcompleteme#OmniComplete' + + " If we don't have native filetype support but the omnifunc is set to YCM's + " omnifunc because the previous file the user was editing DID have native + " support, we remove our omnifunc. + elseif &omnifunc == 'youcompleteme#OmniComplete' + let &omnifunc = '' + let &l:omnifunc = '' + endif +endfunction + +function! s:OnCursorMovedInsertMode() + if !s:AllowedToCompleteInCurrentFile() + return + endif + + exec s:python_command "ycm_state.OnCursorMoved()" + call s:UpdateCursorMoved() + + " Basically, we need to only trigger the completion menu when the user has + " inserted or deleted a character, NOT just when the user moves in insert mode + " (with, say, the arrow keys). If we trigger the menu even on pure moves, then + " it's impossible to move in insert mode since the up/down arrows start moving + " the selected completion in the completion menu. Yeah, people shouldn't be + " moving in insert mode at all (that's what normal mode is for) but explain + " that to the users who complain... + if !s:BufferTextChangedSinceLastMoveInInsertMode() + return + endif + + call s:IdentifierFinishedOperations() + if g:ycm_autoclose_preview_window_after_completion + call s:ClosePreviewWindowIfNeeded() + endif + + if g:ycm_auto_trigger || s:omnifunc_mode + call s:InvokeCompletion() + endif + + " We have to make sure we correctly leave omnifunc mode even when the user + " inserts something like a "operator[]" candidate string which fails + " CurrentIdentifierFinished check. + if s:omnifunc_mode && !s:Pyeval( 'base.LastEnteredCharIsIdentifierChar()') + let s:omnifunc_mode = 0 + endif +endfunction + + +function! s:OnCursorMovedNormalMode() + if !s:AllowedToCompleteInCurrentFile() + return + endif + + call s:OnFileReadyToParse() + exec s:python_command "ycm_state.OnCursorMoved()" +endfunction + + +function! s:OnInsertLeave() + if !s:AllowedToCompleteInCurrentFile() + return + endif + + let s:omnifunc_mode = 0 + call s:OnFileReadyToParse() + exec s:python_command "ycm_state.OnInsertLeave()" + if g:ycm_autoclose_preview_window_after_completion || + \ g:ycm_autoclose_preview_window_after_insertion + call s:ClosePreviewWindowIfNeeded() + endif +endfunction + + +function! s:OnInsertEnter() + let s:previous_num_chars_on_current_line = strlen( getline('.') ) + + if !s:AllowedToCompleteInCurrentFile() + return + endif + + let s:old_cursor_position = [] +endfunction + + +function! s:UpdateCursorMoved() + let current_position = getpos('.') + let s:cursor_moved = current_position != s:old_cursor_position + + let s:moved_vertically_in_insert_mode = s:old_cursor_position != [] && + \ current_position[ 1 ] != s:old_cursor_position[ 1 ] + + let s:old_cursor_position = current_position +endfunction + + +function! s:BufferTextChangedSinceLastMoveInInsertMode() + let num_chars_in_current_cursor_line = strlen( getline('.') ) + + if s:moved_vertically_in_insert_mode + let s:previous_num_chars_on_current_line = num_chars_in_current_cursor_line + return 0 + endif + + let changed_text_on_current_line = num_chars_in_current_cursor_line != + \ s:previous_num_chars_on_current_line + let s:previous_num_chars_on_current_line = num_chars_in_current_cursor_line + + return changed_text_on_current_line +endfunction + + +function! s:ClosePreviewWindowIfNeeded() + let current_buffer_name = bufname('') + + " We don't want to try to close the preview window in special buffers like + " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start + " with '['. + if current_buffer_name[ 0 ] == '[' + return + endif + + " This command does the actual closing of the preview window. If no preview + " window is shown, nothing happens. + pclose +endfunction + + +function! s:IdentifierFinishedOperations() + if !s:Pyeval( 'base.CurrentIdentifierFinished()' ) + return + endif + exec s:python_command "ycm_state.OnCurrentIdentifierFinished()" + let s:omnifunc_mode = 0 +endfunction + + +" Returns 1 when inside comment and 2 when inside string +function! s:InsideCommentOrString() + " Has to be col('.') -1 because col('.') doesn't exist at this point. We are + " in insert mode when this func is called. + let syntax_group = synIDattr( + \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name') + + if stridx(syntax_group, 'Comment') > -1 + return 1 + endif + + if stridx(syntax_group, 'String') > -1 + return 2 + endif + + return 0 +endfunction + + +function! s:InsideCommentOrStringAndShouldStop() + let retval = s:InsideCommentOrString() + let inside_comment = retval == 1 + let inside_string = retval == 2 + + if inside_comment && g:ycm_complete_in_comments || + \ inside_string && g:ycm_complete_in_strings + return 0 + endif + + return retval +endfunction + + +function! s:OnBlankLine() + return s:Pyeval( 'not vim.current.line or vim.current.line.isspace()' ) +endfunction + + +function! s:InvokeCompletion() + if &completefunc != "youcompleteme#Complete" + return + endif + + if s:InsideCommentOrStringAndShouldStop() || s:OnBlankLine() + return + endif + + " This is tricky. First, having 'refresh' set to 'always' in the dictionary + " that our completion function returns makes sure that our completion function + " is called on every keystroke. Second, when the sequence of characters the + " user typed produces no results in our search an infinite loop can occur. The + " problem is that our feedkeys call triggers the OnCursorMovedI event which we + " are tied to. We prevent this infinite loop from starting by making sure that + " the user has moved the cursor since the last time we provided completion + " results. + if !s:cursor_moved + return + endif + + " <c-x><c-u> invokes the user's completion function (which we have set to + " youcompleteme#Complete), and <c-p> tells Vim to select the previous + " completion candidate. This is necessary because by default, Vim selects the + " first candidate when completion is invoked, and selecting a candidate + " automatically replaces the current text with it. Calling <c-p> forces Vim to + " deselect the first candidate and in turn preserve the user's current text + " until he explicitly chooses to replace it with a completion. + call feedkeys( "\<C-X>\<C-U>\<C-P>", 'n' ) +endfunction + + +exec s:python_until_eof +def GetCompletionsInner(): + request = ycm_state.GetCurrentCompletionRequest() + request.Start() + while not request.Done(): + if bool( int( vim.eval( 'complete_check()' ) ) ): + return { 'words' : [], 'refresh' : 'always'} + + results = base.AdjustCandidateInsertionText( request.Response() ) + return { 'words' : results, 'refresh' : 'always' } +EOF + + +function! s:GetCompletions() + exec s:python_command "results = GetCompletionsInner()" + let results = s:Pyeval( 'results' ) + return results +endfunction + + +" This is our main entry point. This is what vim calls to get completions. +function! youcompleteme#Complete( findstart, base ) + " After the user types one character after the call to the omnifunc, the + " completefunc will be called because of our mapping that calls the + " completefunc on every keystroke. Therefore we need to delegate the call we + " 'stole' back to the omnifunc + if s:omnifunc_mode + return youcompleteme#OmniComplete( a:findstart, a:base ) + endif + + if a:findstart + " InvokeCompletion has this check but we also need it here because of random + " Vim bugs and unfortunate interactions with the autocommands of other + " plugins + if !s:cursor_moved + " for vim, -2 means not found but don't trigger an error message + " see :h complete-functions + return -2 + endif + + if !s:Pyeval( 'ycm_state.IsServerAlive()' ) + return -2 + endif + exec s:python_command "ycm_state.CreateCompletionRequest()" + return s:Pyeval( 'base.CompletionStartColumn()' ) + else + return s:GetCompletions() + endif +endfunction + + +function! youcompleteme#OmniComplete( findstart, base ) + if a:findstart + if !s:Pyeval( 'ycm_state.IsServerAlive()' ) + return -2 + endif + let s:omnifunc_mode = 1 + exec s:python_command "ycm_state.CreateCompletionRequest(" + \ "force_semantic = True )" + return s:Pyeval( 'base.CompletionStartColumn()' ) + else + return s:GetCompletions() + endif +endfunction + + +function! youcompleteme#ServerPid() + return s:Pyeval( 'ycm_state.ServerPid()' ) +endfunction + + +function! s:RestartServer() + exec s:python_command "ycm_state.RestartServer()" +endfunction + + +function! s:ShowDetailedDiagnostic() + exec s:python_command "ycm_state.ShowDetailedDiagnostic()" +endfunction + + +function! s:DebugInfo() + echom "Printing YouCompleteMe debug information..." + let debug_info = s:Pyeval( 'ycm_state.DebugInfo()' ) + for line in split( debug_info, "\n" ) + echom '-- ' . line + endfor +endfunction + + +function! s:ToggleLogs(...) + let stderr = a:0 == 0 || a:1 !=? 'stdout' + let stdout = a:0 == 0 || a:1 !=? 'stderr' + exec s:python_command "ycm_state.ToggleLogs(" + \ "stdout = vimsupport.GetBoolValue( 'l:stdout' )," + \ "stderr = vimsupport.GetBoolValue( 'l:stderr' ) )" +endfunction + + +function! s:CompleterCommand(...) + " CompleterCommand will call the OnUserCommand function of a completer. + " If the first arguments is of the form "ft=..." it can be used to specify the + " completer to use (for example "ft=cpp"). Else the native filetype completer + " of the current buffer is used. If no native filetype completer is found and + " no completer was specified this throws an error. You can use + " "ft=ycm:ident" to select the identifier completer. + " The remaining arguments will be passed to the completer. + let arguments = copy(a:000) + let completer = '' + + if a:0 > 0 && strpart(a:1, 0, 3) == 'ft=' + if a:1 == 'ft=ycm:ident' + let completer = 'identifier' + endif + let arguments = arguments[1:] + endif + + exec s:python_command "ycm_state.SendCommandRequest(" + \ "vim.eval( 'l:arguments' ), vim.eval( 'l:completer' ) ) " +endfunction + + +function! youcompleteme#OpenGoToList() + exec s:python_command "vimsupport.PostVimMessage(" + \ "'WARNING: youcompleteme#OpenGoToList function is deprecated." + \ "Do NOT use it.')" + exec s:python_command "vimsupport.OpenQuickFixList( True, True )" +endfunction + + +function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos ) + return "stdout\nstderr" +endfunction + + +function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos ) + return join( s:Pyeval( 'ycm_state.GetDefinedSubcommands()' ), + \ "\n") +endfunction + + +function! s:ForceCompile() + if !s:Pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' ) + echom "Native filetype completion not supported for current file, " + \ . "cannot force recompilation." + return 0 + endif + + echom "Forcing compilation, this will block Vim until done." + exec s:python_command "ycm_state.OnFileReadyToParse()" + exec s:python_command "ycm_state.HandleFileParseRequest( True )" + + return 1 +endfunction + + +function! s:ForceCompileAndDiagnostics() + let compilation_succeeded = s:ForceCompile() + if !compilation_succeeded + return + endif + echom "Diagnostics refreshed." +endfunction + + +function! s:ShowDiagnostics() + let compilation_succeeded = s:ForceCompile() + if !compilation_succeeded + return + endif + + if s:Pyeval( 'ycm_state.PopulateLocationListWithLatestDiagnostics()' ) + if g:ycm_open_loclist_on_ycm_diags + lopen + endif + else + echom "No warnings or errors detected" + endif +endfunction + + +" This is basic vim plugin boilerplate +let &cpo = s:save_cpo +unlet s:save_cpo diff --git a/vim/bundle/YouCompleteMe/ci/appveyor/appveyor_install.bat b/vim/bundle/YouCompleteMe/ci/appveyor/appveyor_install.bat new file mode 100755 index 0000000..33c7807 --- /dev/null +++ b/vim/bundle/YouCompleteMe/ci/appveyor/appveyor_install.bat @@ -0,0 +1,22 @@ +git submodule update --init --recursive +:: Batch script will not exit if a command returns an error, so we manually do +:: it for commands that may fail. +if %errorlevel% neq 0 exit /b %errorlevel% + +:: +:: Python configuration +:: + +if %arch% == 32 ( + set python_path=C:\Python%python% +) else ( + set python_path=C:\Python%python%-x64 +) + +set PATH=%python_path%;%python_path%\Scripts;%PATH% +python --version + +appveyor DownloadFile https://bootstrap.pypa.io/get-pip.py +python get-pip.py +pip install -r python\test_requirements.txt +if %errorlevel% neq 0 exit /b %errorlevel% diff --git a/vim/bundle/YouCompleteMe/ci/travis/travis_install.linux.sh b/vim/bundle/YouCompleteMe/ci/travis/travis_install.linux.sh new file mode 100644 index 0000000..52d400e --- /dev/null +++ b/vim/bundle/YouCompleteMe/ci/travis/travis_install.linux.sh @@ -0,0 +1,5 @@ +# Linux-specific installation + +# In order to work with ycmd, python *must* be built as a shared library. This +# is set via the PYTHON_CONFIGURE_OPTS option. +export PYTHON_CONFIGURE_OPTS="--enable-shared" diff --git a/vim/bundle/YouCompleteMe/ci/travis/travis_install.osx.sh b/vim/bundle/YouCompleteMe/ci/travis/travis_install.osx.sh new file mode 100644 index 0000000..3873f93 --- /dev/null +++ b/vim/bundle/YouCompleteMe/ci/travis/travis_install.osx.sh @@ -0,0 +1,24 @@ +# OS X-specific installation + +# There's a homebrew bug which causes brew update to fail the first time. Run +# it twice to workaround. https://github.com/Homebrew/homebrew/issues/42553 +brew update || brew update + +# List of homebrew formulae to install in the order they appear. +# These are dependencies of pyenv. +REQUIREMENTS="ninja + readline + autoconf + pkg-config + openssl" + +# Install pyenv and dependencies +for pkg in $REQUIREMENTS; do + # Install package, or upgrade it if it is already installed + brew install $pkg || brew outdated $pkg || brew upgrade $pkg +done + +# In order to work with ycmd, python *must* be built as a shared library. The +# most compatible way to do this on OS X is with --enable-framework. This is +# set via the PYTHON_CONFIGURE_OPTS option +export PYTHON_CONFIGURE_OPTS="--enable-framework" diff --git a/vim/bundle/YouCompleteMe/ci/travis/travis_install.sh b/vim/bundle/YouCompleteMe/ci/travis/travis_install.sh new file mode 100644 index 0000000..0060de9 --- /dev/null +++ b/vim/bundle/YouCompleteMe/ci/travis/travis_install.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +set -ev + +#################### +# OS-specific setup +#################### + +# Requirements of OS-specific install: +# - install any software which is not installed by Travis configuration +# - set up everything necessary so that pyenv can build python +source ci/travis/travis_install.${TRAVIS_OS_NAME}.sh + +############# +# pyenv setup +############# + +export PYENV_ROOT="${HOME}/.pyenv" + +if [ ! -d "${PYENV_ROOT}/.git" ]; then + git clone https://github.com/yyuu/pyenv.git ${PYENV_ROOT} +fi +pushd ${PYENV_ROOT} +git fetch --tags +git checkout v20160202 +popd + +export PATH="${PYENV_ROOT}/bin:${PATH}" + +eval "$(pyenv init -)" + +if [ "${YCM_PYTHON_VERSION}" == "2.6" ]; then + PYENV_VERSION="2.6.6" +elif [ "${YCM_PYTHON_VERSION}" == "2.7" ]; then + PYENV_VERSION="2.7.6" +else + PYENV_VERSION="3.3.6" +fi + +pyenv install --skip-existing ${PYENV_VERSION} +pyenv rehash +pyenv global ${PYENV_VERSION} + +# It is quite easy to get the above series of steps wrong. Verify that the +# version of python actually in the path and used is the version that was +# requested, and fail the build if we broke the travis setup +python_version=$(python -c 'import sys; print( "{0}.{1}".format( sys.version_info[0], sys.version_info[1] ) )') +echo "Checking python version (actual ${python_version} vs expected ${YCM_PYTHON_VERSION})" +test ${python_version} == ${YCM_PYTHON_VERSION} + +############ +# pip setup +############ + +pip install -U pip wheel setuptools +pip install -r python/test_requirements.txt + +# The build infrastructure prints a lot of spam after this script runs, so make +# sure to disable printing, and failing on non-zero exit code after this script +# finishes +set +ev diff --git a/vim/bundle/YouCompleteMe/doc/youcompleteme.txt b/vim/bundle/YouCompleteMe/doc/youcompleteme.txt new file mode 100644 index 0000000..4a7bfd7 --- /dev/null +++ b/vim/bundle/YouCompleteMe/doc/youcompleteme.txt @@ -0,0 +1,3209 @@ +*youcompleteme* YouCompleteMe: a code-completion engine for Vim + +=============================================================================== +Contents ~ + + 1. Introduction |youcompleteme-introduction| + 2. Intro |youcompleteme-intro| + 3. Installation |youcompleteme-installation| + 1. Mac OS X |youcompleteme-mac-os-x| + 2. Ubuntu Linux x64 |youcompleteme-ubuntu-linux-x64| + 3. Fedora Linux x64 |youcompleteme-fedora-linux-x64| + 4. Windows |youcompleteme-windows| + 5. FreeBSD/OpenBSD |youcompleteme-freebsd-openbsd| + 6. Full Installation Guide |youcompleteme-full-installation-guide| + 4. Quick Feature Summary |youcompleteme-quick-feature-summary| + 1. General (all languages) |youcompleteme-general| + 2. C-family languages (C, C++, Objective C, Objective C++) |youcompleteme-c-family-languages| + 3. C♯ |youcompleteme-c| + 4. Python |youcompleteme-python| + 5. Go |youcompleteme-go| + 6. TypeScript |youcompleteme-typescript| + 7. JavaScript |youcompleteme-javascript| + 8. Rust |youcompleteme-rust| + 5. User Guide |youcompleteme-user-guide| + 1. General Usage |youcompleteme-general-usage| + 2. Client-Server Architecture |youcompleteme-client-server-architecture| + 3. Completion String Ranking |youcompleteme-completion-string-ranking| + 4. General Semantic Completion |youcompleteme-general-semantic-completion| + 5. C-family Semantic Completion |youcompleteme-c-family-semantic-completion| + 6. JavaScript Semantic Completion |youcompleteme-javascript-semantic-completion| + 1. Quick start |youcompleteme-quick-start| + 2. Explanation |youcompleteme-explanation| + 3. Tips and tricks |youcompleteme-tips-tricks| + 1. Configuring Tern for node support |youcompleteme-configuring-tern-for-node-support| + 2. Configuring Tern for requirejs support |youcompleteme-configuring-tern-for-requirejs-support| + 7. Rust Semantic Completion |youcompleteme-rust-semantic-completion| + 8. Python Semantic Completion |youcompleteme-python-semantic-completion| + 9. Semantic Completion for Other Languages |youcompleteme-semantic-completion-for-other-languages| + 10. Writing New Semantic Completers |youcompleteme-writing-new-semantic-completers| + 11. Diagnostic Display |youcompleteme-diagnostic-display| + 1. Diagnostic Highlighting Groups |youcompleteme-diagnostic-highlighting-groups| + 6. Commands |youcompleteme-commands| + 1. The |:YcmRestartServer| command + 2. The |:YcmForceCompileAndDiagnostics| command + 3. The |:YcmDiags| command + 4. The |:YcmShowDetailedDiagnostic| command + 5. The |:YcmDebugInfo| command + 6. The |:YcmToggleLogs| command + 7. The |:YcmCompleter| command + 7. YcmCompleter Subcommands |youcompleteme-ycmcompleter-subcommands| + 1. GoTo Commands |youcompleteme-goto-commands| + 1. The |GoToInclude| subcommand + 2. The |GoToDeclaration| subcommand + 3. The |GoToDefinition| subcommand + 4. The |GoTo| subcommand + 5. The |GoToImprecise| subcommand + 6. The |GoToReferences| subcommand + 7. The |GoToImplementation| subcommand + 8. The |GoToImplementationElseDeclaration| subcommand + 2. Semantic Information Commands |youcompleteme-semantic-information-commands| + 1. The |GetType| subcommand + 2. The |GetParent| subcommand + 3. The |GetDoc| subcommand + 3. Refactoring and FixIt Commands |youcompleteme-refactoring-fixit-commands| + 1. The |FixIt| subcommand + 2. The 'RefactorRename <new name>' subcommand |RefactorRename-new-name| + 3. Multi-file Refactor |youcompleteme-multi-file-refactor| + 4. Miscellaneous Commands |youcompleteme-miscellaneous-commands| + 1. The |ClearCompilationFlagCache| subcommand + 2. The |StartServer| subcommand + 3. The |StopServer| subcommand + 4. The |RestartServer| subcommand + 5. The |ReloadSolution| subcommand + 8. Functions |youcompleteme-functions| + 1. The |youcompleteme#GetErrorCount| function + 2. The |youcompleteme#GetWarningCount| function + 9. Autocommands |youcompleteme-autocommands| + 1. The |YcmQuickFixOpened| autocommand + 10. Options |youcompleteme-options| + 1. The |g:ycm_min_num_of_chars_for_completion| option + 2. The |g:ycm_min_num_identifier_candidate_chars| option + 3. The |g:ycm_auto_trigger| option + 4. The |g:ycm_filetype_whitelist| option + 5. The |g:ycm_filetype_blacklist| option + 6. The |g:ycm_filetype_specific_completion_to_disable| option + 7. The |g:ycm_show_diagnostics_ui| option + 8. The |g:ycm_error_symbol| option + 9. The |g:ycm_warning_symbol| option + 10. The |g:ycm_enable_diagnostic_signs| option + 11. The |g:ycm_enable_diagnostic_highlighting| option + 12. The |g:ycm_echo_current_diagnostic| option + 13. The |g:ycm_always_populate_location_list| option + 14. The |g:ycm_open_loclist_on_ycm_diags| option + 15. The |g:ycm_allow_changing_updatetime| option + 16. The |g:ycm_complete_in_comments| option + 17. The |g:ycm_complete_in_strings| option + 18. The |g:ycm_collect_identifiers_from_comments_and_strings| option + 19. The |g:ycm_collect_identifiers_from_tags_files| option + 20. The |g:ycm_seed_identifiers_with_syntax| option + 21. The |g:ycm_extra_conf_vim_data| option + 22. The |g:ycm_server_python_interpreter| option + 23. The |g:ycm_server_keep_logfiles| option + 24. The |g:ycm_server_log_level| option + 25. The |g:ycm_auto_start_csharp_server| option + 26. The |g:ycm_auto_stop_csharp_server| option + 27. The |g:ycm_csharp_server_port| option + 28. The |g:ycm_csharp_insert_namespace_expr| option + 29. The |g:ycm_add_preview_to_completeopt| option + 30. The |g:ycm_autoclose_preview_window_after_completion| option + 31. The |g:ycm_autoclose_preview_window_after_insertion| option + 32. The |g:ycm_max_diagnostics_to_display| option + 33. The |g:ycm_key_list_select_completion| option + 34. The |g:ycm_key_list_previous_completion| option + 35. The |g:ycm_key_invoke_completion| option + 36. The |g:ycm_key_detailed_diagnostics| option + 37. The |g:ycm_global_ycm_extra_conf| option + 38. The |g:ycm_confirm_extra_conf| option + 39. The |g:ycm_extra_conf_globlist| option + 40. The |g:ycm_filepath_completion_use_working_dir| option + 41. The |g:ycm_semantic_triggers| option + 42. The |g:ycm_cache_omnifunc| option + 43. The |g:ycm_use_ultisnips_completer| option + 44. The |g:ycm_goto_buffer_command| option + 45. The |g:ycm_disable_for_files_larger_than_kb| option + 46. The |g:ycm_python_binary_path| option + 11. FAQ |youcompleteme-faq| + 1. I used to be able to 'import vim' in '.ycm_extra_conf.py', but now can't |import-vim| + 2. On very rare occasions Vim crashes when I tab through the completion menu |youcompleteme-on-very-rare-occasions-vim-crashes-when-i-tab-through-completion-menu| + 3. I get |ImportError| exceptions that mention 'PyInit_ycm_core' or 'initycm_core' + 4. I get a linker warning regarding |libpython| on Mac when compiling YCM + 5. I get a weird window at the top of my file when I use the semantic engine |youcompleteme-i-get-weird-window-at-top-of-my-file-when-i-use-semantic-engine| + 6. It appears that YCM is not working |youcompleteme-it-appears-that-ycm-is-not-working| + 7. Sometimes it takes much longer to get semantic completions than normal |youcompleteme-sometimes-it-takes-much-longer-to-get-semantic-completions-than-normal| + 8. YCM auto-inserts completion strings I don't want! |youcompleteme-ycm-auto-inserts-completion-strings-i-dont-want| + 9. I get a 'E227: mapping already exists for <blah>' error when I start Vim |E227:-mapping-already-exists-for-blah| + 10. I get "'GLIBC_2.XX' not found (required by libclang.so)" when starting Vim |GLIBC_2.XX-not-found()| + 11. I'm trying to use a Homebrew Vim with YCM and I'm getting segfaults |youcompleteme-im-trying-to-use-homebrew-vim-with-ycm-im-getting-segfaults| + 12. I have a Homebrew Python and/or MacVim; can't compile/SIGABRT when starting |youcompleteme-i-have-homebrew-python-and-or-macvim-cant-compile-sigabrt-when-starting| + 13. Vim segfaults when I use the semantic completer in Ruby files |youcompleteme-vim-segfaults-when-i-use-semantic-completer-in-ruby-files| + 14. I get 'LONG_BIT definition appears wrong for platform' when compiling |LONG_BIT-definition-appears-wrong-for-platform| + 15. I get 'libpython2.7.a [...] relocation R_X86_64_32' when compiling |libpython2.7.a-...-relocation-R_X86_64_32| + 16. I get 'Vim: Caught deadly signal SEGV' on Vim startup |Vim:-Caught-deadly-signal-SEGV| + 17. I get 'Fatal Python error: PyThreadState_Get: no current thread' on startup |Fatal-Python-error:-PyThreadState_Get:-no-current-thread| + 12. |install.py| says python must be compiled with '--enable-framework'. Wat? + 1. YCM does not read identifiers from my tags files |youcompleteme-ycm-does-not-read-identifiers-from-my-tags-files| + 2. 'CTRL-U' in insert mode does not work |CTRL-sub-U| + 3. YCM conflicts with UltiSnips TAB key usage |youcompleteme-ycm-conflicts-with-ultisnips-tab-key-usage| + 4. Why isn't YCM just written in plain VimScript, FFS? |youcompleteme-why-isnt-ycm-just-written-in-plain-vimscript-ffs| + 5. Why does YCM demand such a recent version of Vim? |youcompleteme-why-does-ycm-demand-such-recent-version-of-vim| + 6. I get annoying messages in Vim's status area when I type |youcompleteme-i-get-annoying-messages-in-vims-status-area-when-i-type| + 7. Nasty bugs happen if I have the 'vim-autoclose' plugin installed |vim-sub-autoclose| + 8. Is there some sort of YCM mailing list? I have questions |youcompleteme-is-there-sort-of-ycm-mailing-list-i-have-questions| + 9. I get an internal compiler error when installing |youcompleteme-i-get-an-internal-compiler-error-when-installing| + 10. I get weird errors when I press 'Ctrl-C' in Vim |Ctrl-sub-C| + 11. Why did YCM stop using Syntastic for diagnostics display? |youcompleteme-why-did-ycm-stop-using-syntastic-for-diagnostics-display| + 12. Completion doesn't work with the C++ standard library headers |youcompleteme-completion-doesnt-work-with-c-standard-library-headers| + 13. When I open a JavaScript file, I get an annoying warning about '.tern-project' +file |.tern-sub-project| + 14. When I start vim I get a runtime error saying 'R6034 An application has made an +attempt to load the C runtime library incorrectly.' |R6034-An-application-has-made-an-attempt-to-load-the-C-runtime-library-incorrectly.| + 15. I hear that YCM only supports Python 2, is that true? |youcompleteme-i-hear-that-ycm-only-supports-python-2-is-that-true| + 16. On Windows I get "E887: Sorry, this command is disabled, the Python's site +module could not be loaded" |E887:-Sorry-this-command-is-disabled-the-Python-s-site-module-could-not-be-loaded| + 17. I can't complete python packages in a virtual environment. |youcompleteme-i-cant-complete-python-packages-in-virtual-environment.| + 13. Contributor Code of Conduct |youcompleteme-contributor-code-of-conduct| + 14. Contact |youcompleteme-contact| + 15. License |youcompleteme-license| + 16. References |youcompleteme-references| + +=============================================================================== + *youcompleteme-introduction* +Introduction ~ + +Image: Build Status [1] Image: Build status [3] + +- Intro +- Installation + + - Mac OS X + - Ubuntu Linux x64 + - Fedora Linux x64 + - Windows + - FreeBSD/OpenBSD + - Full Installation Guide + +- Quick Feature Summary +- User Guide + + - General Usage + - Client-Server Architecture + - Completion String Ranking + - General Semantic Completion + - C-family Semantic Completion + - JavaScript Semantic Completion + - Rust Semantic Completion + - Python Semantic Completion + - Semantic Completion for Other Languages + - Writing New Semantic Completers + - Diagnostic Display + + - Diagnostic Highlighting Groups + +- Commands + + - YcmCompleter subcommands + + - GoTo Commands + - Semantic Information Commands + - Refactoring and FixIt Commands + - Miscellaneous Commands + +- Functions +- Autocommands +- Options +- FAQ +- Contributor Code of Conduct +- Contact +- License + +=============================================================================== + *youcompleteme-intro* +Intro ~ + +YouCompleteMe is a fast, as-you-type, fuzzy-search code completion engine for +Vim. It has several completion engines: + +- an identifier-based engine that works with every programming language, + +- a Clang [5]-based engine that provides native semantic code completion for + C/C++/Objective-C/Objective-C++ (from now on referred to as "the C-family + languages"), + +- a Jedi [6]-based completion engine for Python 2 and 3 (using the JediHTTP + [7] wrapper), + +- an OmniSharp [8]-based completion engine for C#, + +- a combination of Gocode [9] and Godef [10] semantic engines for Go, + +- a TSServer [11]-based completion engine for TypeScript, + +- a Tern [12]-based completion engine for JavaScript, + +- a racer [13]-based completion engine for Rust, + +- and an omnifunc-based completer that uses data from Vim's omnicomplete + system to provide semantic completions for many other languages (Ruby, PHP + etc.). + + Image: YouCompleteMe GIF demo (see reference [14]) + +Here's an explanation of what happens in the short GIF demo above. + +First, realize that **no keyboard shortcuts had to be pressed** to get the list +of completion candidates at any point in the demo. The user just types and the +suggestions pop up by themselves. If the user doesn't find the completion +suggestions relevant and/or just wants to type, they can do so; the completion +engine will not interfere. + +When the user sees a useful completion string being offered, they press the TAB +key to accept it. This inserts the completion string. Repeated presses of the +TAB key cycle through the offered completions. + +If the offered completions are not relevant enough, the user can continue +typing to further filter out unwanted completions. + +A critical thing to notice is that the completion **filtering is NOT based on +the input being a string prefix of the completion** (but that works too). The +input needs to be a _subsequence [15] match_ of a completion. This is a fancy +way of saying that any input characters need to be present in a completion +string in the order in which they appear in the input. So 'abc' is a +subsequence of 'xaybgc', but not of 'xbyxaxxc'. After the filter, a complicated +sorting system ranks the completion strings so that the most relevant ones rise +to the top of the menu (so you usually need to press TAB just once). + +**All of the above works with any programming language** because of the +identifier-based completion engine. It collects all of the identifiers in the +current file and other files you visit (and your tags files) and searches them +when you type (identifiers are put into per-filetype groups). + +The demo also shows the semantic engine in use. When the user presses '.', '->' +or '::' while typing in insert mode (for C++; different triggers are used for +other languages), the semantic engine is triggered (it can also be triggered +with a keyboard shortcut; see the rest of the docs). + +The last thing that you can see in the demo is YCM's diagnostic display +features (the little red X that shows up in the left gutter; inspired by +Syntastic [16]) if you are editing a C-family file. As Clang compiles your file +and detects warnings or errors, they will be presented in various ways. You +don't need to save your file or press any keyboard shortcut to trigger this, it +"just happens" in the background. + +In essence, YCM obsoletes the following Vim plugins because it has all of their +features plus extra: + +- clang_complete +- AutoComplPop +- Supertab +- neocomplcache + +**And that's not all...** + +YCM also provides semantic IDE-like features in a number of languages, +including: + +- finding declarations, definitions, usages, etc. of identifiers, +- displaying type information for classes, variables, functions etc., +- displaying documentation for methods, members, etc. in the preview window, +- fixing common coding errors, like missing semi-colons, typos, etc., +- semantic renaming of variables across files (JavaScript only). + +Features vary by file type, so make sure to check out the file type feature +summary and the full list of completer subcommands to find out what's available +for your favourite languages. + +You'll also find that YCM has filepath completers (try typing './' in a file) +and a completer that integrates with UltiSnips [17]. + +=============================================================================== + *youcompleteme-installation* +Installation ~ + +------------------------------------------------------------------------------- + *youcompleteme-mac-os-x* +Mac OS X ~ + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Install the latest version of MacVim [18]. Yes, MacVim. And yes, the _latest_. + +If you don't use the MacVim GUI, it is recommended to use the Vim binary that +is inside the MacVim.app package ('MacVim.app/Contents/MacOS/Vim'). To ensure +it works correctly copy the 'mvim' script from the MacVim [18] download to your +local binary folder (for example '/usr/local/bin/mvim') and then symlink it: +> + ln -s /usr/local/bin/mvim vim +< +Install YouCompleteMe with Vundle [19]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +**NOTE:** If you want C-family completion, you MUST have the latest Xcode +installed along with the latest Command Line Tools (they are installed +automatically when you run 'clang' for the first time, or manually by running +'xcode-select --install') + +Install CMake. Preferably with Homebrew [20], but here's the stand-alone CMake +installer [21]. + +_If_ you have installed a Homebrew Python and/or Homebrew MacVim, see the _FAQ_ +for details. + +Compiling YCM **with** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer +< +Compiling YCM **without** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py +< +The following additional language support options are available: + +- C# support: install Mono with Homebrew [20] or by downloading the Mono Mac + package [22] and add '--omnisharp-completer' when calling './install.py'. + +- Go support: install Go [23] and add '--gocode-completer' when calling + './install.py'. + +- TypeScript support: install Node.js and npm [24] then install the + TypeScript SDK with 'npm install -g typescript'. + +- JavaScript support: install Node.js and npm [24] and add '--tern-completer' + when calling './install.py'. + +- Rust support: install Rust [25] and add '--racer-completer' when calling + './install.py'. + +To simply compile with everything enabled, there's a '--all' flag. So, to +install with all language features, ensure 'xbuild', 'go', 'tsserver', 'node', +'npm', 'rustc', and 'cargo' tools are installed and in your 'PATH', then simply +run: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all +< +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +------------------------------------------------------------------------------- + *youcompleteme-ubuntu-linux-x64* +Ubuntu Linux x64 ~ + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Make sure you have Vim 7.3.598 with python2 or python3 support. Ubuntu 14.04 +and later have a Vim that's recent enough. You can see the version of Vim +installed by running 'vim --version'. If the version is too old, you may need +to compile Vim from source [26] (don't worry, it's easy). + +Install YouCompleteMe with Vundle [19]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +Install development tools and CMake: 'sudo apt-get install build-essential +cmake' + +Make sure you have Python headers installed: 'sudo apt-get install python-dev +python3-dev'. + +Compiling YCM **with** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer +< +Compiling YCM **without** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py +< +The following additional language support options are available: + +- C# support: install Mono [27] and add '--omnisharp-completer' when calling + './install.py'. + +- Go support: install Go [23] and add '--gocode-completer' when calling + './install.py'. + +- TypeScript support: install Node.js and npm [24] then install the + TypeScript SDK with 'npm install -g typescript'. + +- JavaScript support: install Node.js and npm [24] and add '--tern-completer' + when calling './install.py'. + +- Rust support: install Rust [25] and add '--racer-completer' when calling + './install.py'. + +To simply compile with everything enabled, there's a '--all' flag. So, to +install with all language features, ensure 'xbuild', 'go', 'tsserver', 'node', +'npm', 'rustc', and 'cargo' tools are installed and in your 'PATH', then simply +run: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all +< +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +------------------------------------------------------------------------------- + *youcompleteme-fedora-linux-x64* +Fedora Linux x64 ~ + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +Make sure you have Vim 7.3.598 with Python 2 or Python 3 support. Fedora 21 and +later have a Vim that's recent enough. You can see the version of Vim installed +by running 'vim --version'. If the version is too old, you may need to compile +Vim from source [26] (don't worry, it's easy). + +Install YouCompleteMe with Vundle [19]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +Install development tools and CMake: 'sudo dnf install automake gcc gcc-c++ +kernel-devel cmake' + +Make sure you have Python headers installed: 'sudo dnf install python-devel +python3-devel'. + +Compiling YCM **with** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer +< +Compiling YCM **without** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py +< +The following additional language support options are available: + +- C# support: install Mono [28] and add '--omnisharp-completer' when calling + './install.py'. + +- Go support: install Go [23] and add '--gocode-completer' when calling + './install.py'. + +- TypeScript support: install Node.js and npm [24] then install the + TypeScript SDK with 'npm install -g typescript'. + +- JavaScript support: install Node.js and npm [24] and add '--tern-completer' + when calling './install.py'. + +- Rust support: install Rust [25] and add '--racer-completer' when calling + './install.py'. + +To simply compile with everything enabled, there's a '--all' flag. So, to +install with all language features, ensure 'xbuild', 'go', 'tsserver', 'node', +'npm', 'rustc', and 'cargo' tools are installed and in your 'PATH', then simply +run: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all +< +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +------------------------------------------------------------------------------- + *youcompleteme-windows* +Windows ~ + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. + +**Important:** we assume that you are using the 'cmd.exe' command prompt and +that you know how to add an executable to the PATH environment variable. + +Make sure you have at least Vim 7.3.598 with Python 2 or Python 3 support. You +can check the version and which Python is supported by typing ':version' inside +Vim. Look at the features included: '+python/dyn' for Python 2 and +'+python3/dyn' for Python 3. Take note of the Vim architecture, i.e. 32 or +64-bit. It will be important when choosing the Python installer. We recommend +using a 64-bit client. Daily updated copies of 32-bit and 64-bit Vim with +Python 2 and Python 3 support [29] are available. + +Install YouCompleteMe with Vundle [19]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +Download and install the following software: + +- Python 2 or Python 3 [30]. Be sure to pick the version corresponding to + your Vim architecture. It is _Windows x86_ for a 32-bit Vim and _Windows + x86-64_ for a 64-bit Vim. We recommend installing Python 3. + +- CMake [21]. Add CMake executable to the PATH environment variable. + +- Visual Studio [31]. Download the community edition. During setup, choose + _Custom_ as the installation type and select the _Visual C++_ component. + +- 7-zip [32]. Required to build YCM with semantic support for C-family + languages. + +Compiling YCM **with** semantic support for C-family languages: +> + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + install.py --clang-completer +< +Compiling YCM **without** semantic support for C-family languages: +> + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + install.py +< +The following additional language support options are available: + +- C# support: add '--omnisharp-completer' when calling |install.py|. Be sure + that the build utility 'msbuild' is in your PATH [33]. + +- Go support: install Go [23] and add '--gocode-completer' when calling + |install.py|. + +- TypeScript support: install Node.js and npm [24] then install the + TypeScript SDK with 'npm install -g typescript'. + +- JavaScript support: install Node.js and npm [24] and add '--tern-completer' + when calling |install.py|. + +- Rust support: install Rust [25] and add '--racer-completer' when calling + |install.py|. + +To simply compile with everything enabled, there's a '--all' flag. So, to +install with all language features, ensure 'msbuild', 'go', 'tsserver', 'node', +'npm', and 'cargo' tools are installed and in your 'PATH', then simply run: +> + cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe + python install.py --all +< +You can specify the Microsoft Visual C++ (MSVC) version using the '--msvc' +option. YCM officially supports MSVC 11 (Visual Studio 2012), 12 (2013), and 14 +(2015). + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +------------------------------------------------------------------------------- + *youcompleteme-freebsd-openbsd* +FreeBSD/OpenBSD ~ + +Please refer to the full Installation Guide below; the following commands are +provided on a best-effort basis and may not work for you. OpenBSD / FreeBSD are +not officially supported platforms by YCM. + +Make sure you have Vim 7.3.598 with Python 2 or Python 3 support. + +OpenBSD 5.5 and later have a Vim that's recent enough. You can see the version +of Vim installed by running 'vim --version'. + +FreeBSD 10.x comes with clang compiler but not the libraries needed to install. +> + pkg install llvm35 boost-all boost-python-libs clang35 + export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/llvm35/lib/ +< +Install YouCompleteMe with Vundle [19]. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +Install dependencies and CMake: 'sudo pkg_add llvm boost cmake' + +Compiling YCM **with** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --clang-completer --system-libclang --system-boost +< +Compiling YCM **without** semantic support for C-family languages: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --system-boost +< +The following additional language support options are available: + +- C# support: install Mono and add '--omnisharp-completer' when calling + './install.py'. + +- Go support: install Go [23] and add '--gocode-completer' when calling + './install.py'. + +- TypeScript support: install Node.js and npm [24] then install the + TypeScript SDK with 'npm install -g typescript'. + +- JavaScript support: install Node.js and npm [24] and add '--tern-completer' + when calling './install.py'. + +- Rust support: install Rust [25] and add '--racer-completer' when calling + './install.py'. + +To simply compile with everything enabled, there's a '--all' flag. So, to +install with all language features, ensure 'xbuild', 'go', 'tsserver', 'node', +'npm', and 'cargo' tools are installed and in your 'PATH', then simply run: +> + cd ~/.vim/bundle/YouCompleteMe + ./install.py --all +< +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +------------------------------------------------------------------------------- + *youcompleteme-full-installation-guide* +Full Installation Guide ~ + +These are the steps necessary to get YCM working on a Unix OS and on Windows. + +**Note to Windows users:** we assume that you are running the 'cmd.exe' command +prompt and that the needed executables are in the PATH environment variable. Do +not just copy the shell commands. Replace '~' by '%USERPROFILE%' in them and +use the right Vim home directory. It should be 'vimfiles' by default instead of +'.vim'. + +See the _FAQ_ if you have any issues. + +**Remember:** YCM is a plugin with a compiled component. If you **update** YCM +using Vundle and the ycm_core library APIs have changed (happens rarely), YCM +will notify you to recompile it. You should then rerun the install process. + +**Please follow the instructions carefully. Read EVERY WORD.** + +1. **Ensure that your version of Vim is _at least_ 7.3.598 _and_ that it has + support for Python 2 or Python 3 scripting**. + + Inside Vim, type ':version'. Look at the first two to three lines of + output; it should say 'Vi IMproved X.Y', where X.Y is the major version + of vim. If your version is greater than 7.3, then you're all set. If your + version is 7.3 then look below that where it says, 'Included patches: + 1-Z', where Z will be some number. That number needs to be 598 or higher. + + If your version of Vim is not recent enough, you may need to compile Vim + from source [26] (don't worry, it's easy). + + After you have made sure that you have Vim 7.3.598+, type the following + in Vim: ":echo has('python') || has('python3')". The output should be 1. + If it's 0, then get a version of Vim with Python support. + + On Windows, check also if your Vim architecture is 32 or 64-bit. This is + critical because it must match the Python and the YCM libraries + architectures. We recommend using a 64-bit Vim. + +2. **Install YCM** with Vundle [19] (or Pathogen [34], but Vundle is a + better idea). With Vundle, this would mean adding a "Plugin + 'Valloric/YouCompleteMe'" line to your vimrc [35]. + + If you don't install YCM with Vundle, make sure you have run 'git + submodule update --init --recursive' after checking out the YCM + repository (Vundle will do this for you) to fetch YCM's dependencies. + +3. [Complete this step ONLY if you care about semantic completion support + for C-family languages. Otherwise it's not necessary.] + + **Download the latest version of 'libclang'**. Clang is an open-source + compiler that can compile C/C++/Objective-C/Objective-C++. The 'libclang' + library it provides is used to power the YCM semantic completion engine + for those languages. YCM is designed to work with libclang version 3.8 or + higher. + + You can use the system libclang _only if you are sure it is version 3.8 + or higher_, otherwise don't. Even if it is, we recommend using the + official binaries from llvm.org [36] if at all possible. Make sure you + download the correct archive file for your OS. + + We **STRONGLY recommend AGAINST use** of the system libclang instead of + the upstream compiled binaries. Random things may break. Save yourself + the hassle and use the upstream pre-built libclang. + +4. **Compile the 'ycm_core' library** that YCM needs. This library is the + C++ engine that YCM uses to get fast completions. + + You will need to have 'cmake' installed in order to generate the required + makefiles. Linux users can install cmake with their package manager + ('sudo apt-get install cmake' for Ubuntu) whereas other users can + download and install [21] cmake from its project site. Mac users can also + get it through Homebrew [20] with 'brew install cmake'. + + On a Unix OS, you need to make sure you have Python headers installed. On + a Debian-like Linux distro, this would be 'sudo apt-get install python- + dev python3-dev'. On Mac they should already be present. + + On Windows, you need to download and install Python 2 or Python 3 [30]. + Pick the version corresponding to your Vim architecture. You will also + need Microsoft Visual C++ (MSVC) to build YCM. You can obtain it by + installing Visual Studio [31]. MSVC 11 (Visual Studio 2012), 12 (2013), + and 14 (2015) are officially supported. + + Here we'll assume you installed YCM with Vundle. That means that the top- + level YCM directory is in '~/.vim/bundle/YouCompleteMe'. + + We'll create a new folder where build files will be placed. Run the + following: +> + cd ~ + mkdir ycm_build + cd ycm_build +< + Now we need to generate the makefiles. If you DON'T care about semantic + support for C-family languages, run the following command in the + 'ycm_build' directory: +> + cmake -G "<generator>" . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp +< + where '<generator>' is 'Unix Makefiles' on Unix systems and one of the + following Visual Studio generators on Windows: + + - 'Visual Studio 11 Win64' + - 'Visual Studio 12 Win64' + - 'Visual Studio 14 Win64' + + Remove the 'Win64' part in these generators if your Vim architecture is + 32-bit. + + For those who want to use the system version of boost, you would pass + '-DUSE_SYSTEM_BOOST=ON' to cmake. This may be necessary on some systems + where the bundled version of boost doesn't compile out of the box. + + NOTE: We **STRONGLY recommend AGAINST use** of the system boost instead + of the bundled version of boost. Random things may break. Save yourself + the hassle and use the bundled version of boost. + + If you DO care about semantic support for C-family languages, then your + 'cmake' call will be a bit more complicated. We'll assume you downloaded + a binary distribution of LLVM+Clang from llvm.org in step 3 and that you + extracted the archive file to folder '~/ycm_temp/llvm_root_dir' (with + 'bin', 'lib', 'include' etc. folders right inside that folder). On + Windows, you can extract the files from the LLVM+Clang installer using + 7-zip [32]. + + NOTE: This _only_ works with a _downloaded_ LLVM binary package, not a + custom-built LLVM! See docs below for 'EXTERNAL_LIBCLANG_PATH' when using + a custom LLVM build. + + With that in mind, run the following command in the 'ycm_build' + directory: +> + cmake -G "<generator>" -DPATH_TO_LLVM_ROOT=~/ycm_temp/llvm_root_dir . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp +< + where '<generator>' is replaced like above. + + Now that configuration files have been generated, compile the libraries + using this command: +> + cmake --build . --target ycm_core --config Release +< + The '--config Release' part is specific to Windows and will be ignored on + a Unix OS. + + For those who want to use the system version of libclang, you would pass + '-DUSE_SYSTEM_LIBCLANG=ON' to cmake _instead of_ the + '-DPATH_TO_LLVM_ROOT=...' flag. + + NOTE: We **STRONGLY recommend AGAINST use** of the system libclang + instead of the upstream compiled binaries. Random things may break. Save + yourself the hassle and use the upstream pre-built libclang. + + You could also force the use of a custom libclang library with + '-DEXTERNAL_LIBCLANG_PATH=/path/to/libclang.so' flag (the library would + end with '.dylib' on a Mac). Again, this flag would be used _instead of_ + the other flags. **If you compiled LLVM from source, this is the flag you + should be using.** + + Running the 'cmake' command will also place the 'libclang.[so|dylib|dll]' + in the 'YouCompleteMe/third_party/ycmd' folder for you if you compiled + with clang support (it needs to be there for YCM to work). + +5. Set up support for additional languages, as desired: + +6. C# support: install Mono on non-Windows platforms [37]. Navigate to + 'YouCompleteMe/third_party/ycmd/third_party/OmniSharpServer' and run + 'msbuild' (Windows) or 'xbuild' (other platforms, using Mono) depending + on your platform. On Windows, be sure that the build utility 'msbuild' is + in your PATH [33]. + +7. Go support: install Go [23] and add it to your path. Navigate to + 'YouCompleteMe/third_party/ycmd/third_party/gocode' and run 'go build'. + +8. TypeScript support: as with the quick installation, simply 'npm install + -g typescript' after successfully installing Node.js and npm [24]. + +9. JavaScript support: install Node.js and npm [24]. Then navigate to + 'YouCompleteMe/third_party/ycmd/third_party/tern_runtime' and run 'npm + install --production' + +10. Rust support: install Rust [25]. Navigate to + 'YouCompleteMe/third_party/ycmd/third_party/racerd' and run 'cargo + build --release'. + +That's it. You're done. Refer to the _User Guide_ section on how to use YCM. +Don't forget that if you want the C-family semantic completion engine to work, +you will need to provide the compilation flags for your project to YCM. It's +all in the User Guide. + +YCM comes with sane defaults for its options, but you still may want to take a +look at what's available for configuration. There are a few interesting options +that are conservatively turned off by default that you may want to turn on. + +=============================================================================== + *youcompleteme-quick-feature-summary* +Quick Feature Summary ~ + +------------------------------------------------------------------------------- + *youcompleteme-general* +General (all languages) ~ + +- Super-fast identifier completer including tags files and syntax elements +- Intelligent suggestion ranking and filtering +- File and path suggestions +- Suggestions from Vim's OmniFunc +- UltiSnips snippet suggestions + +------------------------------------------------------------------------------- + *youcompleteme-c-family-languages* +C-family languages (C, C++, Objective C, Objective C++) ~ + +- Semantic auto-completion +- Real-time diagnostic display +- Go to include/declaration/definition (|GoTo|, etc.) +- Semantic type information for identifiers (|GetType|) +- Automatically fix certain errors (|FixIt|) +- View documentation comments for identifiers (|GetDoc|) + +------------------------------------------------------------------------------- + *youcompleteme-c* +C♯ ~ + +- Semantic auto-completion +- Real-time diagnostic display +- Go to declaration/definition (|GoTo|, etc.) +- Semantic type information for identifiers (|GetType|) +- Automatically fix certain errors (|FixIt|) +- Management of OmniSharp server instance +- View documentation comments for identifiers (|GetDoc|) + +------------------------------------------------------------------------------- + *youcompleteme-python* +Python ~ + +- Intelligent auto-completion +- Go to declaration/definition, find references (|GoTo|, |GoToReferences|) +- View documentation comments for identifiers (|GetDoc|) +- Restart JediHTTP [7] server using a different Python interpreter + +------------------------------------------------------------------------------- + *youcompleteme-go* +Go ~ + +- Semantic auto-completion +- Go to definition (|GoTo|) +- Management of 'gocode' server instance + +------------------------------------------------------------------------------- + *youcompleteme-typescript* +TypeScript ~ + +- Semantic auto-completion +- Renaming symbols ('RefactorRename <new name>') +- Go to definition, find references (|GoToDefinition|, |GoToReferences|) +- Semantic type information for identifiers (|GetType|) +- View documentation comments for identifiers (|GetDoc|) + +------------------------------------------------------------------------------- + *youcompleteme-javascript* +JavaScript ~ + +- Intelligent auto-completion +- Renaming variables ('RefactorRename <new name>') +- Go to definition, find references (|GoToDefinition|, |GoToReferences|) +- Type information for identifiers (|GetType|) +- View documentation comments for identifiers (|GetDoc|) +- Management of 'Tern' server instance + +------------------------------------------------------------------------------- + *youcompleteme-rust* +Rust ~ + +- Semantic auto-completion +- Go to definition (|GoTo|, |GoToDefinition|, and |GoToDeclaration| are + identical) +- Management of 'racer' server instance + +=============================================================================== + *youcompleteme-user-guide* +User Guide ~ + +------------------------------------------------------------------------------- + *youcompleteme-general-usage* +General Usage ~ + +- If the offered completions are too broad, keep typing characters; YCM will + continue refining the offered completions based on your input. + +- Filtering is "smart-case" sensitive; if you are typing only lowercase + letters, then it's case-insensitive. If your input contains uppercase + letters, then the uppercase letters in your query must match uppercase + letters in the completion strings (the lowercase letters still match both). + So, "foo" matches "Foo" and "foo", "Foo" matches "Foo" and "FOO" but not + "foo". + +- Use the TAB key to accept a completion and continue pressing TAB to cycle + through the completions. Use Shift-TAB to cycle backwards. Note that if + you're using console Vim (that is, not Gvim or MacVim) then it's likely + that the Shift-TAB binding will not work because the console will not pass + it to Vim. You can remap the keys; see the _Options [38]_ section below. + +Knowing a little bit about how YCM works internally will prevent confusion. YCM +has several completion engines: an identifier-based completer that collects all +of the identifiers in the current file and other files you visit (and your tags +files) and searches them when you type (identifiers are put into per-filetype +groups). + +There are also several semantic engines in YCM. There's a libclang-based +completer that provides semantic completion for C-family languages. There's a +Jedi-based completer for semantic completion for Python. There's also an +omnifunc-based completer that uses data from Vim's omnicomplete system to +provide semantic completions when no native completer exists for that language +in YCM. + +There are also other completion engines, like the UltiSnips completer and the +filepath completer. + +YCM automatically detects which completion engine would be the best in any +situation. On occasion, it queries several of them at once, merges the outputs +and presents the results to you. + +------------------------------------------------------------------------------- + *youcompleteme-client-server-architecture* +Client-Server Architecture ~ + +YCM has a client-server architecture; the Vim part of YCM is only a thin client +that talks to the ycmd HTTP+JSON server [39] that has the vast majority of YCM +logic and functionality. The server is started and stopped automatically as you +start and stop Vim. + +------------------------------------------------------------------------------- + *youcompleteme-completion-string-ranking* +Completion String Ranking ~ + +The subsequence filter removes any completions that do not match the input, but +then the sorting system kicks in. It's actually very complicated and uses lots +of factors, but suffice it to say that "word boundary" (WB) subsequence +character matches are "worth" more than non-WB matches. In effect, this means +given an input of "gua", the completion "getUserAccount" would be ranked higher +in the list than the "Fooguxa" completion (both of which are subsequence +matches). A word-boundary character are all capital characters, characters +preceded by an underscore and the first letter character in the completion +string. + +------------------------------------------------------------------------------- + *youcompleteme-general-semantic-completion* +General Semantic Completion ~ + +- You can use Ctrl+Space to trigger the completion suggestions anywhere, even + without a string prefix. This is useful to see which top-level functions + are available for use. + +------------------------------------------------------------------------------- + *youcompleteme-c-family-semantic-completion* +C-family Semantic Completion ~ + +YCM looks for a '.ycm_extra_conf.py' file in the directory of the opened file +or in any directory above it in the hierarchy (recursively); when the file is +found, it is loaded (only once!) as a Python module. YCM calls a 'FlagsForFile' +method in that module which should provide it with the information necessary to +compile the current file. You can also provide a path to a global +'.ycm_extra_conf.py' file, which will be used as a fallback. To prevent the +execution of malicious code from a file you didn't write YCM will ask you once +per '.ycm_extra_conf.py' if it is safe to load. This can be disabled and you +can white-/blacklist files. See the _Options_ section for more details. + +This system was designed this way so that the user can perform any arbitrary +sequence of operations to produce a list of compilation flags YCM should hand +to Clang. + +See YCM's own '.ycm_extra_conf.py' [40] for details on how this works. You +should be able to use it _as a starting point_. **Don't** just copy/paste that +file somewhere and expect things to magically work; **your project needs +different flags**. Hint: just replace the strings in the 'flags' variable with +compilation flags necessary for your project. That should be enough for 99% of +projects. + +Yes, Clang's 'CompilationDatabase' system [41] is also supported. Again, see +the above linked example file. You can get CMake to generate this file for you +by adding 'set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )' to your project's +'CMakeLists.txt' file (if using CMake). If you're not using CMake, you could +use something like Bear [42] to generate the 'compile_commands.json' file. + +Consider using YCM-Generator [43] to generate the 'ycm_extra_conf.py' file. + +If Clang encounters errors when compiling the header files that your file +includes, then it's probably going to take a long time to get completions. When +the completion menu finally appears, it's going to have a large number of +unrelated completion strings (type/function names that are not actually +members). This is because Clang fails to build a precompiled preamble for your +file if there are any errors in the included headers and that preamble is key +to getting fast completions. + +Call the |:YcmDiags| command to see if any errors or warnings were detected in +your file. + +------------------------------------------------------------------------------- + *youcompleteme-javascript-semantic-completion* +JavaScript Semantic Completion ~ + +------------------------------------------------------------------------------- + *youcompleteme-quick-start* +Quick start ~ + +1. Ensure that you have enabled the Tern completer. See the installation + guide for details. + +2. Create a '.tern-project' file in the root directory of your JavaScript + project, by following the instructions [44] in the Tern [12] + documentation. + +3. Make sure that Vim's working directory is a descendent of that directory + (or that directory itself) when working with JavaScript files. + +------------------------------------------------------------------------------- + *youcompleteme-explanation* +Explanation ~ + +JavaScript completion is based on Tern [12]. This completion engine requires a +file named '.tern-project' [44] to exist in the current working directory or a +directory which is an ancestor of the current working directory when the tern +server is started. YCM starts the Tern server the first time a JavaScript file +is edited, so Vim's working directory at that time needs to be a descendent of +the directory containing the '.tern-project' file (or that directory itself). + +Alternatively, as described in the Tern documentation [45], a global '.tern- +config' file may be used. + +Multiple Tern servers, are not supported. To switch to a different JavaScript +project, you can do one of the following: + +- start a new instance of Vim from the new project's directory + +- change Vim's working directory (':cd /path/to/new/project') and restart the + ycmd server [39] (|:YcmRestartServer|) + +- change Vim's working directory (':cd /path/to/new/project'), open a + JavaScript file (or set filetype to JavaScript) and restart the Tern server + using YCM completer subcommands ':YcmCompleter StopServer' and + ':YcmCompleter StartServer'. + +------------------------------------------------------------------------------- + *youcompleteme-tips-tricks* +Tips and tricks ~ + +This section contains some advice for configuring '.tern-project' and working +with JavaScript files. The canonical reference for correctly configuring Tern +is the Tern documentation [45]. Any issues, improvements, advice, etc. should +be sought from the Tern [12] project. For example, see the list of tern plugins +[46] for the list of plugins which can be enabled in the 'plugins' section of +the '.tern-project' file. + +------------------------------------------------------------------------------- + *youcompleteme-configuring-tern-for-node-support* +Configuring Tern for node support ~ + +The following simple example '.tern-project' file enables nodejs support: +> + { + "plugins": { + "node": {} + } + } +< +------------------------------------------------------------------------------- + *youcompleteme-configuring-tern-for-requirejs-support* +Configuring Tern for requirejs support ~ + +The Tern requirejs plugin requires that all included "libraries" are rooted +under the same base directory. If that's not the case for your projects, then +it is possible to make it work with appropriate symbolic links. For example, +create a directory 'ext_lib' within your project and populate it with symlinks +to your libraries. Then set up the '.tern-project' something like this: +> + { + "plugins": { + "requirejs": { + "baseURL": "./ext_lib", + } + } + } +< +Then, given the following structure: +> + ./ext_lib/mylib (symlink) + ./ext_lib/anotherlib (symlink) +< +Can be used as follows: +> + define( [ 'mylib/file1', 'anotherlib/anotherfile' ], function( f1, f2 ) { + // etc. + } ); +< +------------------------------------------------------------------------------- + *youcompleteme-rust-semantic-completion* +Rust Semantic Completion ~ + +Completions and GoTo commands within the current crate and its dependencies +should work out of the box with no additional configuration (provided that you +built YCM with the '--racer-completer' flag; see the _Installation_ section for +details). For semantic analysis inclusive of the standard library, you must +have a local copy of the rust source code [47]. You also need to set the +following option so YouCompleteMe can locate it. +> + " In this example, the rust source code zip has been extracted to + " /usr/local/rust/rustc-1.5.0 + let g:ycm_rust_src_path = '/usr/local/rust/rustc-1.5.0/src' +< +------------------------------------------------------------------------------- + *youcompleteme-python-semantic-completion* +Python Semantic Completion ~ + +Completion and GoTo commands work out of the box with no additional +configuration. Those features are provided by the jedi [6] library which +supports a variety of Python versions (2.6, 2.7, 3.2+) as long as it runs in +the corresponding Python interpreter. By default YCM runs jedi [6] with the +same Python interpreter used by the ycmd server [39], so if you would like to +use a different interpreter, use the following option specifying the Python +binary to use. For example, to provide Python 3 completion in your project, +set: +> + let g:ycm_python_binary_path = '/usr/bin/python3' +< +If the value of |g:ycm_python_binary_path| is an absolute path like above it +will be used as-is, but if it's an executable name it will be searched through +the PATH. So for example if you set: +> + let g:ycm_python_binary_path = 'python' +< +YCM will use the first 'python' executable it finds in the PATH to run jedi +[6]. This means that if you are in a virtual environment and you start vim in +that directory, the first 'python' that YCM will find will be the one in the +virtual environment, so jedi [6] will be able to provide completions for every +package you have in the virtual environment. + +------------------------------------------------------------------------------- + *youcompleteme-semantic-completion-for-other-languages* +Semantic Completion for Other Languages ~ + +Python, C#, Go, Rust, and TypeScript are supported natively by YouCompleteMe +using the Jedi [6], Omnisharp [8], Gocode [9], racer [13], and TSServer [11] +engines, respectively. Check the installation section for instructions to +enable these features if desired. + +YCM will use your 'omnifunc' (see ':h omnifunc' in Vim) as a source for +semantic completions if it does not have a native semantic completion engine +for your file's filetype. Vim comes with okayish omnifuncs for various +languages like Ruby, PHP etc. It depends on the language. + +You can get stellar omnifuncs for Java and Ruby with Eclim [48]. Just make sure +you have the _latest_ Eclim installed and configured (this means Eclim '>= +2.2.*' and Eclipse '>= 4.2.*'). + +After installing Eclim remember to create a new Eclipse project within your +application by typing ':ProjectCreate <path-to-your-project> -n ruby' (or '-n +java') inside vim and don't forget to have "let g:EclimCompletionMethod = +'omnifunc'" in your vimrc. This will make YCM and Eclim play nice; YCM will use +Eclim's omnifuncs as the data source for semantic completions and provide the +auto-triggering and subsequence-based matching (and other YCM features) on top +of it. + +------------------------------------------------------------------------------- + *youcompleteme-writing-new-semantic-completers* +Writing New Semantic Completers ~ + +You have two options here: writing an 'omnifunc' for Vim's omnicomplete system +that YCM will then use through its omni-completer, or a custom completer for +YCM using the Completer API [49]. + +Here are the differences between the two approaches: + +- You have to use VimScript to write the omnifunc, but get to use Python to + write for the Completer API; this by itself should make you want to use the + API. + +- The Completer API is a _much_ more powerful way to integrate with YCM and + it provides a wider set of features. For instance, you can make your + Completer query your semantic back-end in an asynchronous fashion, thus not + blocking Vim's GUI thread while your completion system is processing stuff. + This is impossible with VimScript. All of YCM's completers use the + Completer API. + +- Performance with the Completer API is better since Python executes faster + than VimScript. + +If you want to use the 'omnifunc' system, see the relevant Vim docs with ':h +complete-functions'. For the Completer API, see the API docs [49]. + +If you want to upstream your completer into YCM's source, you should use the +Completer API. + +------------------------------------------------------------------------------- + *youcompleteme-diagnostic-display* +Diagnostic Display ~ + +YCM will display diagnostic notifications for C-family and C# languages if you +compiled YCM with Clang and Omnisharp support, respectively. Since YCM +continuously recompiles your file as you type, you'll get notified of errors +and warnings in your file as fast as possible. + +Here are the various pieces of the diagnostic UI: + +- Icons show up in the Vim gutter on lines that have a diagnostic. +- Regions of text related to diagnostics are highlighted (by default, a red + wavy underline in 'gvim' and a red background in 'vim'). +- Moving the cursor to a line with a diagnostic echoes the diagnostic text. +- Vim's location list is automatically populated with diagnostic data (off by + default, see options). + +The new diagnostics (if any) will be displayed the next time you press any key +on the keyboard. So if you stop typing and just wait for the new diagnostics to +come in, that _will not work_. You need to press some key for the GUI to +update. + +Having to press a key to get the updates is unfortunate, but cannot be changed +due to the way Vim internals operate; there is no way that a background task +can update Vim's GUI after it has finished running. You _have to_ press a key. +This will make YCM check for any pending diagnostics updates. + +You _can_ force a full, blocking compilation cycle with the +|:YcmForceCompileAndDiagnostics| command (you may want to map that command to a +key; try putting 'nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>' in your +vimrc). Calling this command will force YCM to immediately recompile your file +and display any new diagnostics it encounters. Do note that recompilation with +this command may take a while and during this time the Vim GUI _will_ be +blocked. + +YCM will display a short diagnostic message when you move your cursor to the +line with the error. You can get a detailed diagnostic message with the +'<leader>d' key mapping (can be changed in the options) YCM provides when your +cursor is on the line with the diagnostic. + +You can also see the full diagnostic message for all the diagnostics in the +current file in Vim's 'locationlist', which can be opened with the ':lopen' and +':lclose' commands (make sure you have set 'let +g:ycm_always_populate_location_list = 1' in your vimrc). A good way to toggle +the display of the 'locationlist' with a single key mapping is provided by +another (very small) Vim plugin called ListToggle [50] (which also makes it +possible to change the height of the 'locationlist' window), also written by +yours truly. + +------------------------------------------------------------------------------- + *youcompleteme-diagnostic-highlighting-groups* +Diagnostic Highlighting Groups ~ + +You can change the styling for the highlighting groups YCM uses. For the signs +in the Vim gutter, the relevant groups are: + +- 'YcmErrorSign', which falls back to group 'SyntasticErrorSign' and then + 'error' if they exist + +- 'YcmWarningSign', which falls back to group 'SyntasticWarningSign' and then + 'todo' if they exist + +You can also style the line that has the warning/error with these groups: + +- 'YcmErrorLine', which falls back to group 'SyntasticErrorLine' if it exists +- 'YcmWarningLine', which falls back to group 'SyntasticWarningLine' if it + exists + +Note that the line highlighting groups only work when gutter signs are turned +on. + +The syntax groups used to highlight regions of text with errors/warnings: - +'YcmErrorSection', which falls back to group 'SyntasticError' if it exists and +then 'SpellBad' - 'YcmWarningSection', which falls back to group +'SyntasticWarning' if it exists and then 'SpellCap' + +Here's how you'd change the style for a group: +> + highlight YcmErrorLine guibg=#3f0000 +< +=============================================================================== + *youcompleteme-commands* +Commands ~ + +------------------------------------------------------------------------------- +The *:YcmRestartServer* command + +If the ycmd completion server [39] suddenly stops for some reason, you can +restart it with this command. + +------------------------------------------------------------------------------- +The *:YcmForceCompileAndDiagnostics* command + +Calling this command will force YCM to immediately recompile your file and +display any new diagnostics it encounters. Do note that recompilation with this +command may take a while and during this time the Vim GUI _will_ be blocked. + +You may want to map this command to a key; try putting 'nnoremap <F5> +:YcmForceCompileAndDiagnostics<CR>' in your vimrc. + +------------------------------------------------------------------------------- +The *:YcmDiags* command + +Calling this command will fill Vim's 'locationlist' with errors or warnings if +any were detected in your file and then open it. If a given error or warning +can be fixed by a call to ':YcmCompleter FixIt', then '(FixIt available)' is +appended to the error or warning text. See the |FixIt| completer subcommand for +more information. + +NOTE: The absense of '(FixIt available)' does not strictly imply a fix-it is +not available as not all completers are able to provide this indication. For +example, the c-sharp completer provides many fix-its but does not add this +additional indication. + +The |g:ycm_open_loclist_on_ycm_diags| option can be used to prevent the +location list from opening, but still have it filled with new diagnostic data. +See the _Options_ section for details. + +------------------------------------------------------------------------------- +The *:YcmShowDetailedDiagnostic* command + +This command shows the full diagnostic text when the user's cursor is on the +line with the diagnostic. + +------------------------------------------------------------------------------- +The *:YcmDebugInfo* command + +This will print out various debug information for the current file. Useful to +see what compile commands will be used for the file if you're using the +semantic completion engine. + +------------------------------------------------------------------------------- +The *:YcmToggleLogs* command + +This command automatically opens in windows the stdout and stderr logfiles +written by the ycmd server [39]. If one or both logfiles are already opened, +they are automatically closed. 'stderr' or 'stdout' can be specified as an +argument of this command to only open the corresponding logfile instead of +both. If this logfile is already opened, it will be closed. Only for debugging +purpose. + +------------------------------------------------------------------------------- +The *:YcmCompleter* command + +This command gives access to a number of additional IDE-like features in YCM, +for things like semantic GoTo, type information, FixIt and refactoring. + +Technically the command invokes completer-specific commands. If the first +argument is of the form 'ft=...' the completer for that file type will be used +(for example 'ft=cpp'), else the native completer of the current buffer will be +used. Call 'YcmCompleter' without further arguments for a list of the commands +you can call for the current completer. + +See the file type feature summary for an overview of the features available for +each file type. See the _YcmCompleter subcommands_ section for more information +on the available subcommands and their usage. + +=============================================================================== + *youcompleteme-ycmcompleter-subcommands* +YcmCompleter Subcommands ~ + +NOTE: See the docs for the 'YcmCompleter' command before tackling this section. + +The invoked subcommand is automatically routed to the currently active semantic +completer, so ':YcmCompleter GoToDefinition' will invoke the |GoToDefinition| +subcommand on the Python semantic completer if the currently active file is a +Python one and on the Clang completer if the currently active file is a +C/C++/Objective-C one. + +You may also want to map the subcommands to something less verbose; for +instance, 'nnoremap <leader>jd :YcmCompleter GoTo<CR>' maps the '<leader>jd' +sequence to the longer subcommand invocation. + +------------------------------------------------------------------------------- + *youcompleteme-goto-commands* +GoTo Commands ~ + +These commands are useful for jumping around and exploring code. When moving +the cursor, the subcommands add entries to Vim's 'jumplist' so you can use +'CTRL-O' to jump back to where you where before invoking the command (and +'CTRL-I' to jump forward; see ':h jumplist' for details). If there is more than +one destination, the quickfix list (see ':h quickfix') is populated with the +available locations and opened to full width at the bottom of the screen. You +can change this behavior by using the |YcmQuickFixOpened| autocommand. + +------------------------------------------------------------------------------- +The *GoToInclude* subcommand + +Looks up the current line for a header and jumps to it. + +Supported in filetypes: 'c, cpp, objc, objcpp' + +------------------------------------------------------------------------------- +The *GoToDeclaration* subcommand + +Looks up the symbol under the cursor and jumps to its declaration. + +Supported in filetypes: 'c, cpp, objc, objcpp, cs, go, python, rust' + +------------------------------------------------------------------------------- +The *GoToDefinition* subcommand + +Looks up the symbol under the cursor and jumps to its definition. + +NOTE: For C-family languages **this only works in certain situations**, namely +when the definition of the symbol is in the current translation unit. A +translation unit consists of the file you are editing and all the files you are +including with '#include' directives (directly or indirectly) in that file. + +Supported in filetypes: 'c, cpp, objc, objcpp, cs, go, javascript, python, +rust, typescript' + +------------------------------------------------------------------------------- +The *GoTo* subcommand + +This command tries to perform the "most sensible" GoTo operation it can. +Currently, this means that it tries to look up the symbol under the cursor and +jumps to its definition if possible; if the definition is not accessible from +the current translation unit, jumps to the symbol's declaration. For +C/C++/Objective-C, it first tries to look up the current line for a header and +jump to it. For C#, implementations are also considered and preferred. + +Supported in filetypes: 'c, cpp, objc, objcpp, cs, go, javascript, python, +rust' + +------------------------------------------------------------------------------- +The *GoToImprecise* subcommand + +WARNING: This command trades correctness for speed! + +Same as the |GoTo| command except that it doesn't recompile the file with +libclang before looking up nodes in the AST. This can be very useful when +you're editing files that take long to compile but you know that you haven't +made any changes since the last parse that would lead to incorrect jumps. When +you're just browsing around your codebase, this command can spare you quite a +bit of latency. + +Supported in filetypes: 'c, cpp, objc, objcpp' + +------------------------------------------------------------------------------- +The *GoToReferences* subcommand + +This command attempts to find all of the references within the project to the +identifier under the cursor and populates the quickfix list with those +locations. + +Supported in filetypes: 'javascript, python, typescript' + +------------------------------------------------------------------------------- +The *GoToImplementation* subcommand + +Looks up the symbol under the cursor and jumps to its implementation (i.e. non- +interface). If there are multiple implementations, instead provides a list of +implementations to choose from. + +Supported in filetypes: 'cs' + +------------------------------------------------------------------------------- +The *GoToImplementationElseDeclaration* subcommand + +Looks up the symbol under the cursor and jumps to its implementation if one, +else jump to its declaration. If there are multiple implementations, instead +provides a list of implementations to choose from. + +Supported in filetypes: 'cs' + +------------------------------------------------------------------------------- + *youcompleteme-semantic-information-commands* +Semantic Information Commands ~ + +These commands are useful for finding static information about the code, such +as the types of variables, viewing declarations and documentation strings. + +------------------------------------------------------------------------------- +The *GetType* subcommand + +Echos the type of the variable or method under the cursor, and where it +differs, the derived type. + +For example: +> + std::string s; +< +Invoking this command on 's' returns 'std::string => std::basic_string<char>' + +NOTE: Due to limitations of 'libclang', invoking this command on the word +'auto' typically returns 'auto'. However, invoking it on a usage of the +variable with inferred type returns the correct type, but typically it is +repeated due to 'libclang' returning that the types differ. + +For example: +> + const char *s = "String"; + auto x = &s; // invoking on x or auto returns "auto"; + // invoking on s returns "const char *" + std::cout << *x; // invoking on x returns "const char ** => const char **" +< +NOTE: Causes re-parsing of the current translation unit. + +Supported in filetypes: 'c, cpp, objc, objcpp, javascript, typescript' + +------------------------------------------------------------------------------- +The *GetParent* subcommand + +Echos the semantic parent of the point under the cursor. + +The semantic parent is the item that semantically contains the given position. + +For example: +> + class C { + void f(); + }; + + void C::f() { + + } +< +In the out-of-line definition of 'C::f', the semantic parent is the class 'C', +of which this function is a member. + +In the example above, both declarations of 'C::f' have 'C' as their semantic +context, while the lexical context of the first 'C::f' is 'C' and the lexical +context of the second 'C::f' is the translation unit. + +For global declarations, the semantic parent is the translation unit. + +NOTE: Causes re-parsing of the current translation unit. + +Supported in filetypes: 'c, cpp, objc, objcpp' + +------------------------------------------------------------------------------- +The *GetDoc* subcommand + +Displays the preview window populated with quick info about the identifier +under the cursor. Depending on the file type, this includes things like: + +- The type or declaration of identifier, +- Doxygen/javadoc comments, +- Python docstrings, +- etc. + +Supported in filetypes: 'c, cpp, objc, objcpp, cs, python, typescript, +javascript' + +------------------------------------------------------------------------------- + *youcompleteme-refactoring-fixit-commands* +Refactoring and FixIt Commands ~ + +These commands make changes to your source code in order to perform refactoring +or code correction. YouCompleteMe does not perform any action which cannot be +undone, and never saves or writes files to the disk. + +------------------------------------------------------------------------------- +The *FixIt* subcommand + +Where available, attempts to make changes to the buffer to correct the +diagnostic closest to the cursor position. + +Completers which provide diagnostics may also provide trivial modifications to +the source in order to correct the diagnostic. Examples include syntax errors +such as missing trailing semi-colons, spurious characters, or other errors +which the semantic engine can deterministically suggest corrections. + +If no fix-it is available for the current line, or there is no diagnostic on +the current line, this command has no effect on the current buffer. If any +modifications are made, the number of changes made to the buffer is echo'd and +the user may use the editor's undo command to revert. + +When a diagnostic is available, and |g:ycm_echo_current_diagnostic| is set to +1, then the text '(FixIt)' is appended to the echo'd diagnostic when the +completer is able to add this indication. The text '(FixIt available)' is also +appended to the diagnostic text in the output of the |:YcmDiags| command for +any diagnostics with available fix-its (where the completer can provide this +indication). + +NOTE: Causes re-parsing of the current translation unit. + +NOTE: After applying a fix-it, the diagnostics UI is not immediately updated. +This is due to a technical restriction in Vim. Moving the cursor, or issuing +the |:YcmForceCompileAndDiagnostics| command will refresh the diagnostics. +Repeated invocations of the |FixIt| command on a given line, however, _do_ +apply all diagnostics as expected without requiring refreshing of the +diagnostics UI. This is particularly useful where there are multiple +diagnostics on one line, or where after fixing one diagnostic, another fix-it +is available. + +Supported in filetypes: 'c, cpp, objc, objcpp, cs' + +------------------------------------------------------------------------------- + *RefactorRename-new-name* +The 'RefactorRename <new name>' subcommand ~ + +In supported file types, this command attempts to perform a semantic rename of +the identifier under the cursor. This includes renaming declarations, +definitions and usages of the identifier, or any other language-appropriate +action. The specific behavior is defined by the semantic engine in use. + +Similar to |FixIt|, this command applies automatic modifications to your source +files. Rename operations may involve changes to multiple files, which may or +may not be open in Vim buffers at the time. YouCompleteMe handles all of this +for you. The behavior is described in the following section. + +Supported in filetypes: 'javascript' (variables only), 'typescript' + +------------------------------------------------------------------------------- + *youcompleteme-multi-file-refactor* +Multi-file Refactor ~ + +When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts +to apply those modifications to any existing open, visible buffer in the +current tab. If no such buffer can be found, YouCompleteMe opens the file in a +new small horizontal split at the top of the current window, applies the +change, and then _hides_ the window. NOTE: The buffer remains open, and must be +manually saved. A confirmation dialog is opened prior to doing this to remind +you that this is about to happen. + +Once the modifications have been made, the quickfix list (see ':help quickfix') +is opened and populated with the locations of all modifications. This can be +used to review all automatic changes made. Typically, use the 'CTRL-W <enter>' +combination to open the selected file in a new split. It is possible to +customize how the quickfix window is opened by using the |YcmQuickFixOpened| +autocommand. + +The buffers are _not_ saved automatically. That is, you must save the modified +buffers manually after reviewing the changes from the quickfix list. Changes +can be undone using Vim's powerful undo features (see ':help undo'). Note that +Vim's undo is per-buffer, so to undo all changes, the undo commands must be +applied in each modified buffer separately. + +NOTE: While applying modifications, Vim may find files which are already open +and have a swap file. The command is aborted if you select Abort or Quit in any +such prompts. This leaves the Refactor operation partially complete and must be +manually corrected using Vim's undo features. The quickfix list is _not_ +populated in this case. Inspect ':buffers' or equivalent (see ':help buffers') +to see the buffers that were opened by the command. + +------------------------------------------------------------------------------- + *youcompleteme-miscellaneous-commands* +Miscellaneous Commands ~ + +These commands are for general administration, rather than IDE-like features. +They cover things like the semantic engine server instance and compilation +flags. + +------------------------------------------------------------------------------- +The *ClearCompilationFlagCache* subcommand + +YCM caches the flags it gets from the 'FlagsForFile' function in your +'ycm_extra_conf.py' file if you return them with the 'do_cache' parameter set +to 'True'. The cache is in memory and is never invalidated (unless you restart +Vim of course). + +This command clears that cache entirely. YCM will then re-query your +'FlagsForFile' function as needed in the future. + +Supported in filetypes: 'c, cpp, objc, objcpp' + +------------------------------------------------------------------------------- +The *StartServer* subcommand + +Starts the semantic-engine-as-localhost-server for those semantic engines that +work as separate servers that YCM talks to. + +Supported in filetypes: 'cs, go, javascript, rust' + +------------------------------------------------------------------------------- +The *StopServer* subcommand + +Stops the semantic-engine-as-localhost-server for those semantic engines that +work as separate servers that YCM talks to. + +Supported in filetypes: 'cs, go, javascript, rust' + +------------------------------------------------------------------------------- +The *RestartServer* subcommand + +Restarts the semantic-engine-as-localhost-server for those semantic engines +that work as separate servers that YCM talks to. + +An additional optional argument may be supplied for Python, specifying the +python binary to use to restart the Python semantic engine. +> + :YcmCompleter RestartServer /usr/bin/python3.4 +< +Supported in filetypes: 'cs, python, rust' + +------------------------------------------------------------------------------- +The *ReloadSolution* subcommand + +Instruct the Omnisharp server to clear its cache and reload all files from +disk. This is useful when files are added, removed, or renamed in the solution, +files are changed outside of Vim, or whenever Omnisharp cache is out-of-sync. + +Supported in filetypes: 'cs' + +=============================================================================== + *youcompleteme-functions* +Functions ~ + +------------------------------------------------------------------------------- +The *youcompleteme#GetErrorCount* function + +Get the number of YCM Diagnostic errors. If no errors are present, this +function returns 0. + +For example: +> + call youcompleteme#GetErrorCount() +< +Both this function and |youcompleteme#GetWarningCount| can be useful when +integrating YCM with other Vim plugins. For example, a lightline [51] user +could add a diagnostics section to their statusline which would display the +number of errors and warnings. + +------------------------------------------------------------------------------- +The *youcompleteme#GetWarningCount* function + +Get the number of YCM Diagnostic warnings. If no warnings are present, this +function returns 0. + +For example: +> + call youcompleteme#GetWarningCount() +< +=============================================================================== + *youcompleteme-autocommands* +Autocommands ~ + +------------------------------------------------------------------------------- +The *YcmQuickFixOpened* autocommand + +This 'User' autocommand is fired when YCM opens the quickfix window in response +to the 'GoTo*' and 'RefactorRename' subcommands. By default, the quickfix +window is opened to full width at the bottom of the screen and its height is +set to fit all entries. This behavior can be overridden by using the +|YcmQuickFixOpened| autocommand. For instance: +> + function s:CustomizeYcmQuickFixWindow() + " Move the window at the top of the screen. + execute "wincmd K" + " Set the window height to 5. + execute "5wincmd _" + endfunction + + autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow() +< +=============================================================================== + *youcompleteme-options* +Options ~ + +All options have reasonable defaults so if the plug-in works after installation +you don't need to change any options. These options can be configured in your +vimrc script [35] by including a line like this: +> + let g:ycm_min_num_of_chars_for_completion = 1 +< +Note that after changing an option in your vimrc script [35] you have to +restart Vim for the changes to take effect. + +------------------------------------------------------------------------------- +The *g:ycm_min_num_of_chars_for_completion* option + +This option controls the number of characters the user needs to type before +identifier-based completion suggestions are triggered. For example, if the +option is set to '2', then when the user types a second alphanumeric character +after a whitespace character, completion suggestions will be triggered. This +option is NOT used for semantic completion. + +Setting this option to a high number like '99' effectively turns off the +identifier completion engine and just leaves the semantic engine. + +Default: '2' +> + let g:ycm_min_num_of_chars_for_completion = 2 +< +------------------------------------------------------------------------------- +The *g:ycm_min_num_identifier_candidate_chars* option + +This option controls the minimum number of characters that a completion +candidate coming from the identifier completer must have to be shown in the +popup menu. + +A special value of '0' means there is no limit. + +NOTE: This option only applies to the identifier completer; it has no effect on +the various semantic completers. + +Default: '0' +> + let g:ycm_min_num_identifier_candidate_chars = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_auto_trigger* option + +When set to '0', this option turns off YCM's identifier completer (the as-you- +type popup) _and_ the semantic triggers (the popup you'd get after typing '.' +or '->' in say C++). You can still force semantic completion with the +'<C-Space>' shortcut. + +If you want to just turn off the identifier completer but keep the semantic +triggers, you should set |g:ycm_min_num_of_chars_for_completion| to a high +number like '99'. + +Default: '1' +> + let g:ycm_auto_trigger = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_filetype_whitelist* option + +This option controls for which Vim filetypes (see ':h filetype') should YCM be +turned on. The option value should be a Vim dictionary with keys being filetype +strings (like 'python', 'cpp' etc) and values being unimportant (the dictionary +is used like a hash set, meaning that only the keys matter). + +The '*' key is special and matches all filetypes. By default, the whitelist +contains only this '*' key. + +YCM also has a |g:ycm_filetype_blacklist| option that lists filetypes for which +YCM shouldn't be turned on. YCM will work only in filetypes that both the +whitelist and the blacklist allow (the blacklist "allows" a filetype by _not_ +having it as a key). + +For example, let's assume you want YCM to work in files with the 'cpp' +filetype. The filetype should then be present in the whitelist either directly +('cpp' key in the whitelist) or indirectly through the special '*' key. It +should _not_ be present in the blacklist. + +Filetypes that are blocked by the either of the lists will be completely +ignored by YCM, meaning that neither the identifier-based completion engine nor +the semantic engine will operate in them. + +You can get the filetype of the current file in Vim with ':set ft?'. + +Default: "{'*' : 1}" +> + let g:ycm_filetype_whitelist = { '*': 1 } +< +------------------------------------------------------------------------------- +The *g:ycm_filetype_blacklist* option + +This option controls for which Vim filetypes (see ':h filetype') should YCM be +turned off. The option value should be a Vim dictionary with keys being +filetype strings (like 'python', 'cpp' etc) and values being unimportant (the +dictionary is used like a hash set, meaning that only the keys matter). + +See the |g:ycm_filetype_whitelist| option for more details on how this works. + +Default: '[see next line]' +> + let g:ycm_filetype_blacklist = { + \ 'tagbar' : 1, + \ 'qf' : 1, + \ 'notes' : 1, + \ 'markdown' : 1, + \ 'unite' : 1, + \ 'text' : 1, + \ 'vimwiki' : 1, + \ 'pandoc' : 1, + \ 'infolog' : 1, + \ 'mail' : 1 + \} +< +------------------------------------------------------------------------------- +The *g:ycm_filetype_specific_completion_to_disable* option + +This option controls for which Vim filetypes (see ':h filetype') should the YCM +semantic completion engine be turned off. The option value should be a Vim +dictionary with keys being filetype strings (like 'python', 'cpp' etc) and +values being unimportant (the dictionary is used like a hash set, meaning that +only the keys matter). The listed filetypes will be ignored by the YCM semantic +completion engine, but the identifier-based completion engine will still +trigger in files of those filetypes. + +Note that even if semantic completion is not turned off for a specific +filetype, you will not get semantic completion if the semantic engine does not +support that filetype. + +You can get the filetype of the current file in Vim with ':set ft?'. + +Default: '[see next line]' +> + let g:ycm_filetype_specific_completion_to_disable = { + \ 'gitcommit': 1 + \} +< +------------------------------------------------------------------------------- +The *g:ycm_show_diagnostics_ui* option + +When set, this option turns on YCM's diagnostic display features. See the +_Diagnostic display_ section in the _User Manual_ for more details. + +Specific parts of the diagnostics UI (like the gutter signs, text highlighting, +diagnostic echo and auto location list population) can be individually turned +on or off. See the other options below for details. + +Note that YCM's diagnostics UI is only supported for C-family languages. + +When set, this option also makes YCM remove all Syntastic checkers set for the +'c', 'cpp', 'objc' and 'objcpp' filetypes since this would conflict with YCM's +own diagnostics UI. + +If you're using YCM's identifier completer in C-family languages but cannot use +the clang-based semantic completer for those languages _and_ want to use the +GCC Syntastic checkers, unset this option. + +Default: '1' +> + let g:ycm_show_diagnostics_ui = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_error_symbol* option + +YCM will use the value of this option as the symbol for errors in the Vim +gutter. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the 'g:syntastic_error_symbol' option +before using this option's default. + +Default: '>>' +> + let g:ycm_error_symbol = '>>' +< +------------------------------------------------------------------------------- +The *g:ycm_warning_symbol* option + +YCM will use the value of this option as the symbol for warnings in the Vim +gutter. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the 'g:syntastic_warning_symbol' option +before using this option's default. + +Default: '>>' +> + let g:ycm_warning_symbol = '>>' +< +------------------------------------------------------------------------------- +The *g:ycm_enable_diagnostic_signs* option + +When this option is set, YCM will put icons in Vim's gutter on lines that have +a diagnostic set. Turning this off will also turn off the 'YcmErrorLine' and +'YcmWarningLine' highlighting. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the 'g:syntastic_enable_signs' option +before using this option's default. + +Default: '1' +> + let g:ycm_enable_diagnostic_signs = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_enable_diagnostic_highlighting* option + +When this option is set, YCM will highlight regions of text that are related to +the diagnostic that is present on a line, if any. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the 'g:syntastic_enable_highlighting' +option before using this option's default. + +Default: '1' +> + let g:ycm_enable_diagnostic_highlighting = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_echo_current_diagnostic* option + +When this option is set, YCM will echo the text of the diagnostic present on +the current line when you move your cursor to that line. If a |FixIt| is +available for the current diagnostic, then '(FixIt)' is appended. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the 'g:syntastic_echo_current_error' +option before using this option's default. + +Default: '1' +> + let g:ycm_echo_current_diagnostic = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_always_populate_location_list* option + +When this option is set, YCM will populate the location list automatically +every time it gets new diagnostic data. This option is off by default so as not +to interfere with other data you might have placed in the location list. + +See ':help location-list' in Vim to learn more about the location list. + +This option is part of the Syntastic compatibility layer; if the option is not +set, YCM will fall back to the value of the +'g:syntastic_always_populate_loc_list' option before using this option's +default. + +Default: '0' +> + let g:ycm_always_populate_location_list = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_open_loclist_on_ycm_diags* option + +When this option is set, |:YcmDiags| will automatically open the location list +after forcing a compilation and filling the list with diagnostic data. + +See ':help location-list' in Vim to learn more about the location list. + +Default: '1' +> + let g:ycm_open_loclist_on_ycm_diags = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_allow_changing_updatetime* option + +When this option is set to '1', YCM will change the 'updatetime' Vim option to +'2000' (see ':h updatetime'). This may conflict with some other plugins you +have (but it's unlikely). The 'updatetime' option is the number of milliseconds +that have to pass before Vim's 'CursorHold' (see ':h CursorHold') event fires. +YCM runs the completion engines' "file comprehension" systems in the background +on every such event; the identifier-based engine collects the identifiers +whereas the semantic engine compiles the file to build an AST. + +The Vim default of '4000' for 'updatetime' is a bit long, so YCM reduces this. +Set this option to '0' to force YCM to leave your 'updatetime' setting alone. + +Default: '1' +> + let g:ycm_allow_changing_updatetime = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_complete_in_comments* option + +When this option is set to '1', YCM will show the completion menu even when +typing inside comments. + +Default: '0' +> + let g:ycm_complete_in_comments = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_complete_in_strings* option + +When this option is set to '1', YCM will show the completion menu even when +typing inside strings. + +Note that this is turned on by default so that you can use the filename +completion inside strings. This is very useful for instance in C-family files +where typing '#include "' will trigger the start of filename completion. If you +turn off this option, you will turn off filename completion in such situations +as well. + +Default: '1' +> + let g:ycm_complete_in_strings = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_collect_identifiers_from_comments_and_strings* option + +When this option is set to '1', YCM's identifier completer will also collect +identifiers from strings and comments. Otherwise, the text in comments and +strings will be ignored. + +Default: '0' +> + let g:ycm_collect_identifiers_from_comments_and_strings = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_collect_identifiers_from_tags_files* option + +When this option is set to '1', YCM's identifier completer will also collect +identifiers from tags files. The list of tags files to examine is retrieved +from the 'tagfiles()' Vim function which examines the 'tags' Vim option. See +":h 'tags'" for details. + +YCM will re-index your tags files if it detects that they have been modified. + +The only supported tag format is the Exuberant Ctags format [52]. The format +from "plain" ctags is NOT supported. Ctags needs to be called with the '-- +fields=+l' option (that's a lowercase 'L', not a one) because YCM needs the +'language:<lang>' field in the tags output. + +See the _FAQ_ for pointers if YCM does not appear to read your tag files. + +This option is off by default because it makes Vim slower if your tags are on a +network directory. + +Default: '0' +> + let g:ycm_collect_identifiers_from_tags_files = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_seed_identifiers_with_syntax* option + +When this option is set to '1', YCM's identifier completer will seed its +identifier database with the keywords of the programming language you're +writing. + +Since the keywords are extracted from the Vim syntax file for the filetype, all +keywords may not be collected, depending on how the syntax file was written. +Usually at least 95% of the keywords are successfully extracted. + +Default: '0' +> + let g:ycm_seed_identifiers_with_syntax = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_extra_conf_vim_data* option + +If you're using semantic completion for C-family files, this option might come +handy; it's a way of sending data from Vim to your 'FlagsForFile' function in +your '.ycm_extra_conf.py' file. + +This option is supposed to be a list of VimScript expression strings that are +evaluated for every request to the ycmd server [39] and then passed to your +'FlagsForFile' function as a 'client_data' keyword argument. + +For instance, if you set this option to "['v:version']", your 'FlagsForFile' +function will be called like this: +> + # The '704' value is of course contingent on Vim 7.4; in 7.3 it would be '703' + FlagsForFile(filename, client_data = {'v:version': 704}) +< +So the 'client_data' parameter is a dictionary mapping Vim expression strings +to their values at the time of the request. + +The correct way to define parameters for your 'FlagsForFile' function: +> + def FlagsForFile(filename, **kwargs): +< +You can then get to 'client_data' with "kwargs['client_data']". + +Default: '[]' +> + let g:ycm_extra_conf_vim_data = [] +< +------------------------------------------------------------------------------- +The *g:ycm_server_python_interpreter* option + +YCM will by default search for an appropriate Python interpreter on your +system. You can use this option to override that behavior and force the use of +a specific interpreter of your choosing. + +NOTE: This interpreter is only used for the ycmd server [39]. The YCM client +running inside Vim always uses the Python interpreter that's embedded inside +Vim. + +Default: "''" +> + let g:ycm_server_python_interpreter = '' +< +------------------------------------------------------------------------------- +The *g:ycm_server_keep_logfiles* option + +When this option is set to '1', the ycmd completion server [39] will keep the +logfiles around after shutting down (they are deleted on shutdown by default). + +To see where the logfiles are, call |:YcmDebugInfo|. + +Default: '0' +> + let g:ycm_server_keep_logfiles = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_server_log_level* option + +The logging level that the ycmd completion server [39] uses. Valid values are +the following, from most verbose to least verbose: - 'debug' - 'info' - +'warning' - 'error' - 'critical' + +Note that 'debug' is _very_ verbose. + +Default: 'info' +> + let g:ycm_server_log_level = 'info' +< +------------------------------------------------------------------------------- +The *g:ycm_auto_start_csharp_server* option + +When set to '1', the OmniSharp server will be automatically started (once per +Vim session) when you open a C# file. + +Default: '1' +> + let g:ycm_auto_start_csharp_server = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_auto_stop_csharp_server* option + +When set to '1', the OmniSharp server will be automatically stopped upon +closing Vim. + +Default: '1' +> + let g:ycm_auto_stop_csharp_server = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_csharp_server_port* option + +When g:ycm_auto_start_csharp_server is set to '1', specifies the port for the +OmniSharp server to listen on. When set to '0' uses an unused port provided by +the OS. + +Default: '0' +> + let g:ycm_csharp_server_port = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_csharp_insert_namespace_expr* option + +By default, when YCM inserts a namespace, it will insert the 'using' statement +under the nearest 'using' statement. You may prefer that the 'using' statement +is inserted somewhere, for example, to preserve sorting. If so, you can set +this option to override this behavior. + +When this option is set, instead of inserting the 'using' statement itself, YCM +will set the global variable 'g:ycm_namespace_to_insert' to the namespace to +insert, and then evaluate this option's value as an expression. The option's +expression is responsible for inserting the namespace - the default insertion +will not occur. + +Default: '' +> + let g:ycm_csharp_insert_namespace_expr = '' +< +------------------------------------------------------------------------------- +The *g:ycm_add_preview_to_completeopt* option + +When this option is set to '1', YCM will add the 'preview' string to Vim's +'completeopt' option (see ':h completeopt'). If your 'completeopt' option +already has 'preview' set, there will be no effect. You can see the current +state of your 'completeopt' setting with ':set completeopt?' (yes, the question +mark is important). + +When 'preview' is present in 'completeopt', YCM will use the 'preview' window +at the top of the file to store detailed information about the current +completion candidate (but only if the candidate came from the semantic engine). +For instance, it would show the full function prototype and all the function +overloads in the window if the current completion is a function name. + +Default: '0' +> + let g:ycm_add_preview_to_completeopt = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_autoclose_preview_window_after_completion* option + +When this option is set to '1', YCM will auto-close the 'preview' window after +the user accepts the offered completion string. If there is no 'preview' window +triggered because there is no 'preview' string in 'completeopt', this option is +irrelevant. See the |g:ycm_add_preview_to_completeopt| option for more details. + +Default: '0' +> + let g:ycm_autoclose_preview_window_after_completion = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_autoclose_preview_window_after_insertion* option + +When this option is set to '1', YCM will auto-close the 'preview' window after +the user leaves insert mode. This option is irrelevant if +|g:ycm_autoclose_preview_window_after_completion| is set or if no 'preview' +window is triggered. See the |g:ycm_add_preview_to_completeopt| option for more +details. + +Default: '0' +> + let g:ycm_autoclose_preview_window_after_insertion = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_max_diagnostics_to_display* option + +This option controls the maximum number of diagnostics shown to the user when +errors or warnings are detected in the file. This option is only relevant if +you are using the C-family semantic completion engine. + +Default: '30' +> + let g:ycm_max_diagnostics_to_display = 30 +< +------------------------------------------------------------------------------- +The *g:ycm_key_list_select_completion* option + +This option controls the key mappings used to select the first completion +string. Invoking any of them repeatedly cycles forward through the completion +list. + +Some users like adding '<Enter>' to this list. + +Default: "['<TAB>', '<Down>']" +> + let g:ycm_key_list_select_completion = ['<TAB>', '<Down>'] +< +------------------------------------------------------------------------------- +The *g:ycm_key_list_previous_completion* option + +This option controls the key mappings used to select the previous completion +string. Invoking any of them repeatedly cycles backwards through the completion +list. + +Note that one of the defaults is '<S-TAB>' which means Shift-TAB. That mapping +will probably only work in GUI Vim (Gvim or MacVim) and not in plain console +Vim because the terminal usually does not forward modifier key combinations to +Vim. + +Default: "['<S-TAB>', '<Up>']" +> + let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>'] +< +------------------------------------------------------------------------------- +The *g:ycm_key_invoke_completion* option + +This option controls the key mapping used to invoke the completion menu for +semantic completion. By default, semantic completion is trigged automatically +after typing '.', '->' and '::' in insert mode (if semantic completion support +has been compiled in). This key mapping can be used to trigger semantic +completion anywhere. Useful for searching for top-level functions and classes. + +Console Vim (not Gvim or MacVim) passes '<Nul>' to Vim when the user types +'<C-Space>' so YCM will make sure that '<Nul>' is used in the map command when +you're editing in console Vim, and '<C-Space>' in GUI Vim. This means that you +can just press '<C-Space>' in both console and GUI Vim and YCM will do the +right thing. + +Setting this option to an empty string will make sure no mapping is created. + +Default: '<C-Space>' +> + let g:ycm_key_invoke_completion = '<C-Space>' +< +------------------------------------------------------------------------------- +The *g:ycm_key_detailed_diagnostics* option + +This option controls the key mapping used to show the full diagnostic text when +the user's cursor is on the line with the diagnostic. It basically calls +|:YcmShowDetailedDiagnostic|. + +Setting this option to an empty string will make sure no mapping is created. + +Default: '<leader>d' +> + let g:ycm_key_detailed_diagnostics = '<leader>d' +< +------------------------------------------------------------------------------- +The *g:ycm_global_ycm_extra_conf* option + +Normally, YCM searches for a '.ycm_extra_conf.py' file for compilation flags +(see the User Guide for more details on how this works). This option specifies +a fallback path to a config file which is used if no '.ycm_extra_conf.py' is +found. + +You can place such a global file anywhere in your filesystem. + +Default: "''" +> + let g:ycm_global_ycm_extra_conf = '' +< +------------------------------------------------------------------------------- +The *g:ycm_confirm_extra_conf* option + +When this option is set to '1' YCM will ask once per '.ycm_extra_conf.py' file +if it is safe to be loaded. This is to prevent execution of malicious code from +a '.ycm_extra_conf.py' file you didn't write. + +To selectively get YCM to ask/not ask about loading certain +'.ycm_extra_conf.py' files, see the |g:ycm_extra_conf_globlist| option. + +Default: '1' +> + let g:ycm_confirm_extra_conf = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_extra_conf_globlist* option + +This option is a list that may contain several globbing patterns. If a pattern +starts with a '!' all '.ycm_extra_conf.py' files matching that pattern will be +blacklisted, that is they won't be loaded and no confirmation dialog will be +shown. If a pattern does not start with a '!' all files matching that pattern +will be whitelisted. Note that this option is not used when confirmation is +disabled using |g:ycm_confirm_extra_conf| and that items earlier in the list +will take precedence over the later ones. + +Rules: + +- '*' matches everything +- '?' matches any single character +- '[seq]' matches any character in seq +- '[!seq]' matches any char not in seq + +Example: +> + let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*'] +< +- The first rule will match everything contained in the '~/dev' directory so + '.ycm_extra_conf.py' files from there will be loaded. + +- The second rule will match everything in the home directory so a + '.ycm_extra_conf.py' file from there won't be loaded. + +- As the first rule takes precedence everything in the home directory + excluding the '~/dev' directory will be blacklisted. + +NOTE: The glob pattern is first expanded with Python's 'os.path.expanduser()' +and then resolved with 'os.path.abspath()' before being matched against the +filename. + +Default: '[]' +> + let g:ycm_extra_conf_globlist = [] +< +------------------------------------------------------------------------------- +The *g:ycm_filepath_completion_use_working_dir* option + +By default, YCM's filepath completion will interpret relative paths like '../' +as being relative to the folder of the file of the currently active buffer. +Setting this option will force YCM to always interpret relative paths as being +relative to Vim's current working directory. + +Default: '0' +> + let g:ycm_filepath_completion_use_working_dir = 0 +< +------------------------------------------------------------------------------- +The *g:ycm_semantic_triggers* option + +This option controls the character-based triggers for the various semantic +completion engines. The option holds a dictionary of key-values, where the keys +are Vim's filetype strings delimited by commas and values are lists of strings, +where the strings are the triggers. + +Setting key-value pairs on the dictionary _adds_ semantic triggers to the +internal default set (listed below). You cannot remove the default triggers, +only add new ones. + +A "trigger" is a sequence of one or more characters that trigger semantic +completion when typed. For instance, C++ ('cpp' filetype) has '.' listed as a +trigger. So when the user types 'foo.', the semantic engine will trigger and +serve 'foo''s list of member functions and variables. Since C++ also has '->' +listed as a trigger, the same thing would happen when the user typed 'foo->'. + +It's also possible to use a regular expression as a trigger. You have to prefix +your trigger with 're!' to signify it's a regex trigger. For instance, +'re!\w+\.' would only trigger after the '\w+\.' regex matches. + +NOTE: The regex syntax is **NOT** Vim's, it's Python's [53]. + +Default: '[see next line]' +> + let g:ycm_semantic_triggers = { + \ 'c' : ['->', '.'], + \ 'objc' : ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s', + \ 're!\[.*\]\s'], + \ 'ocaml' : ['.', '#'], + \ 'cpp,objcpp' : ['->', '.', '::'], + \ 'perl' : ['->'], + \ 'php' : ['->', '::'], + \ 'cs,java,javascript,typescript,d,python,perl6,scala,vb,elixir,go' : ['.'], + \ 'ruby' : ['.', '::'], + \ 'lua' : ['.', ':'], + \ 'erlang' : [':'], + \ } +< +------------------------------------------------------------------------------- +The *g:ycm_cache_omnifunc* option + +Some omnicompletion engines do not work well with the YCM cache—in particular, +they might not produce all possible results for a given prefix. By unsetting +this option you can ensure that the omnicompletion engine is re-queried on +every keypress. That will ensure all completions will be presented, but might +cause stuttering and lagginess if the omnifunc is slow. + +Default: '1' +> + let g:ycm_cache_omnifunc = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_use_ultisnips_completer* option + +By default, YCM will query the UltiSnips plugin for possible completions of +snippet triggers. This option can turn that behavior off. + +Default: '1' +> + let g:ycm_use_ultisnips_completer = 1 +< +------------------------------------------------------------------------------- +The *g:ycm_goto_buffer_command* option + +Defines where 'GoTo*' commands result should be opened. Can take one of the +following values: "[ 'same-buffer', 'horizontal-split', 'vertical-split', 'new- +tab', 'new-or-existing-tab' ]" If this option is set to the "'same-buffer'" but +current buffer can not be switched (when buffer is modified and 'nohidden' +option is set), then result will be opened in horizontal split. + +Default: "'same-buffer'" +> + let g:ycm_goto_buffer_command = 'same-buffer' +< +------------------------------------------------------------------------------- +The *g:ycm_disable_for_files_larger_than_kb* option + +Defines the max size (in Kb) for a file to be considered for completion. If +this option is set to 0 then no check is made on the size of the file you're +opening. + +Default: 1000 +> + let g:ycm_disable_for_files_larger_than_kb = 1000 +< +------------------------------------------------------------------------------- +The *g:ycm_python_binary_path* option + +This option specifies the Python interpreter to use to run the jedi [6] +completion library. Specify the Python interpreter to use to get completions. +By default the Python under which ycmd [39] runs is used (ycmd [39] runs on +Python 2.6, 2.7 or 3.3+). + +Default: "''" +> + let g:ycm_python_binary_path = 'python' +< +NOTE: the settings above will make YCM use the first 'python' executable found +through the PATH. + +=============================================================================== + *youcompleteme-faq* +FAQ ~ + +------------------------------------------------------------------------------- + *import-vim* +I used to be able to 'import vim' in '.ycm_extra_conf.py', but now can't ~ + +YCM was rewritten to use a client-server architecture where most of the logic +is in the ycmd server [39]. So the magic 'vim' module you could have previously +imported in your '.ycm_extra_conf.py' files doesn't exist anymore. + +To be fair, importing the magic 'vim' module in extra conf files was never +supported in the first place; it only ever worked by accident and was never a +part of the extra conf API. + +But fear not, you should be able to tweak your extra conf files to continue +working by using the |g:ycm_extra_conf_vim_data| option. See the docs on that +option for details. + +------------------------------------------------------------------------------- +*youcompleteme-on-very-rare-occasions-vim-crashes-when-i-tab-through-completion-menu* +On very rare occasions Vim crashes when I tab through the completion menu ~ + +That's a very rare Vim bug most users never encounter. It's fixed in Vim +7.4.72. Update to that version (or above) to resolve the issue. + +------------------------------------------------------------------------------- +I get *ImportError* exceptions that mention 'PyInit_ycm_core' or 'initycm_core' + +These errors are caused by building the YCM native libraries for Python 2 and +trying to load them into a Python 3 process (or the other way around). + +For instance, if building for Python 2 but loading in Python 3: +> + ImportError: dynamic module does not define init function (PyInit_ycm_core) +< +If building for Python 3 but loading in Python 2: +> + ImportError: dynamic module does not define init function (initycm_core) +< +Setting the |g:ycm_server_python_interpreter| option to force the use of a +specific Python interpreter for 'ycmd' is usually the easiest way to solve the +problem. Common values for that option are '/usr/bin/python' and +'/usr/bin/python3'. + +------------------------------------------------------------------------------- +I get a linker warning regarding *libpython* on Mac when compiling YCM + +If the warning is "ld: warning: path '/usr/lib/libpython2.7.dylib' following -L +not a directory", then feel free to ignore it; it's caused by a limitation of +CMake and is not an issue. Everything should still work fine. + +------------------------------------------------------------------------------- +*youcompleteme-i-get-weird-window-at-top-of-my-file-when-i-use-semantic-engine* +I get a weird window at the top of my file when I use the semantic engine ~ + +This is Vim's 'preview' window. Vim uses it to show you extra information about +something if such information is available. YCM provides Vim with such extra +information. For instance, when you select a function in the completion list, +the 'preview' window will hold that function's prototype and the prototypes of +any overloads of the function. It will stay there after you select the +completion so that you can use the information about the parameters and their +types to write the function call. + +If you would like this window to auto-close after you select a completion +string, set the |g:ycm_autoclose_preview_window_after_completion| option to '1' +in your 'vimrc' file. Similarly, the +|g:ycm_autoclose_preview_window_after_insertion| option can be set to close the +'preview' window after leaving insert mode. + +If you don't want this window to ever show up, add 'set completeopt-=preview' +to your 'vimrc'. Also make sure that the |g:ycm_add_preview_to_completeopt| +option is set to '0'. + +------------------------------------------------------------------------------- + *youcompleteme-it-appears-that-ycm-is-not-working* +It appears that YCM is not working ~ + +In Vim, run ':messages' and carefully read the output. YCM will echo messages +to the message log if it encounters problems. It's likely you misconfigured +something and YCM is complaining about it. + +Also, you may want to run the |:YcmDebugInfo| command; it will make YCM spew +out various debugging information, including the ycmd [39] logfile paths and +the compile flags for the current file if the file is a C-family language file +and you have compiled in Clang support. Logfiles can be automatically opened in +the editor using the |:YcmToggleLogs| command. + +------------------------------------------------------------------------------- +*youcompleteme-sometimes-it-takes-much-longer-to-get-semantic-completions-than-normal* +Sometimes it takes much longer to get semantic completions than normal ~ + +This means that libclang (which YCM uses for C-family semantic completion) +failed to pre-compile your file's preamble. In other words, there was an error +compiling some of the source code you pulled in through your header files. I +suggest calling the |:YcmDiags| command to see what they were. + +Bottom line, if libclang can't pre-compile your file's preamble because there +were errors in it, you're going to get slow completions because there's no AST +cache. + +------------------------------------------------------------------------------- + *youcompleteme-ycm-auto-inserts-completion-strings-i-dont-want* +YCM auto-inserts completion strings I don't want! ~ + +This means you probably have some mappings that interfere with YCM's internal +ones. Make sure you don't have something mapped to '<C-p>', '<C-x>' or '<C-u>' +(in insert mode). + +YCM _never_ selects something for you; it just shows you a menu and the user +has to explicitly select something. If something is being selected +automatically, this means there's a bug or a misconfiguration somewhere. + +------------------------------------------------------------------------------- + *E227:-mapping-already-exists-for-blah* +I get a 'E227: mapping already exists for <blah>' error when I start Vim ~ + +This means that YCM tried to set up a key mapping but failed because you +already had something mapped to that key combination. The '<blah>' part of the +message will tell you what was the key combination that failed. + +Look in the _Options_ section and see if any of the default mappings conflict +with your own. Then change that option value to something else so that the +conflict goes away. + +------------------------------------------------------------------------------- + *GLIBC_2.XX-not-found()* +I get "'GLIBC_2.XX' not found (required by libclang.so)" when starting Vim ~ + +Your system is too old for the precompiled binaries from llvm.org. Compile +Clang on your machine and then link against the 'libclang.so' you just +produced. See the full installation guide for help. + +------------------------------------------------------------------------------- + *youcompleteme-im-trying-to-use-homebrew-vim-with-ycm-im-getting-segfaults* +I'm trying to use a Homebrew Vim with YCM and I'm getting segfaults ~ + +Something (I don't know what) is wrong with the way that Homebrew configures +and builds Vim. I recommend using MacVim [18]. Even if you don't like the +MacVim GUI, you can use the Vim binary that is inside the MacVim.app package +(it's 'MacVim.app/Contents/MacOS/Vim') and get the Vim console experience. + +------------------------------------------------------------------------------- +*youcompleteme-i-have-homebrew-python-and-or-macvim-cant-compile-sigabrt-when-starting* +I have a Homebrew Python and/or MacVim; can't compile/SIGABRT when starting ~ + +You should probably run 'brew rm python; brew install python' to get the latest +fixes that should make YCM work with such a configuration. Also rebuild Macvim +then. If you still get problems with this, see issue #18 [54] for suggestions. + +------------------------------------------------------------------------------- + *youcompleteme-vim-segfaults-when-i-use-semantic-completer-in-ruby-files* +Vim segfaults when I use the semantic completer in Ruby files ~ + +This was caused by a Vim bug. Update your version of Vim (Vim 7.3.874 is known +to work, earlier versions may also fix this issue). + +------------------------------------------------------------------------------- + *LONG_BIT-definition-appears-wrong-for-platform* +I get 'LONG_BIT definition appears wrong for platform' when compiling ~ + +Look at the output of your CMake call. There should be a line in it like the +following (with '.dylib' in place of '.so' on a Mac): +> + -- Found PythonLibs: /usr/lib/libpython2.7.so (Required is at least version "2.5") +< +That would be the **correct** output. An example of **incorrect** output would +be the following: +> + -- Found PythonLibs: /usr/lib/libpython2.7.so (found suitable version "2.5.1", minimum required is "2.5") +< +Notice how there's an extra bit of output there, the 'found suitable version +"<version>"' part, where '<version>' is not the same as the version of the +dynamic library. In the example shown, the library is version 2.7 but the +second string is version '2.5.1'. + +This means that CMake found one version of Python headers and a different +version for the library. This is wrong. It can happen when you have multiple +versions of Python installed on your machine. + +You should probably add the following flags to your cmake call (again, 'dylib' +instead of 'so' on a Mac): +> + -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/libpython2.7.so +< +This will force the paths to the Python include directory and the Python +library to use. You may need to set these flags to something else, but you need +to make sure you use the same version of Python that your Vim binary is built +against, which is highly likely to be the system's default Python. + +------------------------------------------------------------------------------- + *libpython2.7.a-...-relocation-R_X86_64_32* +I get 'libpython2.7.a [...] relocation R_X86_64_32' when compiling ~ + +The error is usually encountered when compiling YCM on Centos or RHEL. The full +error looks something like the following: +> + /usr/bin/ld: /usr/local/lib/libpython2.7.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC +< +It's possible to get a slightly different error that's similar to the one +above. Here's the problem and how you solve it: + +Your 'libpython2.7.a' was not compiled with '-fPIC' so it can't be linked into +'ycm_core.so'. Use the '-DPYTHON_LIBRARY=' CMake flag to point it to a '.so' +version of libpython on your machine (for instance, +'-DPYTHON_LIBRARY=/usr/lib/libpython2.7.so'). Naturally, this means you'll have +to go through the full installation guide by hand. + +------------------------------------------------------------------------------- + *Vim:-Caught-deadly-signal-SEGV* +I get 'Vim: Caught deadly signal SEGV' on Vim startup ~ + +This can happen on some Linux distros. If you encounter this situation, run Vim +under 'gdb'. You'll probably see something like this in the output when Vim +crashes: +> + undefined symbol: clang_CompileCommands_dispose +< +This means that Vim is trying to load a 'libclang.so' that is too old. You need +at least a 3.8 libclang. Just go through the installation guide and make sure +you are using a correct 'libclang.so'. We recommend downloading prebuilt +binaries from llvm.org. + +------------------------------------------------------------------------------- + *Fatal-Python-error:-PyThreadState_Get:-no-current-thread* +I get 'Fatal Python error: PyThreadState_Get: no current thread' on startup ~ + +This is caused by linking a static version of |libpython| into ycmd's +'ycm_core.so'. This leads to multiple copies of the python interpreter loaded +when 'python' loads 'ycmd_core.so' and this messes up python's global state. +The details aren't important. + +The solution is that the version of Python linked and run against must be built +with either '--enable-shared' or '--enable-framework' (on OS X). This is +achieved as follows (NOTE: for Mac, replace '--enable-shared' with '--enable- +framework'): + +- When building python from source: './configure --enable-shared {options}' +- When building python from pyenv: 'PYTHON_CONFIGURE_OPTS="--enable-shared" + pyenv install {version}' + +=============================================================================== +*install.py* says python must be compiled with '--enable-framework'. Wat? + +See the previous answer for how to ensure your python is built to support +dynamic modules. + +------------------------------------------------------------------------------- + *youcompleteme-ycm-does-not-read-identifiers-from-my-tags-files* +YCM does not read identifiers from my tags files ~ + +First, put 'let g:ycm_collect_identifiers_from_tags_files = 1' in your vimrc. + +Make sure you are using Exuberant Ctags [55] to produce your tags files since +the only supported tag format is the Exuberant Ctags format [52]. The format +from "plain" ctags is NOT supported. The output of 'ctags --version' should +list "Exuberant Ctags". + +Ctags needs to be called with the '--fields=+l' (that's a lowercase 'L', not a +one) option because YCM needs the 'language:<lang>' field in the tags output. + +NOTE: Exuberant Ctags [55] by default sets language tag for '*.h' files as +'C++'. If you have C (not C++) project, consider giving parameter '-- +langmap=c:.c.h' to ctags to see tags from '*.h' files. + +NOTE: Mac OS X comes with "plain" ctags installed by default. 'brew install +ctags' will get you the Exuberant Ctags version. + +Also make sure that your Vim 'tags' option is set correctly. See ":h 'tags'" +for details. If you want to see which tag files YCM will read for a given +buffer, run ':echo tagfiles()' with the relevant buffer active. Note that that +function will only list tag files that already exist. + +------------------------------------------------------------------------------- + *CTRL-sub-U* +'CTRL-U' in insert mode does not work ~ + +YCM keeps you in a 'completefunc' completion mode when you're typing in insert +mode and Vim disables '<C-U>' in completion mode as a "feature." Sadly there's +nothing I can do about this. + +------------------------------------------------------------------------------- + *youcompleteme-ycm-conflicts-with-ultisnips-tab-key-usage* +YCM conflicts with UltiSnips TAB key usage ~ + +YCM comes with support for UltiSnips (snippet suggestions in the popup menu), +but you'll have to change the UltiSnips mappings. See ':h UltiSnips-triggers' +in Vim for details. You'll probably want to change some/all of the following +options: +> + g:UltiSnipsExpandTrigger + g:UltiSnipsJumpForwardTrigger + g:UltiSnipsJumpBackwardTrigger +< +------------------------------------------------------------------------------- + *youcompleteme-why-isnt-ycm-just-written-in-plain-vimscript-ffs* +Why isn't YCM just written in plain VimScript, FFS? ~ + +Because of the identifier completion engine and subsequence-based filtering. +Let's say you have _many_ dozens of files open in a single Vim instance (I +often do); the identifier-based engine then needs to store thousands (if not +tens of thousands) of identifiers in its internal data-structures. When the +user types, YCM needs to perform subsequence-based filtering on _all_ of those +identifiers (every single one!) in less than 10 milliseconds. + +I'm sorry, but that level of performance is just plain impossible to achieve +with VimScript. I've tried, and the language is just too slow. No, you can't +get acceptable performance even if you limit yourself to just the identifiers +in the current file and simple prefix-based filtering. + +------------------------------------------------------------------------------- + *youcompleteme-why-does-ycm-demand-such-recent-version-of-vim* +Why does YCM demand such a recent version of Vim? ~ + +During YCM's development several show-stopper bugs were encountered in Vim. +Those needed to be fixed upstream (and were). A few months after those bugs +were fixed, Vim trunk landed the 'pyeval()' function which improved YCM +performance even more since less time was spent serializing and deserializing +data between Vim and the embedded Python interpreter. A few critical bugfixes +for 'pyeval()' landed in Vim 7.3.584 (and a few commits before that). + +------------------------------------------------------------------------------- + *youcompleteme-i-get-annoying-messages-in-vims-status-area-when-i-type* +I get annoying messages in Vim's status area when I type ~ + +If you're referring to the 'User defined completion <bla bla> back at original' +and similar, then just update to Vim 7.4.314 (or later) and they'll go away. + +------------------------------------------------------------------------------- + *vim-sub-autoclose* +Nasty bugs happen if I have the 'vim-autoclose' plugin installed ~ + +Use the delimitMate [56] plugin instead. It does the same thing without +conflicting with YCM. + +------------------------------------------------------------------------------- + *youcompleteme-is-there-sort-of-ycm-mailing-list-i-have-questions* +Is there some sort of YCM mailing list? I have questions ~ + +If you have questions about the plugin or need help, please use the ycm-users +[57] mailing list, _don't_ create issues on the tracker. The tracker is for bug +reports and feature requests. + +------------------------------------------------------------------------------- + *youcompleteme-i-get-an-internal-compiler-error-when-installing* +I get an internal compiler error when installing ~ + +This can be a problem on virtual servers with limited memory. A possible +solution is to add more swap memory. A more practical solution would be to +force the build script to run only one compile job at a time. You can do this +by setting the 'YCM_CORES' environment variable to '1'. Example: +> + YCM_CORES=1 ./install.py --clang-completer +< +------------------------------------------------------------------------------- + *Ctrl-sub-C* +I get weird errors when I press 'Ctrl-C' in Vim ~ + +_Never_ use 'Ctrl-C' in Vim. + +Using 'Ctrl-C' to exit insert mode in Vim is a bad idea. The main issue here is +that 'Ctrl-C' in Vim doesn't just leave insert mode, it leaves it without +triggering 'InsertLeave' autocommands (as per Vim docs). This is a bad idea and +is likely to break many other things and not just YCM. + +Bottom line, if you use 'Ctrl-C' to exit insert mode in Vim, you're gonna have +a bad time. + +If pressing '<esc>' is too annoying (agreed, it is), we suggest mapping it to +something more convenient. On a QWERTY keyboard, a good pick for the '<esc>' +map is 'inoremap jk <Esc>'. This is right on the home row, it's an incredibly +rare digraph in English and if you ever need to type those two chars in +sequence in insert mode, you just type 'j', then wait 500ms, then type 'k'. + +------------------------------------------------------------------------------- + *youcompleteme-why-did-ycm-stop-using-syntastic-for-diagnostics-display* +Why did YCM stop using Syntastic for diagnostics display? ~ + +Previously, YCM would send any diagnostics it would receive from the libclang +semantic engine to Syntastic for display as signs in the gutter, red squiggles +etc. Today, YCM uses its own code to do that. + +Using Syntastic for this was always a kludge. Syntastic assumes its "checker" +plugins behave in a certain way; those assumptions have never fit YCM. For +instance, YCM continuously recompiles your code in the background for C-family +languages and tries to push new diagnostics to the user as fast as possible, +even while the user types. + +Syntastic assumes that a checker only runs on file save ("active" mode) or even +less frequently, when the user explicitly invokes it ("passive" mode). This +mismatch in assumptions causes performance problems since Syntastic code isn't +optimized for this use case of constant diagnostic refreshing. + +Poor support for this use case also led to crash bugs in Vim caused by +Syntastic-Vim interactions (issue #593 [58]) and other problems, like random +Vim flickering. Attempts were made to resolve these issues in Syntastic, but +ultimately some of them failed (for various reasons). + +Implementing diagnostic display code directly in YCM resolves all of these +problems. Performance also improved substantially since the relevant code is +now written in Python instead of VimScript (which is very slow) and is tailored +only for YCM's use-cases. We were also able to introduce new features in this +area since we're now not limited to the Syntastic checker API. + +We've tried to implement this in the most backwards-compatible way possible; +YCM options that control diagnostic display fall back to Syntastic options that +control the same concepts if the user has those set. + +Still, some Syntastic-specific configuration you might have had might not be +supported by the new code. Please file issues on the tracker in such cases; if +we find the request to be reasonable, we'll find a way to address it. + +------------------------------------------------------------------------------- + *youcompleteme-completion-doesnt-work-with-c-standard-library-headers* +Completion doesn't work with the C++ standard library headers ~ + +This is caused by an issue with libclang that only affects some operating +systems. Compiling with 'clang' the binary will use the correct default header +search paths but compiling with 'libclang.so' (which YCM uses) does not. + +Mac OS X is normally affected, but there's a workaround in YCM for that +specific OS. If you're not running that OS but still have the same problem, +continue reading. + +The workaround is to call 'echo | clang -v -E -x c++ -' and look at the paths +under the '#include <...> search starts here:' heading. You should take those +paths, prepend '-isystem' to each individual path and append them all to the +list of flags you return from your 'FlagsForFile' function in your +'.ycm_extra_conf.py' file. + +See issue #303 [59] for details. + +------------------------------------------------------------------------------- + *.tern-sub-project* +When I open a JavaScript file, I get an annoying warning about '.tern- ~ +project' file ~ + +Take a look at the instructions for using the JavaScript completer. + +If this is still really annoying, and you have a good reason not to have a +'.tern-project' file, create an empty '.tern-config' file in your home +directory and YCM will stop complaining. + +------------------------------------------------------------------------------- +*R6034-An-application-has-made-an-attempt-to-load-the-C-runtime-library-incorrectly.* +When I start vim I get a runtime error saying 'R6034 An application has made ~ +an attempt to load the C runtime library incorrectly.' ~ + +CMake and other things seem to screw up the PATH with their own msvcrXX.dll +versions. [60] Add the following to the very top of your vimrc to remove these +entries from the path. +> + python << EOF + import os + import re + path = os.environ['PATH'].split(';') + + def contains_msvcr_lib(folder): + try: + for item in os.listdir(folder): + if re.match(r'msvcr\d+\.dll', item): + return True + except: + pass + return False + + path = [folder for folder in path if not contains_msvcr_lib(folder)] + os.environ['PATH'] = ';'.join(path) + EOF +< +------------------------------------------------------------------------------- + *youcompleteme-i-hear-that-ycm-only-supports-python-2-is-that-true* +I hear that YCM only supports Python 2, is that true? ~ + +**No.** Both the Vim client and the ycmd server [39] run on Python 2 or 3. If +you work on a Python 3 project, you may need to set |g:ycm_python_binary_path| +to the Python interpreter you use for your project to get completions for that +version of Python. + +------------------------------------------------------------------------------- +*E887:-Sorry-this-command-is-disabled-the-Python-s-site-module-could-not-be-loaded* +On Windows I get "E887: Sorry, this command is disabled, the Python's site ~ +module could not be loaded" ~ + +If you are running vim on Windows with Python 2.7.11, this is likely caused by +a bug [61]. Follow this workaround [62] or use a different version (Python +2.7.9 does not suffer from the bug). + +------------------------------------------------------------------------------- + *youcompleteme-i-cant-complete-python-packages-in-virtual-environment.* +I can't complete python packages in a virtual environment. ~ + +This means that the Python used to run JediHTTP [7] is not the Python of the +virtual environment you're in. To resolve this you either set +|g:ycm_python_binary_path| to the absolute path of the Python binary in your +virtual environment or since virtual environment will put that Python +executable first in your PATH when the virtual environment is active then if +you set |g:ycm_python_binary_path| to just "'python'" it will be found as the +first Python and used to run JediHTTP [7]. + +=============================================================================== + *youcompleteme-contributor-code-of-conduct* +Contributor Code of Conduct ~ + +Please note that this project is released with a Contributor Code of Conduct +[63]. By participating in this project you agree to abide by its terms. + +=============================================================================== + *youcompleteme-contact* +Contact ~ + +If you have questions about the plugin or need help, please use the ycm-users +[57] mailing list. + +If you have bug reports or feature suggestions, please use the issue tracker +[64]. + +The latest version of the plugin is available at +http://valloric.github.io/YouCompleteMe/. + +The author's homepage is http://val.markovic.io. + +=============================================================================== + *youcompleteme-license* +License ~ + +This software is licensed under the GPL v3 license [65]. © 2015-2016 +YouCompleteMe contributors + +=============================================================================== + *youcompleteme-references* +References ~ + +[1] https://travis-ci.org/Valloric/YouCompleteMe +[2] https://travis-ci.org/Valloric/YouCompleteMe.svg?branch=master +[3] https://ci.appveyor.com/project/Valloric/YouCompleteMe +[4] https://ci.appveyor.com/api/projects/status/ag9uqwi8s6btwjd8/branch/master?svg=true +[5] http://clang.llvm.org/ +[6] https://github.com/davidhalter/jedi +[7] https://github.com/vheon/JediHTTP +[8] https://github.com/OmniSharp/omnisharp-server +[9] https://github.com/nsf/gocode +[10] https://github.com/Manishearth/godef +[11] https://github.com/Microsoft/TypeScript/tree/master/src/server +[12] http://ternjs.net +[13] https://github.com/phildawes/racer +[14] http://i.imgur.com/0OP4ood.gif +[15] https://en.wikipedia.org/wiki/Subsequence +[16] https://github.com/scrooloose/syntastic +[17] https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt +[18] https://github.com/macvim-dev/macvim/releases +[19] https://github.com/VundleVim/Vundle.vim#about +[20] http://brew.sh +[21] https://cmake.org/download/ +[22] http://www.mono-project.com/docs/getting-started/install/mac/ +[23] https://golang.org/doc/install +[24] https://docs.npmjs.com/getting-started/installing-node +[25] https://www.rust-lang.org/ +[26] https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source +[27] http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives +[28] http://www.mono-project.com/docs/getting-started/install/linux/#centos-7-fedora-19-and-later-and-derivatives +[29] https://bintray.com/micbou/generic/vim +[30] https://www.python.org/downloads/windows/ +[31] https://www.visualstudio.com/products/free-developer-offers-vs.aspx +[32] http://www.7-zip.org/download.html +[33] http://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1 +[34] https://github.com/tpope/vim-pathogen#pathogenvim +[35] http://vimhelp.appspot.com/starting.txt.html#vimrc +[36] http://llvm.org/releases/download.html +[37] http://www.mono-project.com/docs/getting-started/install/ +[38] https://github.com/Valloric/YouCompleteMe#options +[39] https://github.com/Valloric/ycmd +[40] https://github.com/Valloric/ycmd/blob/master/cpp/ycm/.ycm_extra_conf.py +[41] http://clang.llvm.org/docs/JSONCompilationDatabase.html +[42] https://github.com/rizsotto/Bear +[43] https://github.com/rdnetto/YCM-Generator +[44] http://ternjs.net/doc/manual.html#configuration +[45] http://ternjs.net/doc/manual.html#server +[46] http://ternjs.net/doc/manual.html#plugins +[47] https://www.rust-lang.org/downloads.html +[48] http://eclim.org/ +[49] https://github.com/Valloric/ycmd/blob/master/ycmd/completers/completer.py +[50] https://github.com/Valloric/ListToggle +[51] https://github.com/itchyny/lightline.vim +[52] http://ctags.sourceforge.net/FORMAT +[53] https://docs.python.org/2/library/re.html#regular-expression-syntax +[54] https://github.com/Valloric/YouCompleteMe/issues/18 +[55] http://ctags.sourceforge.net/ +[56] https://github.com/Raimondi/delimitMate +[57] https://groups.google.com/forum/?hl=en#!forum/ycm-users +[58] https://github.com/Valloric/YouCompleteMe/issues/593 +[59] https://github.com/Valloric/YouCompleteMe/issues/303 +[60] http://stackoverflow.com/questions/14552348/runtime-error-r6034-in-embedded-python-application/34696022 +[61] https://github.com/vim/vim/issues/717 +[62] https://github.com/vim/vim-win32-installer/blob/master/appveyor.bat#L90 +[63] https://github.com/Valloric/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md +[64] https://github.com/Valloric/YouCompleteMe/issues?state=open +[65] http://www.gnu.org/copyleft/gpl.html + +vim: ft=help diff --git a/vim/bundle/YouCompleteMe/install.py b/vim/bundle/YouCompleteMe/install.py new file mode 100755 index 0000000..36bb70e --- /dev/null +++ b/vim/bundle/YouCompleteMe/install.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import + +import os +import subprocess +import sys +import os.path as p +import glob + +PY_MAJOR, PY_MINOR = sys.version_info[ 0 : 2 ] +if not ( ( PY_MAJOR == 2 and PY_MINOR >= 6 ) or + ( PY_MAJOR == 3 and PY_MINOR >= 3 ) or + PY_MAJOR > 3 ): + sys.exit( 'YouCompleteMe requires Python >= 2.6 or >= 3.3; ' + 'your version of Python is ' + sys.version ) + +DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) +DIR_OF_OLD_LIBS = p.join( DIR_OF_THIS_SCRIPT, 'python' ) + + +def Main(): + build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ) + + if not p.isfile( build_file ): + sys.exit( 'File ' + build_file + ' does not exist; you probably forgot ' + 'to run:\n\tgit submodule update --init --recursive\n\n' ) + + python_binary = sys.executable + subprocess.check_call( [ python_binary, build_file ] + sys.argv[1:] ) + + # Remove old YCM libs if present so that YCM can start. + old_libs = ( + glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_core.*' ) ) + + glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_client_support.*' ) ) + + glob.glob( p.join( DIR_OF_OLD_LIBS, '*clang*.*') ) ) + for lib in old_libs: + os.remove( lib ) + +if __name__ == "__main__": + Main() diff --git a/vim/bundle/YouCompleteMe/install.sh b/vim/bundle/YouCompleteMe/install.sh new file mode 100755 index 0000000..8c9c2fd --- /dev/null +++ b/vim/bundle/YouCompleteMe/install.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +echo "WARNING: this script is deprecated. Use the install.py script instead." 1>&2 + + +SCRIPT_DIR=$(dirname $0 || exit $?) + +command_exists() { + command -v "$1" >/dev/null 2>&1 ; +} + +PYTHON_BINARY=python +if command_exists python2; then + PYTHON_BINARY=python2 +fi + +$PYTHON_BINARY "$SCRIPT_DIR/install.py" "$@" || exit $? diff --git a/vim/bundle/YouCompleteMe/plugin/youcompleteme.vim b/vim/bundle/YouCompleteMe/plugin/youcompleteme.vim new file mode 100644 index 0000000..4aa5c33 --- /dev/null +++ b/vim/bundle/YouCompleteMe/plugin/youcompleteme.vim @@ -0,0 +1,138 @@ +" Copyright (C) 2011, 2012 Google Inc. +" +" This file is part of YouCompleteMe. +" +" YouCompleteMe 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. +" +" YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +" This is basic vim plugin boilerplate +let s:save_cpo = &cpo +set cpo&vim + +function! s:restore_cpo() + let &cpo = s:save_cpo + unlet s:save_cpo +endfunction + +if exists( "g:loaded_youcompleteme" ) + call s:restore_cpo() + finish +elseif v:version < 703 || (v:version == 703 && !has('patch598')) + echohl WarningMsg | + \ echomsg "YouCompleteMe unavailable: requires Vim 7.3.598+" | + \ echohl None + call s:restore_cpo() + finish +elseif !has( 'python' ) && !has( 'python3' ) + echohl WarningMsg | + \ echomsg "YouCompleteMe unavailable: requires Vim compiled with " . + \ "Python (2.6+ or 3.3+) support" | + \ echohl None + call s:restore_cpo() + finish +endif + +let g:loaded_youcompleteme = 1 + +" NOTE: Most defaults are in third_party/ycmd/ycmd/default_settings.json. They +" are loaded into Vim globals with the 'ycm_' prefix if such a key does not +" already exist; thus, the user can override the defaults. +" The only defaults that are here are the ones that are only relevant to the YCM +" Vim client and not the ycmd server. + +let g:ycm_allow_changing_updatetime = + \ get( g:, 'ycm_allow_changing_updatetime', 1 ) + +let g:ycm_open_loclist_on_ycm_diags = + \ get( g:, 'ycm_open_loclist_on_ycm_diags', 1 ) + +let g:ycm_add_preview_to_completeopt = + \ get( g:, 'ycm_add_preview_to_completeopt', 0 ) + +let g:ycm_autoclose_preview_window_after_completion = + \ get( g:, 'ycm_autoclose_preview_window_after_completion', 0 ) + +let g:ycm_autoclose_preview_window_after_insertion = + \ get( g:, 'ycm_autoclose_preview_window_after_insertion', 0 ) + +let g:ycm_key_list_select_completion = + \ get( g:, 'ycm_key_list_select_completion', ['<TAB>', '<Down>'] ) + +let g:ycm_key_list_previous_completion = + \ get( g:, 'ycm_key_list_previous_completion', ['<S-TAB>', '<Up>'] ) + +let g:ycm_key_invoke_completion = + \ get( g:, 'ycm_key_invoke_completion', '<C-Space>' ) + +let g:ycm_key_detailed_diagnostics = + \ get( g:, 'ycm_key_detailed_diagnostics', '<leader>d' ) + +let g:ycm_cache_omnifunc = + \ get( g:, 'ycm_cache_omnifunc', 1 ) + +let g:ycm_server_log_level = + \ get( g:, 'ycm_server_log_level', 'info' ) + +let g:ycm_server_keep_logfiles = + \ get( g:, 'ycm_server_keep_logfiles', 0 ) + +let g:ycm_extra_conf_vim_data = + \ get( g:, 'ycm_extra_conf_vim_data', [] ) + +let g:ycm_server_python_interpreter = + \ get( g:, 'ycm_server_python_interpreter', + \ get( g:, 'ycm_path_to_python_interpreter', '' ) ) + +let g:ycm_show_diagnostics_ui = + \ get( g:, 'ycm_show_diagnostics_ui', + \ get( g:, 'ycm_register_as_syntastic_checker', 1 ) ) + +let g:ycm_enable_diagnostic_signs = + \ get( g:, 'ycm_enable_diagnostic_signs', + \ get( g:, 'syntastic_enable_signs', 1 ) ) + +let g:ycm_enable_diagnostic_highlighting = + \ get( g:, 'ycm_enable_diagnostic_highlighting', + \ get( g:, 'syntastic_enable_highlighting', 1 ) ) + +let g:ycm_echo_current_diagnostic = + \ get( g:, 'ycm_echo_current_diagnostic', + \ get( g:, 'syntastic_echo_current_error', 1 ) ) + +let g:ycm_always_populate_location_list = + \ get( g:, 'ycm_always_populate_location_list', + \ get( g:, 'syntastic_always_populate_loc_list', 0 ) ) + +let g:ycm_error_symbol = + \ get( g:, 'ycm_error_symbol', + \ get( g:, 'syntastic_error_symbol', '>>' ) ) + +let g:ycm_warning_symbol = + \ get( g:, 'ycm_warning_symbol', + \ get( g:, 'syntastic_warning_symbol', '>>' ) ) + +let g:ycm_goto_buffer_command = + \ get( g:, 'ycm_goto_buffer_command', 'same-buffer' ) + +let g:ycm_disable_for_files_larger_than_kb = + \ get( g:, 'ycm_disable_for_files_larger_than_kb', 1000 ) + +" On-demand loading. Let's use the autoload folder and not slow down vim's +" startup procedure. +augroup youcompletemeStart + autocmd! + autocmd VimEnter * call youcompleteme#Enable() +augroup END + +" This is basic vim plugin boilerplate +call s:restore_cpo() diff --git a/vim/bundle/YouCompleteMe/print_todos.sh b/vim/bundle/YouCompleteMe/print_todos.sh new file mode 100755 index 0000000..c07471c --- /dev/null +++ b/vim/bundle/YouCompleteMe/print_todos.sh @@ -0,0 +1,8 @@ +#!/bin/bash +ag \ +--ignore gmock \ +--ignore jedi/ \ +--ignore OmniSharpServer \ +--ignore testdata \ +TODO \ +third_party/ycmd/cpp/ycm python autoload plugin diff --git a/vim/bundle/YouCompleteMe/python/test_requirements.txt b/vim/bundle/YouCompleteMe/python/test_requirements.txt new file mode 100644 index 0000000..b67c013 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/test_requirements.txt @@ -0,0 +1,6 @@ +flake8>=2.0 +mock>=1.0.1 +nose>=1.3.0 +PyHamcrest>=1.8.0 +# This needs to be kept in sync with submodule checkout in third_party/ycmd/third_party +future==0.15.2 diff --git a/vim/bundle/YouCompleteMe/python/ycm/__init__.py b/vim/bundle/YouCompleteMe/python/ycm/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/__init__.py diff --git a/vim/bundle/YouCompleteMe/python/ycm/base.py b/vim/bundle/YouCompleteMe/python/ycm/base.py new file mode 100644 index 0000000..4de4c0b --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/base.py @@ -0,0 +1,175 @@ +# Copyright (C) 2011, 2012 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from future.utils import iteritems +from ycm import vimsupport +from ycmd import user_options_store +from ycmd import request_wrap +from ycmd import identifier_utils + +YCM_VAR_PREFIX = 'ycm_' + + +def BuildServerConf(): + """Builds a dictionary mapping YCM Vim user options to values. Option names + don't have the 'ycm_' prefix.""" + # We only evaluate the keys of the vim globals and not the whole dictionary + # to avoid unicode issues. + # See https://github.com/Valloric/YouCompleteMe/pull/2151 for details. + keys = vimsupport.GetVimGlobalsKeys() + server_conf = {} + for key in keys: + if not key.startswith( YCM_VAR_PREFIX ): + continue + new_key = key[ len( YCM_VAR_PREFIX ): ] + new_value = vimsupport.VimExpressionToPythonType( 'g:' + key ) + server_conf[ new_key ] = new_value + + return server_conf + + +def LoadJsonDefaultsIntoVim(): + defaults = user_options_store.DefaultOptions() + for key, value in iteritems( defaults ): + new_key = 'g:ycm_' + key + if not vimsupport.VariableExists( new_key ): + vimsupport.SetVariableValue( new_key, value ) + + +def CompletionStartColumn(): + return ( request_wrap.CompletionStartColumn( + vimsupport.CurrentLineContents(), + vimsupport.CurrentColumn() + 1, + vimsupport.CurrentFiletypes()[ 0 ] ) - 1 ) + + +def CurrentIdentifierFinished(): + current_column = vimsupport.CurrentColumn() + previous_char_index = current_column - 1 + if previous_char_index < 0: + return True + line = vimsupport.CurrentLineContents() + filetype = vimsupport.CurrentFiletypes()[ 0 ] + regex = identifier_utils.IdentifierRegexForFiletype( filetype ) + + for match in regex.finditer( line ): + if match.end() == previous_char_index: + return True + # If the whole line is whitespace, that means the user probably finished an + # identifier on the previous line. + return line[ : current_column ].isspace() + + +def LastEnteredCharIsIdentifierChar(): + current_column = vimsupport.CurrentColumn() + if current_column - 1 < 0: + return False + line = vimsupport.CurrentLineContents() + filetype = vimsupport.CurrentFiletypes()[ 0 ] + return ( + identifier_utils.StartOfLongestIdentifierEndingAtIndex( + line, current_column, filetype ) != current_column ) + + +def AdjustCandidateInsertionText( candidates ): + """This function adjusts the candidate insertion text to take into account the + text that's currently in front of the cursor. + + For instance ('|' represents the cursor): + 1. Buffer state: 'foo.|bar' + 2. A completion candidate of 'zoobar' is shown and the user selects it. + 3. Buffer state: 'foo.zoobar|bar' instead of 'foo.zoo|bar' which is what the + user wanted. + + This function changes candidates to resolve that issue. + + It could be argued that the user actually wants the final buffer state to be + 'foo.zoobar|' (the cursor at the end), but that would be much more difficult + to implement and is probably not worth doing. + """ + + def NewCandidateInsertionText( to_insert, text_after_cursor ): + overlap_len = OverlapLength( to_insert, text_after_cursor ) + if overlap_len: + return to_insert[ :-overlap_len ] + return to_insert + + text_after_cursor = vimsupport.TextAfterCursor() + if not text_after_cursor: + return candidates + + new_candidates = [] + for candidate in candidates: + if isinstance( candidate, dict ): + new_candidate = candidate.copy() + + if 'abbr' not in new_candidate: + new_candidate[ 'abbr' ] = new_candidate[ 'word' ] + + new_candidate[ 'word' ] = NewCandidateInsertionText( + new_candidate[ 'word' ], + text_after_cursor ) + + new_candidates.append( new_candidate ) + + elif isinstance( candidate, str ) or isinstance( candidate, bytes ): + new_candidates.append( + { 'abbr': candidate, + 'word': NewCandidateInsertionText( candidate, text_after_cursor ) } ) + return new_candidates + + +def OverlapLength( left_string, right_string ): + """Returns the length of the overlap between two strings. + Example: "foo baro" and "baro zoo" -> 4 + """ + left_string_length = len( left_string ) + right_string_length = len( right_string ) + + if not left_string_length or not right_string_length: + return 0 + + # Truncate the longer string. + if left_string_length > right_string_length: + left_string = left_string[ -right_string_length: ] + elif left_string_length < right_string_length: + right_string = right_string[ :left_string_length ] + + if left_string == right_string: + return min( left_string_length, right_string_length ) + + # Start by looking for a single character match + # and increase length until no match is found. + best = 0 + length = 1 + while True: + pattern = left_string[ -length: ] + found = right_string.find( pattern ) + if found < 0: + return best + length += found + if left_string[ -length: ] == right_string[ :length ]: + best = length + length += 1 diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/__init__.py b/vim/bundle/YouCompleteMe/python/ycm/client/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/__init__.py diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/base_request.py b/vim/bundle/YouCompleteMe/python/ycm/client/base_request.py new file mode 100644 index 0000000..ffc3fac --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/base_request.py @@ -0,0 +1,244 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +import requests +import urllib.parse +import json +from future.utils import native +from base64 import b64decode, b64encode +from retries import retries +from requests_futures.sessions import FuturesSession +from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor +from ycm import vimsupport +from ycmd.utils import ToBytes +from ycmd.hmac_utils import CreateRequestHmac, CreateHmac, SecureBytesEqual +from ycmd.responses import ServerError, UnknownExtraConf + +_HEADERS = {'content-type': 'application/json'} +_EXECUTOR = UnsafeThreadPoolExecutor( max_workers = 30 ) +# Setting this to None seems to screw up the Requests/urllib3 libs. +_DEFAULT_TIMEOUT_SEC = 30 +_HMAC_HEADER = 'x-ycm-hmac' + + +class BaseRequest( object ): + + def __init__( self ): + pass + + + def Start( self ): + pass + + + def Done( self ): + return True + + + def Response( self ): + return {} + + # This method blocks + # |timeout| is num seconds to tolerate no response from server before giving + # up; see Requests docs for details (we just pass the param along). + @staticmethod + def GetDataFromHandler( handler, timeout = _DEFAULT_TIMEOUT_SEC ): + return JsonFromFuture( BaseRequest._TalkToHandlerAsync( '', + handler, + 'GET', + timeout ) ) + + + # This is the blocking version of the method. See below for async. + # |timeout| is num seconds to tolerate no response from server before giving + # up; see Requests docs for details (we just pass the param along). + @staticmethod + def PostDataToHandler( data, handler, timeout = _DEFAULT_TIMEOUT_SEC ): + return JsonFromFuture( BaseRequest.PostDataToHandlerAsync( data, + handler, + timeout ) ) + + + # This returns a future! Use JsonFromFuture to get the value. + # |timeout| is num seconds to tolerate no response from server before giving + # up; see Requests docs for details (we just pass the param along). + @staticmethod + def PostDataToHandlerAsync( data, handler, timeout = _DEFAULT_TIMEOUT_SEC ): + return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout ) + + + # This returns a future! Use JsonFromFuture to get the value. + # |method| is either 'POST' or 'GET'. + # |timeout| is num seconds to tolerate no response from server before giving + # up; see Requests docs for details (we just pass the param along). + @staticmethod + def _TalkToHandlerAsync( data, + handler, + method, + timeout = _DEFAULT_TIMEOUT_SEC ): + def SendRequest( data, handler, method, timeout ): + request_uri = _BuildUri( handler ) + if method == 'POST': + sent_data = _ToUtf8Json( data ) + return BaseRequest.session.post( + request_uri, + data = sent_data, + headers = BaseRequest._ExtraHeaders( method, + request_uri, + sent_data ), + timeout = timeout ) + if method == 'GET': + return BaseRequest.session.get( + request_uri, + headers = BaseRequest._ExtraHeaders( method, request_uri ), + timeout = timeout ) + + @retries( 5, delay = 0.5, backoff = 1.5 ) + def DelayedSendRequest( data, handler, method ): + request_uri = _BuildUri( handler ) + if method == 'POST': + sent_data = _ToUtf8Json( data ) + return requests.post( + request_uri, + data = sent_data, + headers = BaseRequest._ExtraHeaders( method, + request_uri, + sent_data ) ) + if method == 'GET': + return requests.get( + request_uri, + headers = BaseRequest._ExtraHeaders( method, request_uri ) ) + + if not _CheckServerIsHealthyWithCache(): + return _EXECUTOR.submit( DelayedSendRequest, data, handler, method ) + + return SendRequest( data, handler, method, timeout ) + + + @staticmethod + def _ExtraHeaders( method, request_uri, request_body = None ): + if not request_body: + request_body = bytes( b'' ) + headers = dict( _HEADERS ) + headers[ _HMAC_HEADER ] = b64encode( + CreateRequestHmac( ToBytes( method ), + ToBytes( urllib.parse.urlparse( request_uri ).path ), + request_body, + BaseRequest.hmac_secret ) ) + return headers + + session = FuturesSession( executor = _EXECUTOR ) + server_location = '' + hmac_secret = '' + + +def BuildRequestData( include_buffer_data = True ): + line, column = vimsupport.CurrentLineAndColumn() + filepath = vimsupport.GetCurrentBufferFilepath() + request_data = { + 'line_num': line + 1, + 'column_num': column + 1, + 'filepath': filepath + } + + if include_buffer_data: + request_data[ 'file_data' ] = vimsupport.GetUnsavedAndCurrentBufferData() + + return request_data + + +def JsonFromFuture( future ): + response = future.result() + _ValidateResponseObject( response ) + if response.status_code == requests.codes.server_error: + raise MakeServerException( response.json() ) + + # We let Requests handle the other status types, we only handle the 500 + # error code. + response.raise_for_status() + + if response.text: + return response.json() + return None + + +def HandleServerException( exception ): + serialized_exception = str( exception ) + + # We ignore the exception about the file already being parsed since it comes + # up often and isn't something that's actionable by the user. + if 'already being parsed' in serialized_exception: + return + vimsupport.PostMultiLineNotice( serialized_exception ) + + +def _ToUtf8Json( data ): + return ToBytes( json.dumps( data ) if data else None ) + + +def _ValidateResponseObject( response ): + our_hmac = CreateHmac( response.content, BaseRequest.hmac_secret ) + their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) ) + if not SecureBytesEqual( our_hmac, their_hmac ): + raise RuntimeError( 'Received invalid HMAC for response!' ) + return True + + +def _BuildUri( handler ): + return native( ToBytes( urllib.parse.urljoin( BaseRequest.server_location, + handler ) ) ) + + +SERVER_HEALTHY = False + + +def _CheckServerIsHealthyWithCache(): + global SERVER_HEALTHY + + def _ServerIsHealthy(): + request_uri = _BuildUri( 'healthy' ) + response = requests.get( request_uri, + headers = BaseRequest._ExtraHeaders( + 'GET', request_uri, bytes( b'' ) ) ) + _ValidateResponseObject( response ) + response.raise_for_status() + return response.json() + + if SERVER_HEALTHY: + return True + + try: + SERVER_HEALTHY = _ServerIsHealthy() + return SERVER_HEALTHY + except: + return False + + +def MakeServerException( data ): + if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__: + return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] ) + + return ServerError( '{0}: {1}'.format( data[ 'exception' ][ 'TYPE' ], + data[ 'message' ] ) ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/command_request.py b/vim/bundle/YouCompleteMe/python/ycm/client/command_request.py new file mode 100644 index 0000000..6c5bc66 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/command_request.py @@ -0,0 +1,153 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from requests.exceptions import ReadTimeout + +from ycmd.responses import ServerError +from ycm.client.base_request import ( BaseRequest, BuildRequestData, + HandleServerException ) +from ycm import vimsupport +from ycmd.utils import ToUnicode + + +def _EnsureBackwardsCompatibility( arguments ): + if arguments and arguments[ 0 ] == 'GoToDefinitionElseDeclaration': + arguments[ 0 ] = 'GoTo' + return arguments + + +class CommandRequest( BaseRequest ): + def __init__( self, arguments, completer_target = None ): + super( CommandRequest, self ).__init__() + self._arguments = _EnsureBackwardsCompatibility( arguments ) + self._completer_target = ( completer_target if completer_target + else 'filetype_default' ) + self._response = None + + + def Start( self ): + request_data = BuildRequestData() + request_data.update( { + 'completer_target': self._completer_target, + 'command_arguments': self._arguments + } ) + try: + self._response = self.PostDataToHandler( request_data, + 'run_completer_command' ) + except ( ServerError, ReadTimeout ) as e: + HandleServerException( e ) + + + def Response( self ): + return self._response + + + def RunPostCommandActionsIfNeeded( self ): + if not self.Done() or self._response is None: + return + + # If not a dictionary or a list, the response is necessarily a + # scalar: boolean, number, string, etc. In this case, we print + # it to the user. + if not isinstance( self._response, ( dict, list ) ): + return self._HandleBasicResponse() + + if 'fixits' in self._response: + return self._HandleFixitResponse() + + if 'message' in self._response: + return self._HandleMessageResponse() + + if 'detailed_info' in self._response: + return self._HandleDetailedInfoResponse() + + # The only other type of response we understand is GoTo, and that is the + # only one that we can't detect just by inspecting the response (it should + # either be a single location or a list) + return self._HandleGotoResponse() + + + def _HandleGotoResponse( self ): + if isinstance( self._response, list ): + vimsupport.SetQuickFixList( + [ _BuildQfListItem( x ) for x in self._response ], + focus = True, + autoclose = True ) + else: + vimsupport.JumpToLocation( self._response[ 'filepath' ], + self._response[ 'line_num' ], + self._response[ 'column_num' ] ) + + + def _HandleFixitResponse( self ): + if not len( self._response[ 'fixits' ] ): + vimsupport.EchoText( "No fixits found for current line" ) + else: + chunks = self._response[ 'fixits' ][ 0 ][ 'chunks' ] + try: + vimsupport.ReplaceChunks( chunks ) + except RuntimeError as e: + vimsupport.PostMultiLineNotice( str( e ) ) + + + def _HandleBasicResponse( self ): + vimsupport.EchoText( self._response ) + + + def _HandleMessageResponse( self ): + vimsupport.EchoText( self._response[ 'message' ] ) + + + def _HandleDetailedInfoResponse( self ): + vimsupport.WriteToPreviewWindow( self._response[ 'detailed_info' ] ) + + +def SendCommandRequest( arguments, completer ): + request = CommandRequest( arguments, completer ) + # This is a blocking call. + request.Start() + request.RunPostCommandActionsIfNeeded() + return request.Response() + + +def _BuildQfListItem( goto_data_item ): + qf_item = {} + if 'filepath' in goto_data_item: + qf_item[ 'filename' ] = ToUnicode( goto_data_item[ 'filepath' ] ) + if 'description' in goto_data_item: + qf_item[ 'text' ] = ToUnicode( goto_data_item[ 'description' ] ) + if 'line_num' in goto_data_item: + qf_item[ 'lnum' ] = goto_data_item[ 'line_num' ] + if 'column_num' in goto_data_item: + # ycmd returns columns 1-based, and QuickFix lists require "byte offsets". + # See :help getqflist and equivalent comment in + # vimsupport.ConvertDiagnosticsToQfList. + # + # When the Vim help says "byte index", it really means "1-based column + # number" (which is somewhat confusing). :help getqflist states "first + # column is 1". + qf_item[ 'col' ] = goto_data_item[ 'column_num' ] + + return qf_item diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/completer_available_request.py b/vim/bundle/YouCompleteMe/python/ycm/client/completer_available_request.py new file mode 100644 index 0000000..3a480ca --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/completer_available_request.py @@ -0,0 +1,58 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from requests.exceptions import ReadTimeout + +from ycm.client.base_request import ( BaseRequest, BuildRequestData, + HandleServerException ) +from ycmd.responses import ServerError + + +class CompleterAvailableRequest( BaseRequest ): + def __init__( self, filetypes ): + super( CompleterAvailableRequest, self ).__init__() + self.filetypes = filetypes + self._response = None + + + def Start( self ): + request_data = BuildRequestData() + request_data.update( { 'filetypes': self.filetypes } ) + try: + self._response = self.PostDataToHandler( request_data, + 'semantic_completion_available' ) + except ( ServerError, ReadTimeout ) as e: + HandleServerException( e ) + + + def Response( self ): + return self._response + + +def SendCompleterAvailableRequest( filetypes ): + request = CompleterAvailableRequest( filetypes ) + # This is a blocking call. + request.Start() + return request.Response() diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/completion_request.py b/vim/bundle/YouCompleteMe/python/ycm/client/completion_request.py new file mode 100644 index 0000000..bf16912 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/completion_request.py @@ -0,0 +1,109 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from requests.exceptions import ReadTimeout + +from ycmd.utils import ToUnicode +from ycm.client.base_request import ( BaseRequest, JsonFromFuture, + HandleServerException, + MakeServerException ) +from ycmd.responses import ServerError + +TIMEOUT_SECONDS = 0.5 + + +class CompletionRequest( BaseRequest ): + def __init__( self, request_data ): + super( CompletionRequest, self ).__init__() + self.request_data = request_data + + + def Start( self ): + self._response_future = self.PostDataToHandlerAsync( self.request_data, + 'completions', + TIMEOUT_SECONDS ) + + + def Done( self ): + return self._response_future.done() + + + def RawResponse( self ): + if not self._response_future: + return [] + try: + response = JsonFromFuture( self._response_future ) + + errors = response[ 'errors' ] if 'errors' in response else [] + for e in errors: + HandleServerException( MakeServerException( e ) ) + + return JsonFromFuture( self._response_future )[ 'completions' ] + except ( ServerError, ReadTimeout ) as e: + HandleServerException( e ) + return [] + + + def Response( self ): + return _ConvertCompletionDatasToVimDatas( self.RawResponse() ) + + +def ConvertCompletionDataToVimData( completion_data ): + # see :h complete-items for a description of the dictionary fields + vim_data = { + 'word' : '', + 'dup' : 1, + 'empty' : 1, + } + + if ( 'extra_data' in completion_data and + 'doc_string' in completion_data[ 'extra_data' ] ): + doc_string = completion_data[ 'extra_data' ][ 'doc_string' ] + else: + doc_string = "" + + if 'insertion_text' in completion_data: + vim_data[ 'word' ] = completion_data[ 'insertion_text' ] + if 'menu_text' in completion_data: + vim_data[ 'abbr' ] = completion_data[ 'menu_text' ] + if 'extra_menu_info' in completion_data: + vim_data[ 'menu' ] = completion_data[ 'extra_menu_info' ] + if 'kind' in completion_data: + kind = ToUnicode( completion_data[ 'kind' ] ) + if kind: + vim_data[ 'kind' ] = kind[ 0 ].lower() + if 'detailed_info' in completion_data: + vim_data[ 'info' ] = completion_data[ 'detailed_info' ] + if doc_string: + vim_data[ 'info' ] += '\n' + doc_string + elif doc_string: + vim_data[ 'info' ] = doc_string + + return vim_data + + +def _ConvertCompletionDatasToVimDatas( response_data ): + return [ ConvertCompletionDataToVimData( x ) + for x in response_data ] diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/event_notification.py b/vim/bundle/YouCompleteMe/python/ycm/client/event_notification.py new file mode 100644 index 0000000..b9a60d1 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/event_notification.py @@ -0,0 +1,89 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from requests.exceptions import ReadTimeout + +from ycm import vimsupport +from ycmd.responses import UnknownExtraConf, ServerError +from ycm.client.base_request import ( BaseRequest, BuildRequestData, + JsonFromFuture, HandleServerException ) + + +class EventNotification( BaseRequest ): + def __init__( self, event_name, extra_data = None ): + super( EventNotification, self ).__init__() + self._event_name = event_name + self._extra_data = extra_data + self._cached_response = None + + + def Start( self ): + request_data = BuildRequestData() + if self._extra_data: + request_data.update( self._extra_data ) + request_data[ 'event_name' ] = self._event_name + + self._response_future = self.PostDataToHandlerAsync( request_data, + 'event_notification' ) + + + def Done( self ): + return self._response_future.done() + + + def Response( self ): + if self._cached_response: + return self._cached_response + + if not self._response_future or self._event_name != 'FileReadyToParse': + return [] + + try: + try: + self._cached_response = JsonFromFuture( self._response_future ) + except UnknownExtraConf as e: + if vimsupport.Confirm( str( e ) ): + _LoadExtraConfFile( e.extra_conf_file ) + else: + _IgnoreExtraConfFile( e.extra_conf_file ) + except ( ServerError, ReadTimeout ) as e: + HandleServerException( e ) + + return self._cached_response if self._cached_response else [] + + +def SendEventNotificationAsync( event_name, extra_data = None ): + event = EventNotification( event_name, extra_data ) + event.Start() + + +def _LoadExtraConfFile( filepath ): + BaseRequest.PostDataToHandler( { 'filepath': filepath }, + 'load_extra_conf_file' ) + + +def _IgnoreExtraConfFile( filepath ): + BaseRequest.PostDataToHandler( { 'filepath': filepath }, + 'ignore_extra_conf_file' ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/omni_completion_request.py b/vim/bundle/YouCompleteMe/python/ycm/client/omni_completion_request.py new file mode 100644 index 0000000..2bcb291 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/omni_completion_request.py @@ -0,0 +1,71 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.client.completion_request import CompletionRequest + + +class OmniCompletionRequest( CompletionRequest ): + def __init__( self, omni_completer, request_data ): + super( OmniCompletionRequest, self ).__init__( request_data ) + self._omni_completer = omni_completer + + + def Start( self ): + self._results = self._omni_completer.ComputeCandidates( self.request_data ) + + + def Done( self ): + return True + + + def RawResponse( self ): + return _ConvertVimDatasToCompletionDatas( self._results ) + + + def Response( self ): + return self._results + + +def ConvertVimDataToCompletionData( vim_data ): + # see :h complete-items for a description of the dictionary fields + completion_data = {} + + if 'word' in vim_data: + completion_data[ 'insertion_text' ] = vim_data[ 'word' ] + if 'abbr' in vim_data: + completion_data[ 'menu_text' ] = vim_data[ 'abbr' ] + if 'menu' in vim_data: + completion_data[ 'extra_menu_info' ] = vim_data[ 'menu' ] + if 'kind' in vim_data: + completion_data[ 'kind' ] = [ vim_data[ 'kind' ] ] + if 'info' in vim_data: + completion_data[ 'detailed_info' ] = vim_data[ 'info' ] + + return completion_data + + +def _ConvertVimDatasToCompletionDatas( response_data ): + return [ ConvertVimDataToCompletionData( x ) + for x in response_data ] diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/tests/__init__.py b/vim/bundle/YouCompleteMe/python/ycm/client/tests/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/tests/__init__.py diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/tests/command_request_test.py b/vim/bundle/YouCompleteMe/python/ycm/client/tests/command_request_test.py new file mode 100644 index 0000000..dfc55e0 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/tests/command_request_test.py @@ -0,0 +1,283 @@ +# Copyright (C) 2016 YouCompleteMe Contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import ExtendedMock, MockVimModule +MockVimModule() + +import json +from mock import patch, call +from nose.tools import ok_ +from ycm.client.command_request import CommandRequest + + +class GoToResponse_QuickFix_test( object ): + """This class tests the generation of QuickFix lists for GoTo responses which + return multiple locations, such as the Python completer and JavaScript + completer. It mostly proves that we use 1-based indexing for the column + number.""" + + def setUp( self ): + self._request = CommandRequest( [ 'GoToTest' ] ) + + + def tearDown( self ): + self._request = None + + + def GoTo_EmptyList_test( self ): + self._CheckGoToList( [], [] ) + + + def GoTo_SingleItem_List_test( self ): + self._CheckGoToList( [ { + 'filepath': 'dummy_file', + 'line_num': 10, + 'column_num': 1, + 'description': 'this is some text', + } ], [ { + 'filename': 'dummy_file', + 'text': 'this is some text', + 'lnum': 10, + 'col': 1 + } ] ) + + + def GoTo_MultiItem_List_test( self ): + self._CheckGoToList( [ { + 'filepath': 'dummy_file', + 'line_num': 10, + 'column_num': 1, + 'description': 'this is some other text', + }, { + 'filepath': 'dummy_file2', + 'line_num': 1, + 'column_num': 21, + 'description': 'this is some text', + } ], [ { + 'filename': 'dummy_file', + 'text': 'this is some other text', + 'lnum': 10, + 'col': 1 + }, { + 'filename': 'dummy_file2', + 'text': 'this is some text', + 'lnum': 1, + 'col': 21 + } ] ) + + + @patch( 'ycm.vimsupport.VariableExists', return_value = True ) + @patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' ) + @patch( 'vim.command', new_callable = ExtendedMock ) + @patch( 'vim.eval', new_callable = ExtendedMock ) + def _CheckGoToList( self, + completer_response, + expected_qf_list, + vim_eval, + vim_command, + set_fitting_height, + variable_exists ): + self._request._response = completer_response + + self._request.RunPostCommandActionsIfNeeded() + + vim_eval.assert_has_exact_calls( [ + call( 'setqflist( {0} )'.format( json.dumps( expected_qf_list ) ) ) + ] ) + vim_command.assert_has_exact_calls( [ + call( 'botright copen' ), + call( 'au WinLeave <buffer> q' ), + call( 'doautocmd User YcmQuickFixOpened' ) + ] ) + set_fitting_height.assert_called_once_with() + + +class Response_Detection_test( object ): + + def BasicResponse_test( self ): + def _BasicResponseTest( command, response ): + with patch( 'vim.command' ) as vim_command: + request = CommandRequest( [ command ] ) + request._response = response + request.RunPostCommandActionsIfNeeded() + vim_command.assert_called_with( "echom '{0}'".format( response ) ) + + tests = [ + [ 'AnythingYouLike', True ], + [ 'GoToEvenWorks', 10 ], + [ 'FixItWorks', 'String!' ], + [ 'and8434fd andy garbag!', 10.3 ], + ] + + for test in tests: + yield _BasicResponseTest, test[ 0 ], test[ 1 ] + + + def FixIt_Response_Empty_test( self ): + # Ensures we recognise and handle fixit responses which indicate that there + # are no fixits available + def EmptyFixItTest( command ): + with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks: + with patch( 'ycm.vimsupport.EchoText' ) as echo_text: + request = CommandRequest( [ command ] ) + request._response = { + 'fixits': [] + } + request.RunPostCommandActionsIfNeeded() + + echo_text.assert_called_with( 'No fixits found for current line' ) + replace_chunks.assert_not_called() + + for test in [ 'FixIt', 'Refactor', 'GoToHell', 'any_old_garbade!!!21' ]: + yield EmptyFixItTest, test + + + def FixIt_Response_test( self ): + # Ensures we recognise and handle fixit responses with some dummy chunk data + def FixItTest( command, response, chunks ): + with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks: + with patch( 'ycm.vimsupport.EchoText' ) as echo_text: + request = CommandRequest( [ command ] ) + request._response = response + request.RunPostCommandActionsIfNeeded() + + replace_chunks.assert_called_with( chunks ) + echo_text.assert_not_called() + + basic_fixit = { + 'fixits': [ { + 'chunks': [ { + 'dummy chunk contents': True + } ] + } ] + } + basic_fixit_chunks = basic_fixit[ 'fixits' ][ 0 ][ 'chunks' ] + + multi_fixit = { + 'fixits': [ { + 'chunks': [ { + 'dummy chunk contents': True + } ] + }, { + 'additional fixits are ignored currently': True + } ] + } + multi_fixit_first_chunks = multi_fixit[ 'fixits' ][ 0 ][ 'chunks' ] + + tests = [ + [ 'AnythingYouLike', basic_fixit, basic_fixit_chunks ], + [ 'GoToEvenWorks', basic_fixit, basic_fixit_chunks ], + [ 'FixItWorks', basic_fixit, basic_fixit_chunks ], + [ 'and8434fd andy garbag!', basic_fixit, basic_fixit_chunks ], + [ 'additional fixits ignored', multi_fixit, multi_fixit_first_chunks ], + ] + + for test in tests: + yield FixItTest, test[ 0 ], test[ 1 ], test[ 2 ] + + + def Message_Response_test( self ): + # Ensures we correctly recognise and handle responses with a message to show + # to the user + + def MessageTest( command, message ): + with patch( 'ycm.vimsupport.EchoText' ) as echo_text: + request = CommandRequest( [ command ] ) + request._response = { 'message': message } + request.RunPostCommandActionsIfNeeded() + echo_text.assert_called_with( message ) + + tests = [ + [ '___________', 'This is a message' ], + [ '', 'this is also a message' ], + [ 'GetType', 'std::string' ], + ] + + for test in tests: + yield MessageTest, test[ 0 ], test[ 1 ] + + + def Detailed_Info_test( self ): + # Ensures we correctly detect and handle detailed_info responses which are + # used to display information in the preview window + + def DetailedInfoTest( command, info ): + with patch( 'ycm.vimsupport.WriteToPreviewWindow' ) as write_to_preview: + request = CommandRequest( [ command ] ) + request._response = { 'detailed_info': info } + request.RunPostCommandActionsIfNeeded() + write_to_preview.assert_called_with( info ) + + tests = [ + [ '___________', 'This is a message' ], + [ '', 'this is also a message' ], + [ 'GetDoc', 'std::string\netc\netc' ], + ] + + for test in tests: + yield DetailedInfoTest, test[ 0 ], test[ 1 ] + + + def GoTo_Single_test( self ): + # Ensures we handle any unknown type of response as a GoTo response + + def GoToTest( command, response ): + with patch( 'ycm.vimsupport.JumpToLocation' ) as jump_to_location: + request = CommandRequest( [ command ] ) + request._response = response + request.RunPostCommandActionsIfNeeded() + jump_to_location.assert_called_with( + response[ 'filepath' ], + response[ 'line_num' ], + response[ 'column_num' ] ) + + def GoToListTest( command, response ): + # Note: the detail of these called are tested by + # GoToResponse_QuickFix_test, so here we just check that the right call is + # made + with patch( 'ycm.vimsupport.SetQuickFixList' ) as set_qf_list: + request = CommandRequest( [ command ] ) + request._response = response + request.RunPostCommandActionsIfNeeded() + ok_( set_qf_list.called ) + + basic_goto = { + 'filepath': 'test', + 'line_num': 10, + 'column_num': 100, + } + + tests = [ + [ GoToTest, 'AnythingYouLike', basic_goto ], + [ GoToTest, 'GoTo', basic_goto ], + [ GoToTest, 'FindAThing', basic_goto ], + [ GoToTest, 'FixItGoto', basic_goto ], + [ GoToListTest, 'AnythingYouLike', [ basic_goto ] ], + [ GoToListTest, 'GoTo', [] ], + [ GoToListTest, 'FixItGoto', [ basic_goto, basic_goto ] ], + ] + + for test in tests: + yield test[ 0 ], test[ 1 ], test[ 2 ] diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/tests/completion_request_test.py b/vim/bundle/YouCompleteMe/python/ycm/client/tests/completion_request_test.py new file mode 100644 index 0000000..acf0252 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/tests/completion_request_test.py @@ -0,0 +1,186 @@ +# Copyright (C) 2015 YouCompleteMe Contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from nose.tools import eq_ +from ycm.test_utils import MockVimModule +vim_mock = MockVimModule() + +from .. import completion_request + + +class ConvertCompletionResponseToVimDatas_test( object ): + """ This class tests the + completion_request._ConvertCompletionResponseToVimDatas method """ + + def _Check( self, completion_data, expected_vim_data ): + vim_data = completion_request.ConvertCompletionDataToVimData( + completion_data ) + + try: + eq_( expected_vim_data, vim_data ) + except: + print( "Expected:\n'{0}'\nwhen parsing:\n'{1}'\nBut found:\n'{2}'".format( + expected_vim_data, + completion_data, + vim_data ) ) + raise + + + def All_Fields_test( self ): + self._Check( { + 'insertion_text': 'INSERTION TEXT', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'detailed_info': 'DETAILED INFO', + 'extra_data': { + 'doc_string': 'DOC STRING', + }, + }, { + 'word' : 'INSERTION TEXT', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DETAILED INFO\nDOC STRING', + 'dup' : 1, + 'empty': 1, + } ) + + + def Just_Detailed_Info_test( self ): + self._Check( { + 'insertion_text': 'INSERTION TEXT', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'detailed_info': 'DETAILED INFO', + }, { + 'word' : 'INSERTION TEXT', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DETAILED INFO', + 'dup' : 1, + 'empty': 1, + } ) + + + def Just_Doc_String_test( self ): + self._Check( { + 'insertion_text': 'INSERTION TEXT', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'extra_data': { + 'doc_string': 'DOC STRING', + }, + }, { + 'word' : 'INSERTION TEXT', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DOC STRING', + 'dup' : 1, + 'empty': 1, + } ) + + + def Extra_Info_No_Doc_String_test( self ): + self._Check( { + 'insertion_text': 'INSERTION TEXT', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'extra_data': { + }, + }, { + 'word' : 'INSERTION TEXT', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'dup' : 1, + 'empty': 1, + } ) + + + def Extra_Info_No_Doc_String_With_Detailed_Info_test( self ): + self._Check( { + 'insertion_text': 'INSERTION TEXT', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'detailed_info': 'DETAILED INFO', + 'extra_data': { + }, + }, { + 'word' : 'INSERTION TEXT', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DETAILED INFO', + 'dup' : 1, + 'empty': 1, + } ) + + + def Empty_Insertion_Text_test( self ): + self._Check( { + 'insertion_text': '', + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'detailed_info': 'DETAILED INFO', + 'extra_data': { + 'doc_string': 'DOC STRING', + }, + }, { + 'word' : '', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DETAILED INFO\nDOC STRING', + 'dup' : 1, + 'empty': 1, + } ) + + + def No_Insertion_Text_test( self ): + self._Check( { + 'menu_text': 'MENU TEXT', + 'extra_menu_info': 'EXTRA MENU INFO', + 'kind': 'K', + 'detailed_info': 'DETAILED INFO', + 'extra_data': { + 'doc_string': 'DOC STRING', + }, + }, { + 'word' : '', + 'abbr' : 'MENU TEXT', + 'menu' : 'EXTRA MENU INFO', + 'kind' : 'k', + 'info' : 'DETAILED INFO\nDOC STRING', + 'dup' : 1, + 'empty': 1, + } ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/tests/omni_completion_request_tests.py b/vim/bundle/YouCompleteMe/python/ycm/client/tests/omni_completion_request_tests.py new file mode 100644 index 0000000..02fb2e9 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/tests/omni_completion_request_tests.py @@ -0,0 +1,81 @@ +# Copyright (C) 2016 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from mock import MagicMock +from nose.tools import eq_ +from hamcrest import assert_that, has_entries + +from ycm.client.omni_completion_request import OmniCompletionRequest + + +def BuildOmnicompletionRequest( results ): + omni_completer = MagicMock() + omni_completer.ComputeCandidates = MagicMock( return_value = results ) + + request = OmniCompletionRequest( omni_completer, None ) + request.Start() + + return request + + +def Done_AlwaysTrue_test(): + request = BuildOmnicompletionRequest( [] ) + + eq_( request.Done(), True ) + + +def Response_FromOmniCompleter_test(): + results = [ { "word": "test" } ] + request = BuildOmnicompletionRequest( results ) + + eq_( request.Response(), results ) + + +def RawResponse_ConvertedFromOmniCompleter_test(): + vim_results = [ + { "word": "WORD", "abbr": "ABBR", "menu": "MENU", + "kind": "KIND", "info": "INFO" }, + { "word": "WORD2", "abbr": "ABBR2", "menu": "MENU2", + "kind": "KIND2", "info": "INFO" }, + { "word": "WORD", "abbr": "ABBR", }, + { }, + ] + expected_results = [ + has_entries( { "insertion_text": "WORD", "menu_text": "ABBR", + "extra_menu_info": "MENU", "kind": [ "KIND" ], + "detailed_info": "INFO" } ), + has_entries( { "insertion_text": "WORD2", "menu_text": "ABBR2", + "extra_menu_info": "MENU2", "kind": [ "KIND2" ], + "detailed_info": "INFO" } ), + has_entries( { "insertion_text": "WORD", "menu_text": "ABBR", } ), + has_entries( { } ), + ] + request = BuildOmnicompletionRequest( vim_results ) + + results = request.RawResponse() + + eq_( len( results ), len( expected_results ) ) + for result, expected_result in zip( results, expected_results ): + assert_that( result, expected_result ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/client/ycmd_keepalive.py b/vim/bundle/YouCompleteMe/python/ycm/client/ycmd_keepalive.py new file mode 100644 index 0000000..fca59f4 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/client/ycmd_keepalive.py @@ -0,0 +1,54 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +import time +from threading import Thread +from ycm.client.base_request import BaseRequest + + +# This class can be used to keep the ycmd server alive for the duration of the +# life of the client. By default, ycmd shuts down if it doesn't see a request in +# a while. +class YcmdKeepalive( object ): + def __init__( self, ping_interval_seconds = 60 * 10 ): + self._keepalive_thread = Thread( target = self._ThreadMain ) + self._keepalive_thread.daemon = True + self._ping_interval_seconds = ping_interval_seconds + + + def Start( self ): + self._keepalive_thread.start() + + + def _ThreadMain( self ): + while True: + time.sleep( self._ping_interval_seconds ) + + # We don't care if there's an intermittent problem in contacting the + # server; it's fine to just skip this ping. + try: + BaseRequest.GetDataFromHandler( 'healthy' ) + except: + pass diff --git a/vim/bundle/YouCompleteMe/python/ycm/diagnostic_interface.py b/vim/bundle/YouCompleteMe/python/ycm/diagnostic_interface.py new file mode 100644 index 0000000..7f7de53 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/diagnostic_interface.py @@ -0,0 +1,265 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from future.utils import itervalues, iteritems +from collections import defaultdict, namedtuple +from ycm import vimsupport +import vim + + +class DiagnosticInterface( object ): + def __init__( self, user_options ): + self._user_options = user_options + # Line and column numbers are 1-based + self._buffer_number_to_line_to_diags = defaultdict( + lambda: defaultdict( list ) ) + self._next_sign_id = 1 + self._previous_line_number = -1 + self._diag_message_needs_clearing = False + self._placed_signs = [] + + + def OnCursorMoved( self ): + line, _ = vimsupport.CurrentLineAndColumn() + line += 1 # Convert to 1-based + if line != self._previous_line_number: + self._previous_line_number = line + + if self._user_options[ 'echo_current_diagnostic' ]: + self._EchoDiagnosticForLine( line ) + + + def GetErrorCount( self ): + return len( self._FilterDiagnostics( _DiagnosticIsError ) ) + + + def GetWarningCount( self ): + return len( self._FilterDiagnostics( _DiagnosticIsWarning ) ) + + + def PopulateLocationList( self, diags ): + vimsupport.SetLocationList( + vimsupport.ConvertDiagnosticsToQfList( diags ) ) + + + def UpdateWithNewDiagnostics( self, diags ): + normalized_diags = [ _NormalizeDiagnostic( x ) for x in diags ] + self._buffer_number_to_line_to_diags = _ConvertDiagListToDict( + normalized_diags ) + + if self._user_options[ 'enable_diagnostic_signs' ]: + self._placed_signs, self._next_sign_id = _UpdateSigns( + self._placed_signs, + self._buffer_number_to_line_to_diags, + self._next_sign_id ) + + if self._user_options[ 'enable_diagnostic_highlighting' ]: + _UpdateSquiggles( self._buffer_number_to_line_to_diags ) + + if self._user_options[ 'always_populate_location_list' ]: + self.PopulateLocationList( normalized_diags ) + + def _EchoDiagnosticForLine( self, line_num ): + buffer_num = vim.current.buffer.number + diags = self._buffer_number_to_line_to_diags[ buffer_num ][ line_num ] + if not diags: + if self._diag_message_needs_clearing: + # Clear any previous diag echo + vimsupport.EchoText( '', False ) + self._diag_message_needs_clearing = False + return + + text = diags[ 0 ][ 'text' ] + if diags[ 0 ].get( 'fixit_available', False ): + text += ' (FixIt)' + + vimsupport.EchoTextVimWidth( text ) + self._diag_message_needs_clearing = True + + + def _FilterDiagnostics( self, predicate ): + matched_diags = [] + line_to_diags = self._buffer_number_to_line_to_diags[ + vim.current.buffer.number ] + + for diags in itervalues( line_to_diags ): + matched_diags.extend( list( filter( predicate, diags ) ) ) + return matched_diags + + +def _UpdateSquiggles( buffer_number_to_line_to_diags ): + vimsupport.ClearYcmSyntaxMatches() + line_to_diags = buffer_number_to_line_to_diags[ vim.current.buffer.number ] + + for diags in itervalues( line_to_diags ): + for diag in diags: + location_extent = diag[ 'location_extent' ] + is_error = _DiagnosticIsError( diag ) + + if location_extent[ 'start' ][ 'line_num' ] < 0: + location = diag[ 'location' ] + vimsupport.AddDiagnosticSyntaxMatch( + location[ 'line_num' ], + location[ 'column_num' ] ) + else: + vimsupport.AddDiagnosticSyntaxMatch( + location_extent[ 'start' ][ 'line_num' ], + location_extent[ 'start' ][ 'column_num' ], + location_extent[ 'end' ][ 'line_num' ], + location_extent[ 'end' ][ 'column_num' ], + is_error = is_error ) + + for diag_range in diag[ 'ranges' ]: + vimsupport.AddDiagnosticSyntaxMatch( + diag_range[ 'start' ][ 'line_num' ], + diag_range[ 'start' ][ 'column_num' ], + diag_range[ 'end' ][ 'line_num' ], + diag_range[ 'end' ][ 'column_num' ], + is_error = is_error ) + + +def _UpdateSigns( placed_signs, buffer_number_to_line_to_diags, next_sign_id ): + new_signs, kept_signs, next_sign_id = _GetKeptAndNewSigns( + placed_signs, buffer_number_to_line_to_diags, next_sign_id + ) + # Dummy sign used to prevent "flickering" in Vim when last mark gets + # deleted from buffer. Dummy sign prevents Vim to collapsing the sign column + # in that case. + # There's also a vim bug which causes the whole window to redraw in some + # conditions (vim redraw logic is very complex). But, somehow, if we place a + # dummy sign before placing other "real" signs, it will not redraw the + # buffer (patch to vim pending). + dummy_sign_needed = not kept_signs and new_signs + + if dummy_sign_needed: + vimsupport.PlaceDummySign( next_sign_id + 1, + vim.current.buffer.number, + new_signs[ 0 ].line ) + + # We place only those signs that haven't been placed yet. + new_placed_signs = _PlaceNewSigns( kept_signs, new_signs ) + + # We use incremental placement, so signs that already placed on the correct + # lines will not be deleted and placed again, which should improve performance + # in case of many diags. Signs which don't exist in the current diag should be + # deleted. + _UnplaceObsoleteSigns( kept_signs, placed_signs ) + + if dummy_sign_needed: + vimsupport.UnPlaceDummySign( next_sign_id + 1, vim.current.buffer.number ) + + return new_placed_signs, next_sign_id + + +def _GetKeptAndNewSigns( placed_signs, buffer_number_to_line_to_diags, + next_sign_id ): + new_signs = [] + kept_signs = [] + for buffer_number, line_to_diags in iteritems( + buffer_number_to_line_to_diags ): + if not vimsupport.BufferIsVisible( buffer_number ): + continue + + for line, diags in iteritems( line_to_diags ): + for diag in diags: + sign = _DiagSignPlacement( next_sign_id, + line, + buffer_number, + _DiagnosticIsError( diag ) ) + if sign not in placed_signs: + new_signs += [ sign ] + next_sign_id += 1 + else: + # We use .index here because `sign` contains a new id, but + # we need the sign with the old id to unplace it later on. + # We won't be placing the new sign. + kept_signs += [ placed_signs[ placed_signs.index( sign ) ] ] + return new_signs, kept_signs, next_sign_id + + + +def _PlaceNewSigns( kept_signs, new_signs ): + placed_signs = kept_signs[:] + for sign in new_signs: + # Do not set two signs on the same line, it will screw up storing sign + # locations. + if sign in placed_signs: + continue + vimsupport.PlaceSign( sign.id, sign.line, sign.buffer, sign.is_error ) + placed_signs.append(sign) + return placed_signs + + +def _UnplaceObsoleteSigns( kept_signs, placed_signs ): + for sign in placed_signs: + if sign not in kept_signs: + vimsupport.UnplaceSignInBuffer( sign.buffer, sign.id ) + + +def _ConvertDiagListToDict( diag_list ): + buffer_to_line_to_diags = defaultdict( lambda: defaultdict( list ) ) + for diag in diag_list: + location = diag[ 'location' ] + buffer_number = vimsupport.GetBufferNumberForFilename( + location[ 'filepath' ] ) + line_number = location[ 'line_num' ] + buffer_to_line_to_diags[ buffer_number ][ line_number ].append( diag ) + + for line_to_diags in itervalues( buffer_to_line_to_diags ): + for diags in itervalues( line_to_diags ): + # We also want errors to be listed before warnings so that errors aren't + # hidden by the warnings; Vim won't place a sign oven an existing one. + diags.sort( key = lambda diag: ( diag[ 'location' ][ 'column_num' ], + diag[ 'kind' ] ) ) + return buffer_to_line_to_diags + + +def _DiagnosticIsError( diag ): + return diag[ 'kind' ] == 'ERROR' + + +def _DiagnosticIsWarning( diag ): + return diag[ 'kind' ] == 'WARNING' + + +def _NormalizeDiagnostic( diag ): + def ClampToOne( value ): + return value if value > 0 else 1 + + location = diag[ 'location' ] + location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] ) + location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] ) + return diag + + +class _DiagSignPlacement( + namedtuple( "_DiagSignPlacement", + [ 'id', 'line', 'buffer', 'is_error' ] ) ): + # We want two signs that have different ids but the same location to compare + # equal. ID doesn't matter. + def __eq__( self, other ): + return ( self.line == other.line and + self.buffer == other.buffer and + self.is_error == other.is_error ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/omni_completer.py b/vim/bundle/YouCompleteMe/python/ycm/omni_completer.py new file mode 100644 index 0000000..df3a51c --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/omni_completer.py @@ -0,0 +1,123 @@ +# Copyright (C) 2011, 2012, 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +import vim +from ycm import vimsupport +from ycmd import utils +from ycmd.responses import ServerError +from ycmd.completers.completer import Completer +from ycm.client.base_request import BaseRequest, HandleServerException + +OMNIFUNC_RETURNED_BAD_VALUE = 'Omnifunc returned bad value to YCM!' +OMNIFUNC_NOT_LIST = ( 'Omnifunc did not return a list or a dict with a "words" ' + ' list when expected.' ) + + +class OmniCompleter( Completer ): + def __init__( self, user_options ): + super( OmniCompleter, self ).__init__( user_options ) + self._omnifunc = None + + + def SupportedFiletypes( self ): + return [] + + + def ShouldUseCache( self ): + return bool( self.user_options[ 'cache_omnifunc' ] ) + + + def ShouldUseNow( self, request_data ): + if not self._omnifunc: + return False + + if self.ShouldUseCache(): + return super( OmniCompleter, self ).ShouldUseNow( request_data ) + return self.ShouldUseNowInner( request_data ) + + + def ShouldUseNowInner( self, request_data ): + if not self._omnifunc: + return False + return super( OmniCompleter, self ).ShouldUseNowInner( request_data ) + + + def ComputeCandidates( self, request_data ): + if self.ShouldUseCache(): + return super( OmniCompleter, self ).ComputeCandidates( request_data ) + else: + if self.ShouldUseNowInner( request_data ): + return self.ComputeCandidatesInner( request_data ) + return [] + + + def ComputeCandidatesInner( self, request_data ): + if not self._omnifunc: + return [] + + try: + return_value = int( vim.eval( self._omnifunc + '(1,"")' ) ) + if return_value < 0: + # FIXME: Technically, if the return is -1 we should raise an error + return [] + + omnifunc_call = [ self._omnifunc, + "(0,'", + vimsupport.EscapeForVim( request_data[ 'query' ] ), + "')" ] + + items = vim.eval( ''.join( omnifunc_call ) ) + + if isinstance( items, dict ) and 'words' in items: + items = items[ 'words' ] + + if not hasattr( items, '__iter__' ): + raise TypeError( OMNIFUNC_NOT_LIST ) + + return list( filter( bool, items ) ) + + except ( TypeError, ValueError, vim.error ) as error: + vimsupport.PostVimMessage( + OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) ) + return [] + + + def OnFileReadyToParse( self, request_data ): + self._omnifunc = utils.ToUnicode( vim.eval( '&omnifunc' ) ) + + + def FilterAndSortCandidatesInner( self, candidates, sort_property, query ): + request_data = { + 'candidates': candidates, + 'sort_property': sort_property, + 'query': query + } + + try: + return BaseRequest.PostDataToHandler( request_data, + 'filter_and_sort_candidates' ) + except ServerError as e: + HandleServerException( e ) + return candidates diff --git a/vim/bundle/YouCompleteMe/python/ycm/paths.py b/vim/bundle/YouCompleteMe/python/ycm/paths.py new file mode 100644 index 0000000..17edafa --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/paths.py @@ -0,0 +1,135 @@ +# Copyright (C) 2015 YouCompleteMe contributors. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +import os +import sys +import vim +import functools +import re + +# Can't import these from setup.py because it makes nosetests go crazy. +DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) ) +DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party', + 'ycmd' ) +WIN_PYTHON_PATH = os.path.join( sys.exec_prefix, 'python.exe' ) +PYTHON_BINARY_REGEX = re.compile( + r'python((2(\.[67])?)|(3(\.[3-9])?))?(.exe)?$' ) + + +def Memoize( obj ): + cache = obj.cache = {} + + @functools.wraps( obj ) + def memoizer( *args, **kwargs ): + key = str( args ) + str( kwargs ) + if key not in cache: + cache[ key ] = obj( *args, **kwargs ) + return cache[ key ] + return memoizer + + +@Memoize +def PathToPythonInterpreter(): + from ycmd import utils + + python_interpreter = vim.eval( 'g:ycm_server_python_interpreter' ) + + if python_interpreter: + if IsPythonVersionCorrect( python_interpreter ): + return python_interpreter + + raise RuntimeError( "Path in 'g:ycm_server_python_interpreter' option " + "does not point to a valid Python 2.6+ or 3.3+." ) + + python_interpreter = _PathToPythonUsedDuringBuild() + if IsPythonVersionCorrect( python_interpreter ): + return python_interpreter + + # On UNIX platforms, we use sys.executable as the Python interpreter path. + # We cannot use sys.executable on Windows because for unknown reasons, it + # returns the Vim executable. Instead, we use sys.exec_prefix to deduce the + # interpreter path. + python_interpreter = ( WIN_PYTHON_PATH if utils.OnWindows() else + sys.executable ) + + if IsPythonVersionCorrect( python_interpreter ): + return python_interpreter + + # As a last resort, we search python in the PATH. We prefer Python 2 over 3 + # for the sake of backwards compatibility with ycm_extra_conf.py files out + # there; few people wrote theirs to work on py3. + # So we check 'python2' before 'python' because on some distributions (Arch + # Linux for example), python refers to python3. + python_interpreter = utils.PathToFirstExistingExecutable( [ 'python2', + 'python', + 'python3' ] ) + + if IsPythonVersionCorrect( python_interpreter ): + return python_interpreter + + raise RuntimeError( "Cannot find Python 2.6+ or 3.3+. You can set its path " + "using the 'g:ycm_server_python_interpreter' " + "option." ) + + +def _PathToPythonUsedDuringBuild(): + from ycmd import utils + + try: + filepath = os.path.join( DIR_OF_YCMD, 'PYTHON_USED_DURING_BUILDING' ) + return utils.ReadFile( filepath ).strip() + # We need to check for IOError for Python2 and OSError for Python3 + except ( IOError, OSError ): + return None + + +def EndsWithPython( path ): + """Check if given path ends with a python 2.6+ or 3.3+ name.""" + return path and PYTHON_BINARY_REGEX.search( path ) is not None + + +def IsPythonVersionCorrect( path ): + """Check if given path is the Python interpreter version 2.6+ or 3.3+.""" + from ycmd import utils + + if not EndsWithPython( path ): + return False + + command = [ path, + '-c', + "import sys;" + "major, minor = sys.version_info[ :2 ];" + "good_python = ( major == 2 and minor >= 6 ) " + "or ( major == 3 and minor >= 3 ) or major > 3;" + # If this looks weird, remember that: + # int( True ) == 1 + # int( False ) == 0 + "sys.exit( not good_python )" ] + + return utils.SafePopen( command ).wait() == 0 + + +def PathToServerScript(): + return os.path.join( DIR_OF_YCMD, 'ycmd' ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/setup.py b/vim/bundle/YouCompleteMe/python/ycm/setup.py new file mode 100644 index 0000000..7fc9132 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/setup.py @@ -0,0 +1,53 @@ +# Copyright (C) 2016 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +# No imports from `future` because when this is loaded, sys.path hasn't been set +# up yet! + +import sys +import os + +# Can't import these from paths.py because that uses `future` imports +DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) ) +DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party', + 'ycmd' ) + + +def SetUpSystemPaths(): + sys.path.insert( 0, os.path.join( DIR_OF_YCMD ) ) + + from ycmd import server_utils as su + su.AddNearestThirdPartyFoldersToSysPath( DIR_OF_CURRENT_SCRIPT ) + # We need to import ycmd's third_party folders as well since we import and + # use ycmd code in the client. + su.AddNearestThirdPartyFoldersToSysPath( su.__file__ ) + + +def SetUpYCM(): + from ycm import base + from ycmd import user_options_store + from ycm.youcompleteme import YouCompleteMe + + base.LoadJsonDefaultsIntoVim() + + user_options_store.SetAll( base.BuildServerConf() ) + + return YouCompleteMe( user_options_store.GetAll() ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/syntax_parse.py b/vim/bundle/YouCompleteMe/python/ycm/syntax_parse.py new file mode 100644 index 0000000..e6ea1d5 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/syntax_parse.py @@ -0,0 +1,224 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from future.utils import itervalues +import re +import vim +from ycm import vimsupport + +SYNTAX_GROUP_REGEX = re.compile( + r"""^ + (?P<group_name>\w+) + \s+ + xxx + \s+ + (?P<content>.+?) + $""", + re.VERBOSE ) + +KEYWORD_REGEX = re.compile( r'^[\w,]+$' ) + +SYNTAX_ARGUMENT_REGEX = re.compile( + r"^\w+=.*$" ) + +SYNTAX_ARGUMENTS = set([ + 'cchar', + 'conceal', + 'contained', + 'containedin', + 'nextgroup', + 'skipempty', + 'skipnl', + 'skipwhite', + 'transparent', + 'concealends', + 'contains', + 'display', + 'extend', + 'fold', + 'oneline', + 'keepend', + 'excludenl', +]) + +# We want to parse lines starting with these args +ALLOWED_SYNTAX_ARGUMENTS = set([ + 'contained', +]) + +# These are the parent groups from which we want to extract keywords +ROOT_GROUPS = set([ + 'Statement', + 'Boolean', + 'Include', + 'Type', + 'Identifier', +]) + + +class SyntaxGroup( object ): + def __init__( self, name, lines = None ): + self.name = name + self.lines = lines if lines else [] + self.children = [] + + +def SyntaxKeywordsForCurrentBuffer(): + vim.command( 'redir => b:ycm_syntax' ) + vim.command( 'silent! syntax list' ) + vim.command( 'redir END' ) + syntax_output = vimsupport.VimExpressionToPythonType( 'b:ycm_syntax' ) + return _KeywordsFromSyntaxListOutput( syntax_output ) + + +def _KeywordsFromSyntaxListOutput( syntax_output ): + group_name_to_group = _SyntaxGroupsFromOutput( syntax_output ) + _ConnectGroupChildren( group_name_to_group ) + + groups_with_keywords = [] + for root_group in ROOT_GROUPS: + groups_with_keywords.extend( + _GetAllDescendentats( group_name_to_group[ root_group ] ) ) + + keywords = [] + for group in groups_with_keywords: + keywords.extend( _ExtractKeywordsFromGroup( group ) ) + return set( keywords ) + + +def _SyntaxGroupsFromOutput( syntax_output ): + group_name_to_group = _CreateInitialGroupMap() + lines = syntax_output.split( '\n' ) + looking_for_group = True + + current_group = None + for line in lines: + if not line: + continue + + match = SYNTAX_GROUP_REGEX.search( line ) + if match: + if looking_for_group: + looking_for_group = False + else: + group_name_to_group[ current_group.name ] = current_group + + current_group = SyntaxGroup( match.group( 'group_name' ), + [ match.group( 'content').strip() ] ) + else: + if looking_for_group: + continue + + if line[ 0 ] == ' ' or line[ 0 ] == '\t': + current_group.lines.append( line.strip() ) + + if current_group: + group_name_to_group[ current_group.name ] = current_group + return group_name_to_group + + +def _CreateInitialGroupMap(): + def AddToGroupMap( name, parent ): + new_group = SyntaxGroup( name ) + group_name_to_group[ name ] = new_group + parent.children.append( new_group ) + + statement_group = SyntaxGroup( 'Statement' ) + type_group = SyntaxGroup( 'Type' ) + identifier_group = SyntaxGroup( 'Identifier' ) + + # See `:h group-name` for details on how the initial group hierarchy is built + group_name_to_group = { + 'Statement': statement_group, + 'Type': type_group, + 'Boolean': SyntaxGroup( 'Boolean' ), + 'Include': SyntaxGroup( 'Include' ), + 'Identifier': identifier_group, + } + + AddToGroupMap( 'Conditional', statement_group ) + AddToGroupMap( 'Repeat' , statement_group ) + AddToGroupMap( 'Label' , statement_group ) + AddToGroupMap( 'Operator' , statement_group ) + AddToGroupMap( 'Keyword' , statement_group ) + AddToGroupMap( 'Exception' , statement_group ) + + AddToGroupMap( 'StorageClass', type_group ) + AddToGroupMap( 'Structure' , type_group ) + AddToGroupMap( 'Typedef' , type_group ) + + AddToGroupMap( 'Function', identifier_group ) + + return group_name_to_group + + +def _ConnectGroupChildren( group_name_to_group ): + def GetParentNames( group ): + links_to = 'links to ' + parent_names = [] + for line in group.lines: + if line.startswith( links_to ): + parent_names.append( line[ len( links_to ): ] ) + return parent_names + + for group in itervalues( group_name_to_group ): + parent_names = GetParentNames( group ) + + for parent_name in parent_names: + try: + parent_group = group_name_to_group[ parent_name ] + except KeyError: + continue + parent_group.children.append( group ) + + +def _GetAllDescendentats( root_group ): + descendants = [] + for child in root_group.children: + descendants.append( child ) + descendants.extend( _GetAllDescendentats( child ) ) + return descendants + + +def _ExtractKeywordsFromGroup( group ): + keywords = [] + for line in group.lines: + if line.startswith( 'links to ' ): + continue + + words = line.split() + if not words or ( words[ 0 ] in SYNTAX_ARGUMENTS and + words[ 0 ] not in ALLOWED_SYNTAX_ARGUMENTS ): + continue + + for word in words: + if ( word not in SYNTAX_ARGUMENTS and + not SYNTAX_ARGUMENT_REGEX.match( word ) and + KEYWORD_REGEX.match( word ) ): + + if word.endswith( ',' ): + word = word[ :-1 ] + keywords.append( word ) + return keywords diff --git a/vim/bundle/YouCompleteMe/python/ycm/test_utils.py b/vim/bundle/YouCompleteMe/python/ycm/test_utils.py new file mode 100644 index 0000000..3a16255 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/test_utils.py @@ -0,0 +1,201 @@ +# Copyright (C) 2011, 2012 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from mock import MagicMock +from hamcrest import assert_that, equal_to +import re +import sys +import nose +import functools + +from ycmd.utils import ToUnicode + + +BUFNR_REGEX = re.compile( r"^bufnr\('(.+)', ([0-9]+)\)$" ) +BUFWINNR_REGEX = re.compile( r"^bufwinnr\(([0-9]+)\)$" ) +BWIPEOUT_REGEX = re.compile( r"^(?:silent! )bwipeout!? ([0-9]+)$" ) + +# One-and only instance of mocked Vim object. The first 'import vim' that is +# executed binds the vim module to the instance of MagicMock that is created, +# and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively +# update them. The result is that while running the tests, we must assign only +# one instance of MagicMock to sys.modules[ 'vim' ] and always return it. +# +# More explanation is available: +# https://github.com/Valloric/YouCompleteMe/pull/1694 +VIM_MOCK = MagicMock() + +# The default options which are only relevant to the client, not the server and +# thus are not part of default_options.json, but are required for a working +# YouCompleteMe or OmniCompleter object. +DEFAULT_CLIENT_OPTIONS = { + 'server_log_level': 'info', + 'extra_conf_vim_data': [], + 'show_diagnostics_ui': 1, + 'enable_diagnostic_signs': 1, + 'enable_diagnostic_highlighting': 0, + 'always_populate_location_list': 0, +} + + +def MockGetBufferNumber( buffer_filename ): + for buffer in VIM_MOCK.buffers: + if buffer[ 'filename' ] == buffer_filename: + return buffer[ 'number' ] + return -1 + + +def MockGetBufferWindowNumber( buffer_number ): + for buffer in VIM_MOCK.buffers: + if buffer[ 'number' ] == buffer_number and 'window' in buffer: + return buffer[ 'window' ] + return -1 + + +def MockVimEval( value ): + if value == "g:ycm_min_num_of_chars_for_completion": + return 0 + if value == "g:ycm_server_python_interpreter": + return '' + if value == "tempname()": + return '_TEMP_FILE_' + if value == "&previewheight": + # Default value from Vim + return 12 + + match = BUFNR_REGEX.search( value ) + if match: + return MockGetBufferNumber( match.group( 1 ) ) + + match = BUFWINNR_REGEX.search( value ) + if match: + return MockGetBufferWindowNumber( int( match.group( 1 ) ) ) + + raise ValueError( 'Unexpected evaluation: ' + value ) + + +def MockWipeoutBuffer( buffer_number ): + buffers = VIM_MOCK.buffers + + for index, buffer in enumerate( buffers ): + if buffer[ 'number' ] == buffer_number: + return buffers.pop( index ) + + +def MockVimCommand( command ): + match = BWIPEOUT_REGEX.search( command ) + if match: + return MockWipeoutBuffer( int( match.group( 1 ) ) ) + + raise RuntimeError( 'Unexpected command: ' + command ) + + +def MockVimModule(): + """The 'vim' module is something that is only present when running inside the + Vim Python interpreter, so we replace it with a MagicMock for tests. If you + need to add additional mocks to vim module functions, then use 'patch' from + mock module, to ensure that the state of the vim mock is returned before the + next test. That is: + + from ycm.test_utils import MockVimModule + from mock import patch + + # Do this once + MockVimModule() + + @patch( 'vim.eval', return_value='test' ) + @patch( 'vim.command', side_effect=ValueError ) + def test( vim_command, vim_eval ): + # use vim.command via vim_command, e.g.: + vim_command.assert_has_calls( ... ) + + Failure to use this approach may lead to unexpected failures in other + tests.""" + + VIM_MOCK.buffers = {} + VIM_MOCK.eval = MagicMock( side_effect = MockVimEval ) + sys.modules[ 'vim' ] = VIM_MOCK + + return VIM_MOCK + + +class ExtendedMock( MagicMock ): + """An extension to the MagicMock class which adds the ability to check that a + callable is called with a precise set of calls in a precise order. + + Example Usage: + from ycm.test_utils import ExtendedMock + @patch( 'test.testing', new_callable = ExtendedMock, ... ) + def my_test( test_testing ): + ... + """ + + def assert_has_exact_calls( self, calls, any_order = False ): + self.assert_has_calls( calls, any_order ) + assert_that( self.call_count, equal_to( len( calls ) ) ) + + +def ExpectedFailure( reason, *exception_matchers ): + """Defines a decorator to be attached to tests. This decorator + marks the test as being known to fail, e.g. where documenting or exercising + known incorrect behaviour. + + The parameters are: + - |reason| a textual description of the reason for the known issue. This + is used for the skip reason + - |exception_matchers| additional arguments are hamcrest matchers to apply + to the exception thrown. If the matchers don't match, then the + test is marked as error, with the original exception. + + If the test fails (for the correct reason), then it is marked as skipped. + If it fails for any other reason, it is marked as failed. + If the test passes, then it is also marked as failed.""" + def decorator( test ): + @functools.wraps( test ) + def Wrapper( *args, **kwargs ): + try: + test( *args, **kwargs ) + except Exception as test_exception: + # Ensure that we failed for the right reason + test_exception_message = ToUnicode( test_exception ) + try: + for matcher in exception_matchers: + assert_that( test_exception_message, matcher ) + except AssertionError: + # Failed for the wrong reason! + import traceback + print( 'Test failed for the wrong reason: ' + traceback.format_exc() ) + # Real failure reason is the *original* exception, we're only trapping + # and ignoring the exception that is expected. + raise test_exception + + # Failed for the right reason + raise nose.SkipTest( reason ) + else: + raise AssertionError( 'Test was expected to fail: {0}'.format( + reason ) ) + return Wrapper + + return decorator diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/__init__.py b/vim/bundle/YouCompleteMe/python/ycm/tests/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/__init__.py diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/base_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/base_test.py new file mode 100644 index 0000000..9d1ba27 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/base_test.py @@ -0,0 +1,270 @@ +# coding: utf-8 +# +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +import contextlib +from nose.tools import eq_, ok_ +from mock import patch + +from ycm.test_utils import MockVimModule +vim_mock = MockVimModule() +from ycm import base + + +@contextlib.contextmanager +def MockCurrentFiletypes( filetypes = [''] ): + with patch( 'ycm.vimsupport.CurrentFiletypes', return_value = filetypes ): + yield + + +@contextlib.contextmanager +def MockCurrentColumnAndLineContents( column, line_contents ): + with patch( 'ycm.vimsupport.CurrentColumn', return_value = column ): + with patch( 'ycm.vimsupport.CurrentLineContents', + return_value = line_contents ): + yield + + +@contextlib.contextmanager +def MockTextAfterCursor( text ): + with patch( 'ycm.vimsupport.TextAfterCursor', return_value = text ): + yield + + +def AdjustCandidateInsertionText_Basic_test(): + with MockTextAfterCursor( 'bar' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) + + +def AdjustCandidateInsertionText_ParenInTextAfterCursor_test(): + with MockTextAfterCursor( 'bar(zoo' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) + + +def AdjustCandidateInsertionText_PlusInTextAfterCursor_test(): + with MockTextAfterCursor( 'bar+zoo' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) + + +def AdjustCandidateInsertionText_WhitespaceInTextAfterCursor_test(): + with MockTextAfterCursor( 'bar zoo' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) + + +def AdjustCandidateInsertionText_MoreThanWordMatchingAfterCursor_test(): + with MockTextAfterCursor( 'bar.h' ): + eq_( [ { 'abbr': 'foobar.h', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar.h' ] ) ) + + with MockTextAfterCursor( 'bar(zoo' ): + eq_( [ { 'abbr': 'foobar(zoo', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( [ 'foobar(zoo' ] ) ) + + +def AdjustCandidateInsertionText_NotSuffix_test(): + with MockTextAfterCursor( 'bar' ): + eq_( [ { 'abbr': 'foofoo', 'word': 'foofoo' } ], + base.AdjustCandidateInsertionText( [ 'foofoo' ] ) ) + + +def AdjustCandidateInsertionText_NothingAfterCursor_test(): + with MockTextAfterCursor( '' ): + eq_( [ 'foofoo', + 'zobar' ], + base.AdjustCandidateInsertionText( [ 'foofoo', + 'zobar' ] ) ) + + +def AdjustCandidateInsertionText_MultipleStrings_test(): + with MockTextAfterCursor( 'bar' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' }, + { 'abbr': 'zobar', 'word': 'zo' }, + { 'abbr': 'qbar', 'word': 'q' }, + { 'abbr': 'bar', 'word': '' }, ], + base.AdjustCandidateInsertionText( [ 'foobar', + 'zobar', + 'qbar', + 'bar' ] ) ) + + +def AdjustCandidateInsertionText_DictInput_test(): + with MockTextAfterCursor( 'bar' ): + eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( + [ { 'word': 'foobar' } ] ) ) + + +def AdjustCandidateInsertionText_DontTouchAbbr_test(): + with MockTextAfterCursor( 'bar' ): + eq_( [ { 'abbr': '1234', 'word': 'foo' } ], + base.AdjustCandidateInsertionText( + [ { 'abbr': '1234', 'word': 'foobar' } ] ) ) + + +def OverlapLength_Basic_test(): + eq_( 3, base.OverlapLength( 'foo bar', 'bar zoo' ) ) + eq_( 3, base.OverlapLength( 'foobar', 'barzoo' ) ) + + +def OverlapLength_BasicWithUnicode_test(): + eq_( 3, base.OverlapLength( u'bar fäö', u'fäö bar' ) ) + eq_( 3, base.OverlapLength( u'zoofäö', u'fäözoo' ) ) + + +def OverlapLength_OneCharOverlap_test(): + eq_( 1, base.OverlapLength( 'foo b', 'b zoo' ) ) + + +def OverlapLength_SameStrings_test(): + eq_( 6, base.OverlapLength( 'foobar', 'foobar' ) ) + + +def OverlapLength_Substring_test(): + eq_( 6, base.OverlapLength( 'foobar', 'foobarzoo' ) ) + eq_( 6, base.OverlapLength( 'zoofoobar', 'foobar' ) ) + + +def OverlapLength_LongestOverlap_test(): + eq_( 7, base.OverlapLength( 'bar foo foo', 'foo foo bar' ) ) + + +def OverlapLength_EmptyInput_test(): + eq_( 0, base.OverlapLength( '', 'goobar' ) ) + eq_( 0, base.OverlapLength( 'foobar', '' ) ) + eq_( 0, base.OverlapLength( '', '' ) ) + + +def OverlapLength_NoOverlap_test(): + eq_( 0, base.OverlapLength( 'foobar', 'goobar' ) ) + eq_( 0, base.OverlapLength( 'foobar', '(^($@#$#@' ) ) + eq_( 0, base.OverlapLength( 'foo bar zoo', 'foo zoo bar' ) ) + + +def LastEnteredCharIsIdentifierChar_Basic_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 3, 'abc' ): + ok_( base.LastEnteredCharIsIdentifierChar() ) + + with MockCurrentColumnAndLineContents( 2, 'abc' ): + ok_( base.LastEnteredCharIsIdentifierChar() ) + + with MockCurrentColumnAndLineContents( 1, 'abc' ): + ok_( base.LastEnteredCharIsIdentifierChar() ) + + +def LastEnteredCharIsIdentifierChar_FiletypeHtml_test(): + with MockCurrentFiletypes( ['html'] ): + with MockCurrentColumnAndLineContents( 3, 'ab-' ): + ok_( base.LastEnteredCharIsIdentifierChar() ) + + +def LastEnteredCharIsIdentifierChar_ColumnIsZero_test(): + with MockCurrentColumnAndLineContents( 0, 'abc' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + +def LastEnteredCharIsIdentifierChar_LineEmpty_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 3, '' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + with MockCurrentColumnAndLineContents( 0, '' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + +def LastEnteredCharIsIdentifierChar_NotIdentChar_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 3, 'ab;' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + with MockCurrentColumnAndLineContents( 1, ';' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + with MockCurrentColumnAndLineContents( 3, 'ab-' ): + ok_( not base.LastEnteredCharIsIdentifierChar() ) + + +def CurrentIdentifierFinished_Basic_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 3, 'ab;' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 2, 'ab;' ): + ok_( not base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 1, 'ab;' ): + ok_( not base.CurrentIdentifierFinished() ) + + +def CurrentIdentifierFinished_NothingBeforeColumn_test(): + with MockCurrentColumnAndLineContents( 0, 'ab;' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 0, '' ): + ok_( base.CurrentIdentifierFinished() ) + + +def CurrentIdentifierFinished_InvalidColumn_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 5, '' ): + ok_( not base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 5, 'abc' ): + ok_( not base.CurrentIdentifierFinished() ) + + +def CurrentIdentifierFinished_InMiddleOfLine_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 4, 'bar.zoo' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 4, 'bar(zoo' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ): + ok_( base.CurrentIdentifierFinished() ) + + +def CurrentIdentifierFinished_Html_test(): + with MockCurrentFiletypes( ['html'] ): + with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ): + ok_( not base.CurrentIdentifierFinished() ) + + +def CurrentIdentifierFinished_WhitespaceOnly_test(): + with MockCurrentFiletypes(): + with MockCurrentColumnAndLineContents( 1, '\n' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 3, '\n ' ): + ok_( base.CurrentIdentifierFinished() ) + + with MockCurrentColumnAndLineContents( 3, '\t\t\t\t' ): + ok_( base.CurrentIdentifierFinished() ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/event_notification_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/event_notification_test.py new file mode 100644 index 0000000..c065a1e --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/event_notification_test.py @@ -0,0 +1,406 @@ +# Copyright (C) 2015 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import MockVimModule, ExtendedMock, DEFAULT_CLIENT_OPTIONS +MockVimModule() + +import contextlib +import os + +from ycm.youcompleteme import YouCompleteMe +from ycmd import user_options_store +from ycmd.responses import ( BuildDiagnosticData, Diagnostic, Location, Range, + UnknownExtraConf, ServerError ) + +from mock import call, MagicMock, patch +from nose.tools import eq_, ok_ + + +def PostVimMessage_Call( message ): + """Return a mock.call object for a call to vimsupport.PostVimMesasge with the + supplied message""" + return call( 'redraw | echohl WarningMsg | echom \'' + + message + + '\' | echohl None' ) + + +def PostMultiLineNotice_Call( message ): + """Return a mock.call object for a call to vimsupport.PostMultiLineNotice with + the supplied message""" + return call( 'echohl WarningMsg | echo \'' + + message + + '\' | echohl None' ) + + +def PresentDialog_Confirm_Call( message ): + """Return a mock.call object for a call to vimsupport.PresentDialog, as called + why vimsupport.Confirm with the supplied confirmation message""" + return call( message, [ 'Ok', 'Cancel' ] ) + + +def PlaceSign_Call( sign_id, line_num, buffer_num, is_error ): + sign_name = 'YcmError' if is_error else 'YcmWarning' + return call( 'sign place {0} line={1} name={2} buffer={3}' + .format( sign_id, line_num, sign_name, buffer_num ) ) + + +def UnplaceSign_Call( sign_id, buffer_num ): + return call( 'try | exec "sign unplace {0} buffer={1}" |' + ' catch /E158/ | endtry'.format( sign_id, buffer_num ) ) + + +@contextlib.contextmanager +def MockArbitraryBuffer( filetype, native_available = True ): + """Used via the with statement, set up mocked versions of the vim module such + that a single buffer is open with an arbitrary name and arbirary contents. Its + filetype is set to the supplied filetype""" + with patch( 'vim.current' ) as vim_current: + def VimEval( value ): + """Local mock of the vim.eval() function, used to ensure we get the + correct behvaiour""" + + if value == '&omnifunc': + # The omnicompleter is not required here + return '' + + if value == 'getbufvar(0, "&mod")': + # Ensure that we actually send the even to the server + return 1 + + if value == 'getbufvar(0, "&ft")' or value == '&filetype': + return filetype + + if value.startswith( 'bufnr(' ): + return 0 + + if value.startswith( 'bufwinnr(' ): + return 0 + + raise ValueError( 'Unexpected evaluation' ) + + # Arbitrary, but valid, cursor position + vim_current.window.cursor = ( 1, 2 ) + + # Arbitrary, but valid, single buffer open + current_buffer = MagicMock() + current_buffer.number = 0 + current_buffer.filename = os.path.realpath( 'TEST_BUFFER' ) + current_buffer.name = 'TEST_BUFFER' + current_buffer.window = 0 + + # The rest just mock up the Vim module so that our single arbitrary buffer + # makes sense to vimsupport module. + with patch( 'vim.buffers', [ current_buffer ] ): + with patch( 'vim.current.buffer', current_buffer ): + with patch( 'vim.eval', side_effect=VimEval ): + yield + + +@contextlib.contextmanager +def MockEventNotification( response_method, native_filetype_completer = True ): + """Mock out the EventNotification client request object, replacing the + Response handler's JsonFromFuture with the supplied |response_method|. + Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype + method to return the supplied |native_filetype_completer| parameter, rather + than querying the server""" + + # We don't want the event to actually be sent to the server, just have it + # return success + with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync', + return_value = MagicMock( return_value=True ) ): + + # We set up a fake a Response (as called by EventNotification.Response) + # which calls the supplied callback method. Generally this callback just + # raises an apropriate exception, otherwise it would have to return a mock + # future object. + # + # Note: JsonFromFuture is actually part of ycm.client.base_request, but we + # must patch where an object is looked up, not where it is defined. + # See https://docs.python.org/dev/library/unittest.mock.html#where-to-patch + # for details. + with patch( 'ycm.client.event_notification.JsonFromFuture', + side_effect = response_method ): + + # Filetype available information comes from the server, so rather than + # relying on that request, we mock out the check. The caller decides if + # filetype completion is available + with patch( + 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype', + return_value = native_filetype_completer ): + + yield + + +class EventNotification_test( object ): + + def setUp( self ): + options = dict( user_options_store.DefaultOptions() ) + options.update( DEFAULT_CLIENT_OPTIONS ) + user_options_store.SetAll( options ) + + self.server_state = YouCompleteMe( user_options_store.GetAll() ) + pass + + + def tearDown( self ): + if self.server_state: + self.server_state.OnVimLeave() + + + @patch( 'vim.command', new_callable = ExtendedMock ) + def FileReadyToParse_NonDiagnostic_Error_test( self, vim_command ): + # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest + # in combination with YouCompleteMe.OnFileReadyToParse when the completer + # raises an exception handling FileReadyToParse event notification + ERROR_TEXT = 'Some completer response text' + + def ErrorResponse( *args ): + raise ServerError( ERROR_TEXT ) + + with MockArbitraryBuffer( 'javascript' ): + with MockEventNotification( ErrorResponse ): + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + + # The first call raises a warning + vim_command.assert_has_exact_calls( [ + PostMultiLineNotice_Call( ERROR_TEXT ), + ] ) + + # Subsequent calls don't re-raise the warning + self.server_state.HandleFileParseRequest() + vim_command.assert_has_exact_calls( [ + PostMultiLineNotice_Call( ERROR_TEXT ), + ] ) + + # But it does if a subsequent event raises again + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + vim_command.assert_has_exact_calls( [ + PostMultiLineNotice_Call( ERROR_TEXT ), + PostMultiLineNotice_Call( ERROR_TEXT ), + ] ) + + + @patch( 'vim.command' ) + def FileReadyToParse_NonDiagnostic_Error_NonNative_test( self, vim_command ): + with MockArbitraryBuffer( 'javascript' ): + with MockEventNotification( None, False ): + self.server_state.OnFileReadyToParse() + self.server_state.HandleFileParseRequest() + vim_command.assert_not_called() + + + @patch( 'ycm.client.event_notification._LoadExtraConfFile', + new_callable = ExtendedMock ) + @patch( 'ycm.client.event_notification._IgnoreExtraConfFile', + new_callable = ExtendedMock ) + def FileReadyToParse_NonDiagnostic_ConfirmExtraConf_test( + self, + ignore_extra_conf, + load_extra_conf, + *args ): + + # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest + # in combination with YouCompleteMe.OnFileReadyToParse when the completer + # raises the (special) UnknownExtraConf exception + + FILE_NAME = 'a_file' + MESSAGE = ( 'Found ' + FILE_NAME + '. Load? \n\n(Question can be ' + 'turned off with options, see YCM docs)' ) + + def UnknownExtraConfResponse( *args ): + raise UnknownExtraConf( FILE_NAME ) + + with MockArbitraryBuffer( 'javascript' ): + with MockEventNotification( UnknownExtraConfResponse ): + + # When the user accepts the extra conf, we load it + with patch( 'ycm.vimsupport.PresentDialog', + return_value = 0, + new_callable = ExtendedMock ) as present_dialog: + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ), + ] ) + load_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + ] ) + + # Subsequent calls don't re-raise the warning + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ) + ] ) + load_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + ] ) + + # But it does if a subsequent event raises again + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ), + PresentDialog_Confirm_Call( MESSAGE ), + ] ) + load_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + call( FILE_NAME ), + ] ) + + # When the user rejects the extra conf, we reject it + with patch( 'ycm.vimsupport.PresentDialog', + return_value = 1, + new_callable = ExtendedMock ) as present_dialog: + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ), + ] ) + ignore_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + ] ) + + # Subsequent calls don't re-raise the warning + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ) + ] ) + ignore_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + ] ) + + # But it does if a subsequent event raises again + self.server_state.OnFileReadyToParse() + assert self.server_state.FileParseRequestReady() + self.server_state.HandleFileParseRequest() + + present_dialog.assert_has_exact_calls( [ + PresentDialog_Confirm_Call( MESSAGE ), + PresentDialog_Confirm_Call( MESSAGE ), + ] ) + ignore_extra_conf.assert_has_exact_calls( [ + call( FILE_NAME ), + call( FILE_NAME ), + ] ) + + + def FileReadyToParse_Diagnostic_Error_Native_test( self ): + self._Check_FileReadyToParse_Diagnostic_Error() + self._Check_FileReadyToParse_Diagnostic_Warning() + self._Check_FileReadyToParse_Diagnostic_Clean() + + + @patch( 'vim.command' ) + def _Check_FileReadyToParse_Diagnostic_Error( self, vim_command ): + # Tests Vim sign placement and error/warning count python API + # when one error is returned. + def DiagnosticResponse( *args ): + start = Location( 1, 2, 'TEST_BUFFER' ) + end = Location( 1, 4, 'TEST_BUFFER' ) + extent = Range( start, end ) + diagnostic = Diagnostic( [], start, extent, 'expected ;', 'ERROR' ) + return [ BuildDiagnosticData( diagnostic ) ] + + with MockArbitraryBuffer( 'cpp' ): + with MockEventNotification( DiagnosticResponse ): + self.server_state.OnFileReadyToParse() + ok_( self.server_state.FileParseRequestReady() ) + self.server_state.HandleFileParseRequest() + vim_command.assert_has_calls( [ + PlaceSign_Call( 1, 1, 0, True ) + ] ) + eq_( self.server_state.GetErrorCount(), 1 ) + eq_( self.server_state.GetWarningCount(), 0 ) + + # Consequent calls to HandleFileParseRequest shouldn't mess with + # existing diagnostics, when there is no new parse request. + vim_command.reset_mock() + ok_( not self.server_state.FileParseRequestReady() ) + self.server_state.HandleFileParseRequest() + vim_command.assert_not_called() + eq_( self.server_state.GetErrorCount(), 1 ) + eq_( self.server_state.GetWarningCount(), 0 ) + + + @patch( 'vim.command' ) + def _Check_FileReadyToParse_Diagnostic_Warning( self, vim_command ): + # Tests Vim sign placement/unplacement and error/warning count python API + # when one warning is returned. + # Should be called after _Check_FileReadyToParse_Diagnostic_Error + def DiagnosticResponse( *args ): + start = Location( 2, 2, 'TEST_BUFFER' ) + end = Location( 2, 4, 'TEST_BUFFER' ) + extent = Range( start, end ) + diagnostic = Diagnostic( [], start, extent, 'cast', 'WARNING' ) + return [ BuildDiagnosticData( diagnostic ) ] + + with MockArbitraryBuffer( 'cpp' ): + with MockEventNotification( DiagnosticResponse ): + self.server_state.OnFileReadyToParse() + ok_( self.server_state.FileParseRequestReady() ) + self.server_state.HandleFileParseRequest() + vim_command.assert_has_calls( [ + PlaceSign_Call( 2, 2, 0, False ), + UnplaceSign_Call( 1, 0 ) + ] ) + eq_( self.server_state.GetErrorCount(), 0 ) + eq_( self.server_state.GetWarningCount(), 1 ) + + # Consequent calls to HandleFileParseRequest shouldn't mess with + # existing diagnostics, when there is no new parse request. + vim_command.reset_mock() + ok_( not self.server_state.FileParseRequestReady() ) + self.server_state.HandleFileParseRequest() + vim_command.assert_not_called() + eq_( self.server_state.GetErrorCount(), 0 ) + eq_( self.server_state.GetWarningCount(), 1 ) + + + @patch( 'vim.command' ) + def _Check_FileReadyToParse_Diagnostic_Clean( self, vim_command ): + # Tests Vim sign unplacement and error/warning count python API + # when there are no errors/warnings left. + # Should be called after _Check_FileReadyToParse_Diagnostic_Warning + with MockArbitraryBuffer( 'cpp' ): + with MockEventNotification( MagicMock( return_value = [] ) ): + self.server_state.OnFileReadyToParse() + self.server_state.HandleFileParseRequest() + vim_command.assert_has_calls( [ + UnplaceSign_Call( 2, 0 ) + ] ) + eq_( self.server_state.GetErrorCount(), 0 ) + eq_( self.server_state.GetWarningCount(), 0 ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/omni_completer_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/omni_completer_test.py new file mode 100644 index 0000000..e590847 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/omni_completer_test.py @@ -0,0 +1,758 @@ +# encoding: utf-8 +# +# Copyright (C) 2016 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa +from future.utils import PY2 + +from mock import patch, call +from nose.tools import eq_ +from hamcrest import contains_string + +from ycm.test_utils import MockVimModule, ExtendedMock +MockVimModule() + +from ycm.test_utils import DEFAULT_CLIENT_OPTIONS, ExpectedFailure +from ycm.omni_completer import OmniCompleter +from ycm.youcompleteme import YouCompleteMe + +from ycmd import user_options_store +from ycmd.utils import ToBytes +from ycmd.request_wrap import RequestWrap + + +def ToBytesOnPY2( data ): + # To test the omnifunc, etc. returning strings, which can be of different + # types depending on python version, we use ToBytes on PY2 and just the native + # str on python3. This roughly matches what happens between py2 and py3 + # versions within Vim + if PY2: + return ToBytes( data ) + + return data + + +def BuildRequest( line_num, column_num, contents ): + # Note: it would be nice to use ycmd.test_utils.BuildRequest directly here, + # but we can't import ycmd.test_utils because that in turn imports ycm_core, + # which would cause our "ycm_core not imported" test to fail. + return { + 'line_num': line_num, + 'column_num': column_num, + 'filepath': '/test', + 'file_data': { + '/test': { + 'contents': contents, + 'filetypes': [ 'java' ] # We need a filetype with a trigger, so we just + # use java + } + } + } + + +def BuildRequestWrap( line_num, column_num, contents ): + return RequestWrap( BuildRequest( line_num, column_num, contents ) ) + + +def MakeUserOptions( custom_options = {} ): + options = dict( user_options_store.DefaultOptions() ) + options.update( DEFAULT_CLIENT_OPTIONS ) + options.update( custom_options ) + return options + + +class OmniCompleter_test( object ): + + def setUp( self ): + # We need a server instance for FilterAndSortCandidates + self._server_state = YouCompleteMe( MakeUserOptions() ) + + + def tearDown( self ): + self._server_state.OnVimLeave() + + + def OmniCompleter_GetCompletions_Cache_List_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.' + request_data = BuildRequestWrap( line_num = 1, + column_num = 6, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'cdef' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'')" ), + ] ) + + eq_( results, omnifunc_result ) + + + def OmniCompleter_GetCompletions_Cache_ListFilter_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.t' + request_data = BuildRequestWrap( line_num = 1, + column_num = 7, + contents = contents ) + + eq_( request_data[ 'query' ], 't' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'cdef' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'t')" ), + ] ) + + eq_( results, [] ) + + + def OmniCompleter_GetCompletions_NoCache_List_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = 'test.' + request_data = BuildRequestWrap( line_num = 1, + column_num = 6, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'cdef' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'')" ), + ] ) + + eq_( results, omnifunc_result ) + + + def OmniCompleter_GetCompletions_NoCache_ListFilter_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = 'test.t' + request_data = BuildRequestWrap( line_num = 1, + column_num = 7, + contents = contents ) + + eq_( request_data[ 'query' ], 't' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'cdef' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'t')" ), + ] ) + + # actual result is that the results are not filtered, as we expect the + # omniufunc or vim itself to do this filtering + eq_( results, omnifunc_result ) + + + @ExpectedFailure( 'We ignore the result of the call to findstart and use our ' + 'own interpretation of where the identifier should be', + contains_string( "test_omnifunc(0,'t')" ) ) + def OmniCompleter_GetCompletsions_UseFindStart_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.t' + request_data = BuildRequestWrap( line_num = 1, + column_num = 7, + contents = contents ) + + eq_( request_data[ 'query' ], 't' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'cdef' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 1, omnifunc_result ] ) as vim_eval: + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + + # Fails here: actual result is that the findstart result (1) is ignored + # and we use the 't' query as we normally would on the server side + call( "test_omnifunc(0,'test.t')" ), + ] ) + + eq_( results, omnifunc_result ) + + + def OmniCompleter_GetCompletions_Cache_Object_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.t' + request_data = BuildRequestWrap( line_num = 1, + column_num = 7, + contents = contents ) + + eq_( request_data[ 'query' ], 't' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = { + 'words': [ + ToBytesOnPY2( 'a' ), + ToBytesOnPY2( 'b' ), + ToBytesOnPY2( 'CDtEF' ) + ] + } + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'t')" ), + ] ) + + eq_( results, [ ToBytesOnPY2( 'CDtEF' ) ] ) + + + def OmniCompleter_GetCompletions_Cache_ObjectList_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.tt' + request_data = BuildRequestWrap( line_num = 1, + column_num = 8, + contents = contents ) + + eq_( request_data[ 'query' ], 'tt' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ + { + 'word': ToBytesOnPY2( 'a' ), + 'abbr': ToBytesOnPY2( 'ABBR'), + 'menu': ToBytesOnPY2( 'MENU' ), + 'info': ToBytesOnPY2( 'INFO' ), + 'kind': ToBytesOnPY2( 'K' ) + }, + { + 'word': ToBytesOnPY2( 'test' ), + 'abbr': ToBytesOnPY2( 'ABBRTEST'), + 'menu': ToBytesOnPY2( 'MENUTEST' ), + 'info': ToBytesOnPY2( 'INFOTEST' ), + 'kind': ToBytesOnPY2( 'T' ) + } + ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'tt')" ), + ] ) + + eq_( results, [ omnifunc_result[ 1 ] ] ) + + + def OmniCompleter_GetCompletions_NoCache_ObjectList_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = 'test.tt' + request_data = BuildRequestWrap( line_num = 1, + column_num = 8, + contents = contents ) + + eq_( request_data[ 'query' ], 'tt' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ + { + 'word': ToBytesOnPY2( 'a' ), + 'abbr': ToBytesOnPY2( 'ABBR'), + 'menu': ToBytesOnPY2( 'MENU' ), + 'info': ToBytesOnPY2( 'INFO' ), + 'kind': ToBytesOnPY2( 'K' ) + }, + { + 'word': ToBytesOnPY2( 'test' ), + 'abbr': ToBytesOnPY2( 'ABBRTEST'), + 'menu': ToBytesOnPY2( 'MENUTEST' ), + 'info': ToBytesOnPY2( 'INFOTEST' ), + 'kind': ToBytesOnPY2( 'T' ) + } + ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'tt')" ), + ] ) + + # We don't filter the result - we expect the omnifunc to do that + # based on the query we supplied (Note: that means no fuzzy matching!) + eq_( results, omnifunc_result ) + + + def OmniCompleter_GetCompletions_Cache_ObjectListObject_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = 'test.tt' + request_data = BuildRequestWrap( line_num = 1, + column_num = 8, + contents = contents ) + + eq_( request_data[ 'query' ], 'tt' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = { + 'words': [ + { + 'word': ToBytesOnPY2( 'a' ), + 'abbr': ToBytesOnPY2( 'ABBR'), + 'menu': ToBytesOnPY2( 'MENU' ), + 'info': ToBytesOnPY2( 'INFO' ), + 'kind': ToBytesOnPY2( 'K' ) + }, + { + 'word': ToBytesOnPY2( 'test' ), + 'abbr': ToBytesOnPY2( 'ABBRTEST'), + 'menu': ToBytesOnPY2( 'MENUTEST' ), + 'info': ToBytesOnPY2( 'INFOTEST' ), + 'kind': ToBytesOnPY2( 'T' ) + } + ] + } + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'tt')" ), + ] ) + + eq_( results, [ omnifunc_result[ 'words' ][ 1 ] ] ) + + + def OmniCompleter_GetCompletions_NoCache_ObjectListObject_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = 'test.tt' + request_data = BuildRequestWrap( line_num = 1, + column_num = 8, + contents = contents ) + + eq_( request_data[ 'query' ], 'tt' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = { + 'words': [ + { + 'word': ToBytesOnPY2( 'a' ), + 'abbr': ToBytesOnPY2( 'ABBR'), + 'menu': ToBytesOnPY2( 'MENU' ), + 'info': ToBytesOnPY2( 'INFO' ), + 'kind': ToBytesOnPY2( 'K' ) + }, + { + 'word': ToBytesOnPY2( 'test' ), + 'abbr': ToBytesOnPY2( 'ABBRTEST'), + 'menu': ToBytesOnPY2( 'MENUTEST' ), + 'info': ToBytesOnPY2( 'INFOTEST' ), + 'kind': ToBytesOnPY2( 'T' ) + } + ] + } + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'tt')" ), + ] ) + + # No FilterAndSortCandidates for cache_omnifunc=0 (we expect the omnifunc + # to do the filtering?) + eq_( results, omnifunc_result[ 'words' ] ) + + + def OmniCompleter_GetCompletions_Cache_List_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = '†åsty_π.' + request_data = BuildRequestWrap( line_num = 1, + column_num = 13, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( '†est' ), + ToBytesOnPY2( 'å_unicode_identifier' ), + ToBytesOnPY2( 'πππππππ yummy πie' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'')" ), + ] ) + + eq_( results, omnifunc_result ) + + + def OmniCompleter_GetCompletions_NoCache_List_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = '†åsty_π.' + request_data = BuildRequestWrap( line_num = 1, + column_num = 13, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( '†est' ), + ToBytesOnPY2( 'å_unicode_identifier' ), + ToBytesOnPY2( 'πππππππ yummy πie' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'')" ), + ] ) + + eq_( results, omnifunc_result ) + + + @ExpectedFailure( 'Filtering on unicode is not supported by the server' ) + def OmniCompleter_GetCompletions_Cache_List_Filter_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = '†åsty_π.ππ' + request_data = BuildRequestWrap( line_num = 1, + column_num = 17, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( '†est' ), + ToBytesOnPY2( 'å_unicode_identifier' ), + ToBytesOnPY2( 'πππππππ yummy πie' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'ππ')" ), + ] ) + + # Fails here: Filtering on unicode is not supported + eq_( results, [ omnifunc_result[ 2 ] ] ) + + + def OmniCompleter_GetCompletions_NoCache_List_Filter_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 0 + } ) ) + + contents = '†åsty_π.ππ' + request_data = BuildRequestWrap( line_num = 1, + column_num = 17, + contents = contents ) + + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ ToBytesOnPY2( 'πππππππ yummy πie' ) ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'ππ')" ), + ] ) + + eq_( results, omnifunc_result ) + + + @ExpectedFailure( 'Filtering on unicode is not supported by the server' ) + def OmniCompleter_GetCompletions_Cache_ObjectList_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = '†åsty_π.ππ' + request_data = BuildRequestWrap( line_num = 1, + column_num = 17, + contents = contents ) + + + eq_( request_data[ 'query' ], 'ππ' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = [ + { + 'word': ToBytesOnPY2( 'ålpha∫et' ), + 'abbr': ToBytesOnPY2( 'å∫∫®'), + 'menu': ToBytesOnPY2( 'µ´~¨á' ), + 'info': ToBytesOnPY2( '^~fo' ), + 'kind': ToBytesOnPY2( '˚' ) + }, + { + 'word': ToBytesOnPY2( 'π†´ß†π' ), + 'abbr': ToBytesOnPY2( 'ÅııÂʉÍÊ'), + 'menu': ToBytesOnPY2( '˜‰ˆËʉÍÊ' ), + 'info': ToBytesOnPY2( 'ȈÏØʉÍÊ' ), + 'kind': ToBytesOnPY2( 'Ê' ) + } + ] + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'ππ')" ), + ] ) + + # Fails here: Filtering on unicode is not supported + eq_( results, [ omnifunc_result[ 1 ] ] ) + + + def OmniCompleter_GetCompletions_Cache_ObjectListObject_Unicode_test( self ): + omni_completer = OmniCompleter( MakeUserOptions( { + 'cache_omnifunc': 1 + } ) ) + + contents = '†åsty_π.t' + request_data = BuildRequestWrap( line_num = 1, + column_num = 14, + contents = contents ) + + + eq_( request_data[ 'query' ], 't' ) + + # Make sure there is an omnifunc set up. + with patch( 'vim.eval', return_value = ToBytesOnPY2( 'test_omnifunc' ) ): + omni_completer.OnFileReadyToParse( request_data ) + + omnifunc_result = { + 'words': [ + { + 'word': ToBytesOnPY2( 'ålpha∫et' ), + 'abbr': ToBytesOnPY2( 'å∫∫®'), + 'menu': ToBytesOnPY2( 'µ´~¨á' ), + 'info': ToBytesOnPY2( '^~fo' ), + 'kind': ToBytesOnPY2( '˚' ) + }, + { + 'word': ToBytesOnPY2( 'π†´ß†π' ), + 'abbr': ToBytesOnPY2( 'ÅııÂʉÍÊ'), + 'menu': ToBytesOnPY2( '˜‰ˆËʉÍÊ' ), + 'info': ToBytesOnPY2( 'ȈÏØʉÍÊ' ), + 'kind': ToBytesOnPY2( 'Ê' ) + }, + { + 'word': ToBytesOnPY2( 'test' ), + 'abbr': ToBytesOnPY2( 'ÅııÂʉÍÊ'), + 'menu': ToBytesOnPY2( '˜‰ˆËʉÍÊ' ), + 'info': ToBytesOnPY2( 'ȈÏØʉÍÊ' ), + 'kind': ToBytesOnPY2( 'Ê' ) + } + ] + } + + # And get the completions + with patch( 'vim.eval', + new_callable = ExtendedMock, + side_effect = [ 6, omnifunc_result ] ) as vim_eval: + + results = omni_completer.ComputeCandidates( request_data ) + + vim_eval.assert_has_exact_calls( [ + call( 'test_omnifunc(1,"")' ), + call( "test_omnifunc(0,'t')" ), + ] ) + + # Note: the filtered results are all unicode objects (not bytes) because + # they are passed through the FilterAndSortCandidates machinery + # (via the server) + eq_( results, [ { + 'word': 'test', + 'abbr': 'ÅııÂʉÍÊ', + 'menu': '˜‰ˆËʉÍÊ', + 'info': 'ȈÏØʉÍÊ', + 'kind': 'Ê' + } ] ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/paths_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/paths_test.py new file mode 100644 index 0000000..e390f4f --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/paths_test.py @@ -0,0 +1,78 @@ +# Copyright (C) 2016 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import MockVimModule +MockVimModule() + +from nose.tools import ok_ +from ycm.paths import EndsWithPython + + +def EndsWithPython_Good( path ): + ok_( EndsWithPython( path ) ) + + +def EndsWithPython_Bad( path ): + ok_( not EndsWithPython( path ) ) + + +def EndsWithPython_Python2Paths_test(): + python_paths = [ + 'python', + 'python2', + '/usr/bin/python2.6', + '/home/user/.pyenv/shims/python2.7', + r'C:\Python26\python.exe' + ] + + for path in python_paths: + yield EndsWithPython_Good, path + + + +def EndsWithPython_Python3Paths_test(): + python_paths = [ + 'python3', + '/usr/bin/python3.3', + '/home/user/.pyenv/shims/python3.3', + r'C:\Python33\python.exe' + ] + + for path in python_paths: + yield EndsWithPython_Good, path + + +def EndsWithPython_BadPaths_test(): + not_python_paths = [ + None, + '', + '/opt/local/bin/vim', + r'C:\Program Files\Vim\vim74\gvim.exe', + '/usr/bin/python2.5', + '/home/user/.pyenv/shims/python3.2', + ] + + for path in not_python_paths: + yield EndsWithPython_Bad, path diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/postcomplete_tests.py b/vim/bundle/YouCompleteMe/python/ycm/tests/postcomplete_tests.py new file mode 100644 index 0000000..11225d4 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/postcomplete_tests.py @@ -0,0 +1,439 @@ +# encoding: utf-8 +# +# Copyright (C) 2015 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import MockVimModule +MockVimModule() + +import contextlib +from hamcrest import assert_that, empty +from mock import MagicMock, DEFAULT, patch +from nose.tools import eq_, ok_ + +from ycmd.utils import ToBytes +from ycm import vimsupport +from ycm.youcompleteme import YouCompleteMe + + +def GetVariableValue_CompleteItemIs( word, abbr = None, menu = None, + info = None, kind = None ): + def Result( variable ): + if variable == 'v:completed_item': + return { + 'word': ToBytes( word ), + 'abbr': ToBytes( abbr ), + 'menu': ToBytes( menu ), + 'info': ToBytes( info ), + 'kind': ToBytes( kind ), + } + return DEFAULT + return MagicMock( side_effect = Result ) + + +def BuildCompletion( namespace = None, insertion_text = 'Test', + menu_text = None, extra_menu_info = None, + detailed_info = None, kind = None ): + return { + 'extra_data': { 'required_namespace_import': namespace }, + 'insertion_text': insertion_text, + 'menu_text': menu_text, + 'extra_menu_info': extra_menu_info, + 'kind': kind, + 'detailed_info': detailed_info, + } + + +class PostComplete_test(): + + def setUp( self ): + self.ycm = YouCompleteMe( MagicMock( spec_set = dict ) ) + + + def tearDown( self ): + self.ycm.OnVimLeave() + + + @contextlib.contextmanager + def _SetupForCsharpCompletionDone( self, completions ): + with patch( 'ycm.vimsupport.InsertNamespace' ): + with patch( 'ycm.vimsupport.TextBeforeCursor', + return_value = ' Test' ): + request = MagicMock() + request.Done = MagicMock( return_value = True ) + request.RawResponse = MagicMock( return_value = completions ) + self.ycm._latest_completion_request = request + yield + + + @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'cs' ] ) + def GetCompleteDoneHooks_ResultOnCsharp_test( self, *args ): + result = self.ycm.GetCompleteDoneHooks() + eq_( 1, len( list( result ) ) ) + + + @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'txt' ] ) + def GetCompleteDoneHooks_EmptyOnOtherFiletype_test( self, *args ): + result = self.ycm.GetCompleteDoneHooks() + eq_( 0, len( list( result ) ) ) + + + @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'txt' ] ) + def OnCompleteDone_WithActionCallsIt_test( self, *args ): + action = MagicMock() + self.ycm._complete_done_hooks[ 'txt' ] = action + self.ycm.OnCompleteDone() + + ok_( action.called ) + + + @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'txt' ] ) + def OnCompleteDone_NoActionNoError_test( self, *args ): + self.ycm.OnCompleteDone() + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Test' ) ) + def FilterToCompletedCompletions_NewVim_MatchIsReturned_test( self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + eq_( list( result ), completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'A' ) ) + def FilterToCompletedCompletions_NewVim_ShortTextDoesntRaise_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'AAA' ) ] + self.ycm._FilterToMatchingCompletions( completions, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Test' ) ) + def FilterToCompletedCompletions_NewVim_ExactMatchIsReturned_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + eq_( list( result ), completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( ' Quote' ) ) + def FilterToCompletedCompletions_NewVim_NonMatchIsntReturned_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'A' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + assert_that( list( result ), empty() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( '†es†' ) ) + def FilterToCompletedCompletions_NewVim_Unicode_test( self, *args ): + completions = [ BuildCompletion( insertion_text = '†es†' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + eq_( list( result ), completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Test' ) + def FilterToCompletedCompletions_OldVim_MatchIsReturned_test( self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + eq_( list( result ), completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'X' ) + def FilterToCompletedCompletions_OldVim_ShortTextDoesntRaise_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'AAA' ) ] + self.ycm._FilterToMatchingCompletions( completions, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'Test' ) + def FilterToCompletedCompletions_OldVim_ExactMatchIsReturned_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + eq_( list( result ), completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def FilterToCompletedCompletions_OldVim_NonMatchIsntReturned_test( self, + *args ): + completions = [ BuildCompletion( insertion_text = 'A' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + assert_that( list( result ), empty() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'Uniçø∂¢' ) + def FilterToCompletedCompletions_OldVim_Unicode_test( self, *args ): + completions = [ BuildCompletion( insertion_text = 'Uniçø∂¢' ) ] + result = self.ycm._FilterToMatchingCompletions( completions, False ) + assert_that( list( result ), empty() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Te' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_OldVim_MatchIsReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, True ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'X' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_OldVim_ShortTextDoesntRaise_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = "AAA" ) ] + self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'Test' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_OldVim_ExactMatchIsntReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_OldVim_NonMatchIsntReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'A' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'Uniç' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_OldVim_Unicode_test( + self, *args ): + completions = [ BuildCompletion( insertion_text = 'Uniçø∂¢' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, True ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Te' ) ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_NewVim_MatchIsReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, True ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'X' ) ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_NewVim_ShortTextDoesntRaise_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'AAA' ) ] + self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( completions ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Test' ) ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_NewVim_ExactMatchIsntReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = 'Test' ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( ' Quote' ) ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Quote' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_NewVim_NonMatchIsntReturned_test( # noqa + self, *args ): + completions = [ BuildCompletion( insertion_text = "A" ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, False ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Uniç' ) ) + @patch( 'ycm.vimsupport.TextBeforeCursor', return_value = 'Uniç' ) + def HasCompletionsThatCouldBeCompletedWithMoreText_NewVim_Unicode_test( + self, *args ): + completions = [ BuildCompletion( insertion_text = "Uniçø∂¢" ) ] + result = self.ycm._HasCompletionsThatCouldBeCompletedWithMoreText( + completions ) + eq_( result, True ) + + + def GetRequiredNamespaceImport_ReturnNoneForNoExtraData_test( self ): + eq_( None, self.ycm._GetRequiredNamespaceImport( {} ) ) + + + def GetRequiredNamespaceImport_ReturnNamespaceFromExtraData_test( self ): + namespace = 'A_NAMESPACE' + eq_( namespace, self.ycm._GetRequiredNamespaceImport( + BuildCompletion( namespace ) + ) ) + + + def GetCompletionsUserMayHaveCompleted_ReturnEmptyIfNotDone_test( self ): + with self._SetupForCsharpCompletionDone( [] ): + self.ycm._latest_completion_request.Done = MagicMock( + return_value = False ) + eq_( [], self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Te' ) ) + def GetCompletionsUserMayHaveCompleted_ReturnEmptyIfPendingMatches_NewVim_test( # noqa + self, *args ): + completions = [ BuildCompletion( None ) ] + with self._SetupForCsharpCompletionDone( completions ): + eq_( [], self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + def GetCompletionsUserMayHaveCompleted_ReturnEmptyIfPendingMatches_OldVim_test( # noqa + self, *args ): + completions = [ BuildCompletion( None ) ] + with self._SetupForCsharpCompletionDone( completions ): + with patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Te' ): + eq_( [], self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + def GetCompletionsUserMayHaveCompleted_ReturnMatchIfExactMatches_NewVim_test( + self, *args ): + info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] + completions = [ BuildCompletion( *info ) ] + with self._SetupForCsharpCompletionDone( completions ): + with patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): + eq_( completions, self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + def GetCompletionsUserMayHaveCompleted_ReturnMatchIfExactMatchesEvenIfPartial_NewVim_test( # noqa + self, *args ): + info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] + completions = [ BuildCompletion( *info ), + BuildCompletion( insertion_text = 'TestTest' ) ] + with self._SetupForCsharpCompletionDone( completions ): + with patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): + eq_( [ completions[ 0 ] ], + self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + def GetCompletionsUserMayHaveCompleted_DontReturnMatchIfNontExactMatchesAndPartial_NewVim_test( # noqa + self, *args ): + info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] + completions = [ BuildCompletion( insertion_text = info[ 0 ] ), + BuildCompletion( insertion_text = 'TestTest' ) ] + with self._SetupForCsharpCompletionDone( completions ): + with patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): + eq_( [], self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = True ) + @patch( 'ycm.vimsupport.GetVariableValue', + GetVariableValue_CompleteItemIs( 'Test' ) ) + def GetCompletionsUserMayHaveCompleted_ReturnMatchIfMatches_NewVim_test( + self, *args ): + completions = [ BuildCompletion( None ) ] + with self._SetupForCsharpCompletionDone( completions ): + eq_( completions, self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + def GetCompletionsUserMayHaveCompleted_ReturnMatchIfMatches_OldVim_test( + self, *args ): + completions = [ BuildCompletion( None ) ] + with self._SetupForCsharpCompletionDone( completions ): + eq_( completions, self.ycm.GetCompletionsUserMayHaveCompleted() ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + def PostCompleteCsharp_EmptyDoesntInsertNamespace_test( self, *args ): + with self._SetupForCsharpCompletionDone( [] ): + self.ycm._OnCompleteDone_Csharp() + ok_( not vimsupport.InsertNamespace.called ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + def PostCompleteCsharp_ExistingWithoutNamespaceDoesntInsertNamespace_test( + self, *args ): + completions = [ BuildCompletion( None ) ] + with self._SetupForCsharpCompletionDone( completions ): + self.ycm._OnCompleteDone_Csharp() + ok_( not vimsupport.InsertNamespace.called ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + def PostCompleteCsharp_ValueDoesInsertNamespace_test( self, *args ): + namespace = 'A_NAMESPACE' + completions = [ BuildCompletion( namespace ) ] + with self._SetupForCsharpCompletionDone( completions ): + self.ycm._OnCompleteDone_Csharp() + vimsupport.InsertNamespace.assert_called_once_with( namespace ) + + + @patch( 'ycm.vimsupport.VimVersionAtLeast', return_value = False ) + @patch( 'ycm.vimsupport.PresentDialog', return_value = 1 ) + def PostCompleteCsharp_InsertSecondNamespaceIfSelected_test( self, *args ): + namespace = 'A_NAMESPACE' + namespace2 = 'ANOTHER_NAMESPACE' + completions = [ + BuildCompletion( namespace ), + BuildCompletion( namespace2 ), + ] + with self._SetupForCsharpCompletionDone( completions ): + self.ycm._OnCompleteDone_Csharp() + vimsupport.InsertNamespace.assert_called_once_with( namespace2 ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/syntax_parse_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/syntax_parse_test.py new file mode 100644 index 0000000..8fe5c79 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/syntax_parse_test.py @@ -0,0 +1,310 @@ +# Copyright (C) 2013 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import MockVimModule +MockVimModule() + +import os +from nose.tools import eq_ +from hamcrest import assert_that, has_items +from ycm import syntax_parse +from ycmd.utils import ReadFile + + +def ContentsOfTestFile( test_file ): + dir_of_script = os.path.dirname( os.path.abspath( __file__ ) ) + full_path_to_test_file = os.path.join( dir_of_script, 'testdata', test_file ) + return ReadFile( full_path_to_test_file ) + + + +def KeywordsFromSyntaxListOutput_PythonSyntax_test(): + eq_( set(['bytearray', 'IndexError', 'all', 'help', 'vars', + 'SyntaxError', 'global', 'elif', 'unicode', 'sorted', 'memoryview', + 'isinstance', 'except', 'nonlocal', 'NameError', 'finally', + 'BytesWarning', 'dict', 'IOError', 'pass', 'oct', 'match', 'bin', + 'SystemExit', 'return', 'StandardError', 'format', 'TabError', + 'break', 'next', 'not', 'UnicodeDecodeError', 'False', + 'RuntimeWarning', 'list', 'iter', 'try', 'reload', 'Warning', + 'round', 'dir', 'cmp', 'set', 'bytes', 'UnicodeTranslateError', + 'intern', 'issubclass', 'yield', 'Ellipsis', 'hash', 'locals', + 'BufferError', 'slice', 'for', 'FloatingPointError', 'sum', + 'VMSError', 'getattr', 'abs', 'print', 'import', 'True', + 'FutureWarning', 'ImportWarning', 'None', 'EOFError', 'len', + 'frozenset', 'ord', 'super', 'raise', 'TypeError', + 'KeyboardInterrupt', 'UserWarning', 'filter', 'range', + 'staticmethod', 'SystemError', 'or', 'BaseException', 'pow', + 'RuntimeError', 'float', 'MemoryError', 'StopIteration', 'globals', + 'divmod', 'enumerate', 'apply', 'LookupError', 'open', 'basestring', + 'from', 'UnicodeError', 'zip', 'hex', 'long', 'IndentationError', + 'int', 'chr', '__import__', 'type', 'Exception', 'continue', + 'tuple', 'reduce', 'reversed', 'else', 'assert', + 'UnicodeEncodeError', 'input', 'with', 'hasattr', 'delattr', + 'setattr', 'raw_input', 'PendingDeprecationWarning', 'compile', + 'ArithmeticError', 'while', 'del', 'str', 'property', 'def', 'and', + 'GeneratorExit', 'ImportError', 'xrange', 'is', 'EnvironmentError', + 'KeyError', 'coerce', 'SyntaxWarning', 'file', 'in', 'unichr', + 'ascii', 'any', 'as', 'if', 'OSError', 'DeprecationWarning', 'min', + 'UnicodeWarning', 'execfile', 'id', 'complex', 'bool', 'ValueError', + 'NotImplemented', 'map', 'exec', 'buffer', 'max', 'class', 'object', + 'repr', 'callable', 'ZeroDivisionError', 'eval', '__debug__', + 'ReferenceError', 'AssertionError', 'classmethod', + 'UnboundLocalError', 'NotImplementedError', 'lambda', + 'AttributeError', 'OverflowError', 'WindowsError'] ), + syntax_parse._KeywordsFromSyntaxListOutput( + ContentsOfTestFile( 'python_syntax' ) ) ) + + +def KeywordsFromSyntaxListOutput_CppSyntax_test(): + eq_( set(['int_fast32_t', 'FILE', 'size_t', 'bitor', 'typedef', 'const', + 'struct', 'uint8_t', 'fpos_t', 'thread_local', 'unsigned', + 'uint_least16_t', 'match', 'do', 'intptr_t', 'uint_least64_t', + 'return', 'auto', 'void', '_Complex', 'break', '_Alignof', 'not', + 'using', '_Static_assert', '_Thread_local', 'public', + 'uint_fast16_t', 'this', 'continue', 'char32_t', 'int16_t', + 'intmax_t', 'static', 'clock_t', 'sizeof', 'int_fast64_t', + 'mbstate_t', 'try', 'xor', 'uint_fast32_t', 'int_least8_t', 'div_t', + 'volatile', 'template', 'char16_t', 'new', 'ldiv_t', + 'int_least16_t', 'va_list', 'uint_least8_t', 'goto', 'noreturn', + 'enum', 'static_assert', 'bitand', 'compl', 'imaginary', 'jmp_buf', + 'throw', 'asm', 'ptrdiff_t', 'uint16_t', 'or', 'uint_fast8_t', + '_Bool', 'int32_t', 'float', 'private', 'restrict', 'wint_t', + 'operator', 'not_eq', '_Imaginary', 'alignas', 'union', 'long', + 'uint_least32_t', 'int_least64_t', 'friend', 'uintptr_t', 'int8_t', + 'else', 'export', 'int_fast8_t', 'catch', 'true', 'case', 'default', + 'double', '_Noreturn', 'signed', 'typename', 'while', 'protected', + 'wchar_t', 'wctrans_t', 'uint64_t', 'delete', 'and', 'register', + 'false', 'int', 'uintmax_t', 'off_t', 'char', 'int64_t', + 'int_fast16_t', 'DIR', '_Atomic', 'time_t', 'xor_eq', 'namespace', + 'virtual', 'complex', 'bool', 'mutable', 'if', 'int_least32_t', + 'sig_atomic_t', 'and_eq', 'ssize_t', 'alignof', '_Alignas', + '_Generic', 'extern', 'class', 'typeid', 'short', 'for', + 'uint_fast64_t', 'wctype_t', 'explicit', 'or_eq', 'switch', + 'uint32_t', 'inline']), + syntax_parse._KeywordsFromSyntaxListOutput( + ContentsOfTestFile( 'cpp_syntax' ) ) ) + + +def KeywordsFromSyntaxListOutput_JavaSyntax_test(): + eq_( set(['code', 'text', 'cols', 'datetime', 'disabled', 'shape', 'codetype', + 'alt', 'compact', 'style', 'valuetype', 'short', 'finally', + 'continue', 'extends', 'valign', 'match', 'bordercolor', 'do', + 'return', 'rel', 'rules', 'void', 'nohref', 'abbr', 'background', + 'scrolling', 'instanceof', 'name', 'summary', 'try', 'default', + 'noshade', 'coords', 'dir', 'frame', 'usemap', 'ismap', 'static', + 'hspace', 'vlink', 'for', 'selected', 'rev', 'vspace', 'content', + 'method', 'version', 'volatile', 'above', 'new', 'charoff', 'public', + 'alink', 'enum', 'codebase', 'if', 'noresize', 'interface', + 'checked', 'byte', 'super', 'throw', 'src', 'language', 'package', + 'standby', 'script', 'longdesc', 'maxlength', 'cellpadding', + 'throws', 'tabindex', 'color', 'colspan', 'accesskey', 'float', + 'while', 'private', 'height', 'boolean', 'wrap', 'prompt', 'nowrap', + 'size', 'rows', 'span', 'clip', 'bgcolor', 'top', 'long', 'start', + 'scope', 'scheme', 'type', 'final', 'lang', 'visibility', 'else', + 'assert', 'transient', 'link', 'catch', 'true', 'serializable', + 'target', 'lowsrc', 'this', 'double', 'align', 'value', 'cite', + 'headers', 'below', 'protected', 'declare', 'classid', 'defer', + 'false', 'synchronized', 'int', 'abstract', 'accept', 'hreflang', + 'char', 'border', 'id', 'native', 'rowspan', 'charset', 'archive', + 'strictfp', 'readonly', 'axis', 'cellspacing', 'profile', 'multiple', + 'object', 'action', 'pagex', 'pagey', 'marginheight', 'data', + 'class', 'frameborder', 'enctype', 'implements', 'break', 'gutter', + 'url', 'clear', 'face', 'switch', 'marginwidth', 'width', 'left']), + syntax_parse._KeywordsFromSyntaxListOutput( + ContentsOfTestFile( 'java_syntax' ) ) ) + + +def KeywordsFromSyntaxListOutput_PhpSyntax_ContainsFunctions_test(): + assert_that( syntax_parse._KeywordsFromSyntaxListOutput( + ContentsOfTestFile( 'php_syntax' ) ), + has_items( 'array_change_key_case' ) ) + + +def KeywordsFromSyntaxListOutput_Basic_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +foogroup xxx foo bar + zoo goo + links to Statement""" ) ) + + +def KeywordsFromSyntaxListOutput_Function_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +foogroup xxx foo bar + zoo goo + links to Function""" ) ) + + +def KeywordsFromSyntaxListOutput_ContainedArgAllowed_test(): + assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ +phpFunctions xxx contained gzclose yaz_syntax html_entity_decode fbsql_read_blob png2wbmp mssql_init cpdf_set_title gztell fbsql_insert_id empty cpdf_restore mysql_field_type closelog swftext ldap_search curl_errno gmp_div_r mssql_data_seek getmyinode printer_draw_pie mcve_initconn ncurses_getmaxyx defined + contained replace_child has_attributes specified insertdocument assign node_name hwstat addshape get_attribute_node html_dump_mem userlist + links to Function""" ), # noqa + has_items( 'gzclose', 'userlist', 'ldap_search' ) ) + + +def KeywordsFromSyntaxListOutput_JunkIgnored_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +--- Syntax items --- +foogroup xxx foo bar + zoo goo + links to Statement +Spell cluster=NONE +NoSpell cluster=NONE""" ) ) + + +def KeywordsFromSyntaxListOutput_MultipleStatementGroups_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +foogroup xxx foo bar + links to Statement +bargroup xxx zoo goo + links to Statement""" ) ) + + +def KeywordsFromSyntaxListOutput_StatementAndTypeGroups_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +foogroup xxx foo bar + links to Statement +bargroup xxx zoo goo + links to Type""" ) ) + + +def KeywordsFromSyntaxListOutput_StatementHierarchy_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +baa xxx foo bar + links to Foo +Foo xxx zoo goo + links to Bar +Bar xxx qux moo + links to Statement""" ) ) + + +def KeywordsFromSyntaxListOutput_TypeHierarchy_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +baa xxx foo bar + links to Foo +Foo xxx zoo goo + links to Bar +Bar xxx qux moo + links to Type""" ) ) + + +def KeywordsFromSyntaxListOutput_StatementAndTypeHierarchy_test(): + eq_( set([ 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo', 'na', 'nb', 'nc' ]), + syntax_parse._KeywordsFromSyntaxListOutput( """ +tBaa xxx foo bar + links to tFoo +tFoo xxx zoo goo + links to tBar +tBar xxx qux moo + links to Type +sBaa xxx na bar + links to sFoo +sFoo xxx zoo nb + links to sBar +sBar xxx qux nc + links to Statement""" ) ) + + +def SyntaxGroupsFromOutput_Basic_test(): + groups = syntax_parse._SyntaxGroupsFromOutput( + """foogroup xxx foo bar + zoo goo + links to Statement""" ) + + assert 'foogroup' in groups + + +def ExtractKeywordsFromGroup_Basic_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo bar', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_Commas_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo, bar,', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_WithLinksTo_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo bar', + 'zoo goo', + 'links to Statement' + ] ) ) ) + + +def ExtractKeywordsFromGroup_KeywordStarts_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo bar', + 'transparent boo baa', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_KeywordMiddle_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo oneline bar', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_KeywordAssign_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo end=zoo((^^//)) bar', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_KeywordAssignAndMiddle_test(): + eq_( ['foo', 'bar', 'zoo', 'goo' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'foo end=zoo((^^//)) transparent bar', + 'zoo goo', + ] ) ) ) + + +def ExtractKeywordsFromGroup_ContainedSyntaxArgAllowed_test(): + eq_( ['foo', 'zoq', 'bar', 'goo', 'far' ], + syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup('', [ + 'contained foo zoq', + 'contained bar goo', + 'far', + ] ) ) ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/cpp_syntax b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/cpp_syntax new file mode 100644 index 0000000..4d111a5 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/cpp_syntax @@ -0,0 +1,160 @@ +--- Syntax items --- +cCustomFunc xxx match /\w\+\s*\((\)\@=/ + links to Function +cCustomClass xxx match /\w\+\s*\(::\)\@=/ + links to Function +OperatorChars xxx match #?\|+\|-\|\*\|;\|:\|,\|<\|>\|&\||\|!\|\~\|%\|=\|)\|(\|{\|}\|\.\|\[\|\]\|/\(/\|*\)\@!# +cStatement xxx return goto asm continue break + links to Statement +cLabel xxx default case + links to Label +cConditional xxx if switch else + links to Conditional +cRepeat xxx for while do + links to Repeat +cTodo xxx contained XXX FIXME TODO + links to Todo +cBadContinuation xxx match /\\\s\+$/ contained + links to Error +cSpecial xxx match /\\\(x\x\+\|\o\{1,3}\|.\|$\)/ display contained + match /\\\(u\x\{4}\|U\x\{8}\)/ display contained + links to SpecialChar +cFormat xxx match /%\(\d\+\$\)\=[-+' #0*]*\(\d*\|\*\|\*\d\+\$\)\(\.\(\d*\|\*\|\*\d\+\$\)\)\=\([hlLjzt]\|ll\|hh\)\=\([aAbdiuoxXDOUfFeEgGcCsSpn]\|\[\^\=.[^]]*\]\)/ display contained + match /%%/ display contained + links to cSpecial +cString xxx start=/L\="/ skip=/\\\\\|\\"/ end=/"/ extend contains=cSpecial,cFormat,@Spell + start=/\%(U\|u8\=\)"/ skip=/\\\\\|\\"/ end=/"/ extend contains=cSpecial,cFormat,@Spell + links to String +cCppString xxx start=/L\="/ skip=/\\\\\|\\"\|\\$/ end=/$/ end=/"/ excludenl contains=cSpecial,cFormat,@Spell + links to cString +cCharacter xxx match /L\='[^\\]'/ + match /L'[^']*'/ contains=cSpecial + match /[Uu]'[^\\]'/ + match /[Uu]'[^']*'/ contains=cSpecial + links to Character +cSpecialError xxx match /L\='\\[^'\"?\\abfnrtv]'/ + match /[Uu]'\\[^'\"?\\abfnrtv]'/ + links to cError +cSpecialCharacter xxx match /L\='\\['\"?\\abfnrtv]'/ + match /L\='\\\o\{1,3}'/ display + match /'\\x\x\{1,2}'/ display + match /L'\\x\x\+'/ display + match /[Uu]'\\['\"?\\abfnrtv]'/ + match /[Uu]'\\\o\{1,3}'/ display + match /[Uu]'\\x\x\+'/ display + links to cSpecial +cBadBlock xxx start=/{/ end=/}/ contained keepend transparent fold containedin=cParen,cBracket,cBadBlock +cErrInParen xxx match /[\]{}]\|<%\|%>/ display contained + links to cError +cCppParen xxx start=/(/ skip=/\\$/ end=/$/ end=/)/ contained excludenl transparent contains=ALLBUT,@cParenGroup,cErrInBracket,cParen,cBracket,cString,@Spell +cErrInBracket xxx match /[);{}]\|<%\|%>/ display contained + links to cError +cCppBracket xxx start=/\[\|<::\@!/ skip=/\\$/ end=/$/ end=/]\|:>/ contained excludenl transparent contains=ALLBUT,@cParenGroup,cErrInParen,cParen,cBracket,cString,@Spell +cBlock xxx start=/{/ end=/}/ transparent fold +cParenError xxx match /[\])]/ display + links to cError +cIncluded xxx start=/"/ skip=/\\\\\|\\"/ end=/"/ display contained + match /<[^>]*>/ display contained + links to cString +cCommentStartError xxx match +/\*+me=e-1 display contained + links to cError +cUserCont xxx match /^\s*\I\i*\s*:$/ display contains=@cLabelGroup + match /;\s*\I\i*\s*:$/ display contains=@cLabelGroup + match /^\s*\I\i*\s*:[^:]/me=e-1 display contains=@cLabelGroup + match /;\s*\I\i*\s*:[^:]/me=e-1 display contains=@cLabelGroup +cUserLabel xxx match /\I\i*/ display contained + links to Label +cBitField xxx match /^\s*\I\i*\s*:\s*[1-9]/me=e-1 display contains=cType + match /;\s*\I\i*\s*:\s*[1-9]/me=e-1 display contains=cType +cOctalZero xxx match /\<0/ display contained + links to PreProc +cNumber xxx match /\d\+\(u\=l\{0,2}\|ll\=u\)\>/ display contained + match /0x\x\+\(u\=l\{0,2}\|ll\=u\)\>/ display contained + links to Number +cFloat xxx match /\d\+f/ display contained + match /\d\+\.\d*\(e[-+]\=\d\+\)\=[fl]\=/ display contained + match /\.\d\+\(e[-+]\=\d\+\)\=[fl]\=\>/ display contained + match /\d\+e[-+]\=\d\+[fl]\=\>/ display contained + match /0x\x*\.\x\+p[-+]\=\d\+[fl]\=\>/ display contained + match /0x\x\+\.\=p[-+]\=\d\+[fl]\=\>/ display contained + links to Float +cOctal xxx match /0\o\+\(u\=l\{0,2}\|ll\=u\)\>/ display contained contains=cOctalZero + links to Number +cOctalError xxx match /0\o*[89]\d*/ display contained + links to cError +cNumbersCom xxx match /\<\d\|\.\d/ display contained transparent contains=cNumber,cFloat,cOctal +cParen xxx start=/(/ end=/}/me=s-1 end=/)/ transparent contains=ALLBUT,cBlock,@cParenGroup,cCppParen,cErrInBracket,cCppBracket,cCppString,@Spell +cBracket xxx start=/\[\|<::\@!/ end=/}/me=s-1 end=/]\|:>/ transparent contains=ALLBUT,cBlock,@cParenGroup,cErrInParen,cCppParen,cCppBracket,cCppString,@Spell +cNumbers xxx match /\<\d\|\.\d/ display transparent contains=cNumber,cFloat,cOctalError,cOctal +cCommentL xxx start=+//+ skip=/\\$/ end=/$/ keepend contains=@cCommentGroup,cSpaceError,@Spell + links to cComment +cComment xxx matchgroup=cCommentStart start=+/\*+ end=+\*/+ extend fold contains=@cCommentGroup,cCommentStartError,cSpaceError,@Spell + links to Comment +cCommentError xxx match +\*/+ display + links to cError +cOperator xxx _Generic sizeof _Alignof _Static_assert alignof static_assert + links to Operator +cType xxx wchar_t uint8_t uint_fast32_t _Bool int_fast8_t float off_t _Complex uint_least32_t int_fast16_t int_fast32_t ptrdiff_t uintptr_t uint64_t uint_fast8_t int_least32_t long void wint_t complex uint_least8_t uint16_t uint_fast64_t imaginary int32_t unsigned char16_t FILE uint_least64_t int_least8_t va_list intptr_t int_fast64_t uint_fast16_t fpos_t size_t wctrans_t div_t jmp_buf uintmax_t mbstate_t int_least64_t _Imaginary uint_least16_t int8_t time_t DIR clock_t sig_atomic_t wctype_t int_least16_t ldiv_t bool ssize_t uint32_t double short char intmax_t int64_t char32_t int int16_t signed + links to Type +cStructure xxx struct union typedef enum + links to Structure +cStorageClass xxx inline const volatile alignas register thread_local _Noreturn static extern _Alignas _Atomic restrict noreturn _Thread_local auto + links to StorageClass +cConstant xxx stderr USHRT_MAX CHAR_BIT SIGINT SIGINT EINVAL LDBL_MIN_EXP INT_FAST32_MIN UINT_LEAST16_MAX LONG_MAX EROFS EXIT_FAILURE ENOTSUP SCHAR_MAX SEEK_END EINPROGRESS SLONG_MIN SIGSEGV SIGSEGV UINT_FAST8_MAX EINTR true ENOSYS INT32_MAX ULLONG_MAX SINT_MIN SIGALRM SHRT_MIN INT64_MAX WINT_MAX ENOTDIR INT_FAST16_MAX ESPIPE __FILE__ M_PI TMP_MAX MB_LEN_MAX SIGKILL DBL_MIN_10_EXP INT_LEAST8_MAX LC_COLLATE ENOSPC HUGE_VAL EIO INT8_MAX LC_MONETARY LDBL_MIN INT_LEAST16_MIN INT_FAST64_MIN INT_MAX EILSEQ FLT_MANT_DIG INT_FAST32_MAX __func__ FLT_MIN EOF false DBL_MIN_EXP ETIMEDOUT INT_FAST8_MIN M_LN10 FLT_EPSILON stdin INT_FAST64_MAX EISDIR ENOENT UINTMAX_MAX SIGSTOP UINT_LEAST32_MAX LDBL_MIN_10_EXP SLONG_MAX SIG_ATOMIC_MIN SIZE_MAX SIGTERM SIGTERM EPERM NULL FOPEN_MAX EMFILE UINT_LEAST64_MAX DBL_MAX SIGFPE SIGFPE INT_LEAST32_MIN SIGPIPE SINT_MAX SHRT_MAX __STDC_VERSION__ SIGQUIT UINT16_MAX SSHRT_MIN INT_LEAST64_MIN M_SQRT2 INTPTR_MAX EMSGSIZE DBL_MANT_DIG _IOFBF DBL_MAX_10_EXP stdout SIGUSR2 LC_ALL EMLINK SIGTTOU SIGHUP SIGHUP LDBL_MAX INT_LEAST16_MAX UINT32_MAX __DATE__ FLT_MAX FILENAME_MAX INT_FAST8_MAX BUFSIZ UINT64_MAX EBADMSG INT_MIN UCHAR_MAX LDBL_EPSILON FLT_MIN_10_EXP SIGABRT SIGABRT SIG_ATOMIC_MAX M_E LLONG_MIN UINT_FAST16_MAX ECHILD INT_LEAST32_MAX M_1_PI LDBL_DIG ENOLCK L_tmpnam ENOTTY FLT_DIG SSHRT_MAX INT_LEAST64_MAX EACCES WEOF __LINE__ UINT_LEAST8_MAX __TIME__ CHAR_MIN M_PI_2 _IONBF M_PI_4 __STDC__ UINT_FAST32_MAX FLT_ROUNDS SEEK_SET EBUSY INTMAX_MIN FLT_MAX_10_EXP LC_TIME CLOCKS_PER_SEC ENXIO ERANGE _IOLBF ENODEV EXDEV FLT_MIN_EXP EFAULT M_2_PI WCHAR_MIN LDBL_MAX_EXP DBL_EPSILON ULONG_MAX ENOMEM SIGTRAP UINT_MAX M_LOG2E LLONG_MAX LDBL_MAX_10_EXP SIG_IGN M_SQRT1_2 EDEADLK ENOTEMPTY LC_NUMERIC ENOEXEC INT16_MIN PTRDIFF_MIN ESRCH MB_CUR_MAX RAND_MAX M_LN2 ENFILE INTPTR_MIN EXIT_SUCCESS CHAR_MAX SIGILL SIGILL LONG_MIN INT_LEAST8_MIN SCHAR_MIN SIG_DFL SEEK_CUR SIGTTIN FLT_MAX_EXP EDOM INT32_MIN SIGUSR1 ECANCELED UINT8_MAX EEXIST LDBL_MANT_DIG EAGAIN INT64_MIN WINT_MIN INT_FAST16_MIN LC_CTYPE ENAMETOOLONG EBADF M_LOG10E E2BIG SIGCONT M_2_SQRTPI WCHAR_MAX DBL_MAX_EXP EPIPE SIGTSTP UINTPTR_MAX UINT_FAST64_MAX SIGCHLD INTMAX_MAX EFBIG SIG_ERR INT8_MIN INT16_MAX PTRDIFF_MAX FLT_RADIX DBL_MIN DBL_DIG + links to Constant +cPreCondit xxx start=/^\s*\(%:\|#\)\s*\(if\|ifdef\|ifndef\|elif\)\>/ skip=/\\$/ end=/$/ keepend contains=cComment,cCommentL,cCppString,cCharacter,cCppParen,cParenError,cNumbers,cCommentError,cSpaceError + links to PreCondit +cPreConditMatch xxx match /^\s*\(%:\|#\)\s*\(else\|endif\)\>/ display + links to cPreCondit +cCppInIf xxx matchgroup=cCppInWrapper start=/\d\+/ end=/^\s*\(%:\|#\)\s*endif\>/ contained contains=TOP,cPreCondit +cCppInElse xxx start==^\s*\(%:\|#\)\s*\(else\>\|elif\s\+\(0*[1-9]\d*\s*\($\|//\|/\*\||\)\)\@!\)= end=/.\@=\|$/ contained fold contains=cCppInElse2 containedin=cCppInIf +cCppInElse2 xxx matchgroup=cCppInWrapper start=+^\s*\(%:\|#\)\s*\(else\|elif\)\([^/]\|/[^/*]\)*+ end=/^\s*\(%:\|#\)\s*endif\>/me=s-1 contained contains=cSpaceError,cCppOutSkip + links to cCppOutIf2 +cCppOutIf xxx start=/0\+/ matchgroup=cCppOutWrapper end=/^\s*\(%:\|#\)\s*endif\>/ contained contains=cCppOutIf2,cCppOutElse +cCppOutIf2 xxx matchgroup=cCppOutWrapper start=/0\+/ end==^\s*\(%:\|#\)\s*\(else\>\|elif\s\+\(0\+\s*\($\|//\|/\*\|&\)\)\@!\|endif\>\)=me=s-1 contained fold contains=cSpaceError,cCppOutSkip + links to cCppOut2 +cCppOutElse xxx matchgroup=cCppOutWrapper start=/^\s*\(%:\|#\)\s*\(else\|elif\)/ end=/^\s*\(%:\|#\)\s*endif\>/me=s-1 contained contains=TOP,cPreCondit +cCppInSkip xxx matchgroup=cCppInWrapper start==^\s*\(%:\|#\)\s*\(if\s\+\(\d\+\s*\($\|//\|/\*\||\|&\)\)\@!\|ifdef\>\|ifndef\>\)= skip=/\\$/ end=/^\s*\(%:\|#\)\s*endif\>/ contained contains=TOP,cPreProc containedin=cCppOutElse,cCppInIf,cCppInSkip +cCppOutSkip xxx start=/^\s*\(%:\|#\)\s*\(if\>\|ifdef\>\|ifndef\>\)/ skip=/\\$/ end=/^\s*\(%:\|#\)\s*endif\>/ contained contains=cSpaceError,cCppOutSkip + links to cCppOutIf2 +cCppOutWrapper xxx start==^\s*\(%:\|#\)\s*if\s\+0\+\s*\($\|//\|/\*\|&\)= end=/.\@=\|$/ fold contains=cCppOutIf,cCppOutElse + links to cPreCondit +cCppInWrapper xxx start==^\s*\(%:\|#\)\s*if\s\+0*[1-9]\d*\s*\($\|//\|/\*\||\)= end=/.\@=\|$/ fold contains=cCppInIf,cCppInElse + links to cCppOutWrapper +cPreProc xxx start=/^\s*\(%:\|#\)\s*\(pragma\>\|line\>\|warning\>\|warn\>\|error\>\)/ skip=/\\$/ end=/$/ keepend contains=ALLBUT,@cPreProcGroup,@Spell + links to PreProc +cInclude xxx match /^\s*\(%:\|#\)\s*include\>\s*["<]/ display contains=cIncluded + links to Include +cDefine xxx start=/^\s*\(%:\|#\)\s*\(define\|undef\)\>/ skip=/\\$/ end=/$/ keepend contains=ALLBUT,@cPreProcGroup,@Spell + links to Macro +cMulti xxx start=/?/ skip=/::/ end=/:/ transparent contains=ALLBUT,@cMultiGroup,@Spell +cppStatement xxx this delete using friend new + links to Statement +cppAccess xxx public protected private + links to cppStatement +cppType xxx wchar_t inline explicit virtual export bool + links to Type +cppExceptions xxx catch try throw + links to Exception +cppOperator xxx bitand or compl operator and_eq not_eq xor_eq bitor xor and or_eq not typeid + links to Operator +cppCast xxx match /\<\(const\|static\|dynamic\|reinterpret\)_cast\s*</me=e-1 + match /\<\(const\|static\|dynamic\|reinterpret\)_cast\s*$/ + links to cppStatement +cppStorageClass xxx mutable + links to StorageClass +cppStructure xxx class typename template namespace + links to Structure +cppNumber xxx NPOS + links to Number +cppBoolean xxx true false + links to Boolean +cppMinMax xxx match /[<>]?/ +cCommentGroup cluster=cTodo,cBadContinuation +Spell cluster=NONE +cParenGroup cluster=cParenError,cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cBitField,cOctalZero,@cCppOutInGroup,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom +cCppOutInGroup cluster=cCppInIf,cCppInElse,cCppInElse2,cCppOutIf,cCppOutIf2,cCppOutElse,cCppInSkip,cCppOutSkip +cPreProcGroup cluster=cPreCondit,cIncluded,cInclude,cDefine,cErrInParen,cErrInBracket,cUserLabel,cSpecial,cOctalZero,cCppOutWrapper,cCppInWrapper,@cCppOutInGroup,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cString,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cParen,cBracket,cMulti,cBadBlock +cMultiGroup cluster=cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cBitField,cOctalZero,cCppOutWrapper,cCppInWrapper,@cCppOutInGroup,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cCppParen,cCppBracket,cCppString +cLabelGroup cluster=cUserLabel + diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/java_syntax b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/java_syntax new file mode 100644 index 0000000..595f25d --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/java_syntax @@ -0,0 +1,231 @@ +--- Syntax items --- +htmlValue xxx match /=[\t ]*[^'" \t>][^ \t>]*/hs=s+1 contained contains=javaScriptExpression,@htmlPreproc + links to Normal +cCustomFunc xxx match /\w\+\s*\((\)\@=/ + links to Function +cCustomClass xxx match /\w\+\s*\(::\)\@=/ + links to Function +OperatorChars xxx match #?\|+\|-\|\*\|;\|:\|,\|<\|>\|&\||\|!\|\~\|%\|=\|)\|(\|{\|}\|\.\|\[\|\]\|/\(/\|*\)\@!# +javaFold xxx start=/{/ end=/}/ transparent fold +javaError xxx const goto + match /[\\@`]/ + match +<<<\|\.\.\|=>\|||=\|&&=\|[^-]->\|\*\/+ + links to Error +javaOK xxx match /\.\.\./ +javaError2 xxx match /#\|=</ + links to javaError +javaExternal xxx native package + match /\<import\>\(\s\+static\>\)\?/ + links to Include +javaConditional xxx if else switch + links to Conditional +javaRepeat xxx do for while + links to Repeat +javaBoolean xxx true false + links to Boolean +javaConstant xxx null + links to Constant +javaTypedef xxx this super + match /\.\s*\<class\>/ms=s+1 + links to Typedef +javaOperator xxx new instanceof + links to Operator +javaType xxx float boolean long void double short char byte int + links to Type +javaStatement xxx return + links to Statement +javaStorageClass xxx transient strictfp serializable synchronized static final volatile + links to StorageClass +javaExceptions xxx finally catch try throw + links to Exception +javaAssert xxx assert + links to Statement +javaMethodDecl xxx synchronized throws + links to javaStorageClass +javaClassDecl xxx interface implements enum extends + match /^class\>/ + match /[^.]\s*\<class\>/ms=s+1 + match /@interface\>/ + links to javaStorageClass +javaAnnotation xxx match /@\([_$a-zA-Z][_$a-zA-Z0-9]*\.\)*[_$a-zA-Z][_$a-zA-Z0-9]*\>/ + links to PreProc +javaBranch xxx nextgroup=javaUserLabelRef skipwhite continue + nextgroup=javaUserLabelRef skipwhite break + links to Conditional +javaUserLabelRef xxx match /\k\+/ contained + links to javaUserLabel +javaVarArg xxx match /\.\.\./ + links to Function +javaScopeDecl xxx protected public private abstract + links to javaStorageClass +javaLabel xxx default + links to Label +javaNumber xxx match /\<\(0[0-7]*\|0[xX]\x\+\|\d\+\)[lL]\=\>/ + match /\(\<\d\+\.\d*\|\.\d\+\)\([eE][-+]\=\d\+\)\=[fFdD]\=/ + match /\<\d\+[eE][-+]\=\d\+[fFdD]\=\>/ + match /\<\d\+\([eE][-+]\=\d\+\)\=[fFdD]\>/ + links to Number +javaCharacter xxx match /'[^']*'/ contains=javaSpecialChar,javaSpecialCharError + match /'\\''/ contains=javaSpecialChar + match /'[^\\]'/ + links to Character +javaLabelRegion xxx matchgroup=javaLabel start=/\<case\>/ matchgroup=NONE end=/:/ transparent contains=javaNumber,javaCharacter +javaUserLabel xxx match /^\s*[_$a-zA-Z][_$a-zA-Z0-9_]*\s*:/he=e-1 contains=javaLabel + links to Label +javaTodo xxx contained TODO XXX FIXME + links to Todo +javaSpecial xxx match /\\u\d\{4\}/ + links to Special +javaCommentStar xxx match +^\s*\*[^/]+me=e-1 contained + match /^\s*\*$/ contained + links to javaComment +javaSpecialChar xxx match /\\\([4-9]\d\|[0-3]\d\d\|[\"\\'ntbrf]\|u\x\{4\}\)/ contained + links to SpecialChar +javaComment xxx start=+/\*+ end=+\*/+ contains=@javaCommentSpecial,javaTodo,@Spell + match +/\*\*/+ + links to Comment +javaLineComment xxx match +//.*+ contains=@javaCommentSpecial2,javaTodo,@Spell + links to Comment +javaString xxx start=/"/ end=/$/ end=/"/ contains=javaSpecialChar,javaSpecialError,@Spell + links to String +htmlError xxx match /[<>&]/ contained + links to Error +htmlSpecialChar xxx match /&#\=[0-9A-Za-z]\{1,8};/ contained + links to Special +htmlString xxx start=/"/ end=/"/ contained contains=htmlSpecialChar,javaScriptExpression,@htmlPreproc + start=/'/ end=/'/ contained contains=htmlSpecialChar,javaScriptExpression,@htmlPreproc + links to String +htmlTagN xxx match /<\s*[-a-zA-Z0-9]\+/hs=s+1 contained contains=htmlTagName,htmlSpecialTagName,@htmlTagNameCluster + match =</\s*[-a-zA-Z0-9]\+=hs=s+2 contained contains=htmlTagName,htmlSpecialTagName,@htmlTagNameCluster +htmlTagError xxx match /[^>]</ms=s+1 contained + links to htmlError +htmlEndTag xxx start=+</+ end=/>/ contained contains=htmlTagN,htmlTagError + links to Identifier +htmlArg xxx contained below color name gutter span classid alt marginheight target rows bgcolor ismap cellspacing object codetype frame noshade data for bordercolor clip rowspan defer cellpadding shape usemap rules multiple start selected language summary hspace lowsrc type valign hreflang noresize scheme + contained class visibility checked pagex pagey headers scrolling clear charset id id declare codebase tabindex standby version link accept coords alink background vspace wrap profile width compact marginwidth above content border top maxlength prompt dir value charoff height longdesc nowrap + contained accesskey cols cite rel rev style method size src axis vlink valuetype colspan nohref face lang frameborder enctype readonly action left text url char align scope code disabled abbr datetime archive + match /\<\(http-equiv\|href\|title\)=/me=e-1 contained + match /\<z-index\>/ contained + match /\<\(accept-charset\|label\)\>/ contained + links to Type +htmlTag xxx start=+<[^/]+ end=/>/ contained fold contains=htmlTagN,htmlString,htmlArg,htmlValue,htmlTagError,htmlEvent,htmlCssDefinition,@htmlPreproc,@htmlArgCluster + links to Function +htmlTagName xxx contained marquee span ol thead pre blink tbody a p q s object legend frame acronym noframes blockquote var table input hr button bdo font caption sub del sup col basefont xmp iframe dfn html meta nobr fieldset optgroup option applet link area map li td th tr tt param center address small frameset + contained label ul dir div kbd cite big layer form textarea base tfoot br strike samp select menu colgroup img nolayer spacer ilayer code abbr isindex dd ins dl dt noscript + match /\<\(b\|i\|u\|h[1-6]\|em\|strong\|head\|body\|title\)\>/ contained + links to htmlStatement +htmlSpecialTagName xxx contained script style + links to Exception +htmlCommentPart xxx start=/--/ end=/--\s*/ contained contains=@htmlPreproc,@Spell + links to Comment +htmlCommentError xxx match /[^><!]/ contained + links to htmlError +htmlComment xxx start=/<!/ end=/>/ contained contains=htmlCommentPart,htmlCommentError,@Spell + start=/<!DOCTYPE/ end=/>/ contained keepend + links to Comment +htmlPreStmt xxx match /<!--#\(config\|echo\|exec\|fsize\|flastmod\|include\|printenv\|set\|if\|elif\|else\|endif\|geoguide\)\>/ contained + links to PreProc +htmlPreError xxx match /<!--#\S*/ms=s+4 contained + links to Error +htmlPreAttr xxx match /\w\+=[^"]\S\+/ contained contains=htmlPreProcAttrError,htmlPreProcAttrName + start=/\w\+="/ skip=/\\\\\|\\"/ end=/"/ contained keepend contains=htmlPreProcAttrName + links to String +htmlPreProc xxx start=/<!--#/ end=/-->/ contained contains=htmlPreStmt,htmlPreError,htmlPreAttr + links to PreProc +htmlPreProcAttrError xxx match /\w\+=/he=e-1 contained + links to Error +htmlPreProcAttrName xxx match /\(expr\|errmsg\|sizefmt\|timefmt\|var\|cgi\|cmd\|file\|virtual\|value\)=/he=e-1 contained + links to PreProc +htmlLink xxx start=/<a\>\_[^>]*\<href\>/ end=+</a>+me=e-4 contained contains=@Spell,htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLeadingSpace,javaScript,@htmlPreproc + links to Underlined +htmlBoldUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic +htmlBoldItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop,htmlBoldItalicUnderline + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop,htmlBoldItalicUnderline +htmlBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic +htmlBoldUnderlineItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop +htmlBoldItalicUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic + links to htmlBoldUnderlineItalic +htmlUnderlineBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop,htmlUnderlineBoldItalic + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop,htmlUnderlineBoldItalic + links to htmlBoldUnderline +htmlUnderlineItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop,htmlUnderlineItalicBold + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop,htmlUnderlineItalicBold +htmlUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlUnderlineBold,htmlUnderlineItalic +htmlUnderlineBoldItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlUnderlineItalicBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlItalicBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop,htmlItalicBoldUnderline + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop,htmlItalicBoldUnderline + links to htmlBoldItalic +htmlItalicUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlItalicUnderlineBold + links to htmlUnderlineItalic +htmlItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop,htmlItalicBold,htmlItalicUnderline + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop +htmlItalicBoldUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlItalicUnderlineBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlLeadingSpace xxx match /^\s\+/ contained + links to None +htmlH1 xxx start=/<h1\>/ end=+</h1>+me=e-5 contained contains=@htmlTop + links to Title +htmlH2 xxx start=/<h2\>/ end=+</h2>+me=e-5 contained contains=@htmlTop + links to htmlH1 +htmlH3 xxx start=/<h3\>/ end=+</h3>+me=e-5 contained contains=@htmlTop + links to htmlH2 +htmlH4 xxx start=/<h4\>/ end=+</h4>+me=e-5 contained contains=@htmlTop + links to htmlH3 +htmlH5 xxx start=/<h5\>/ end=+</h5>+me=e-5 contained contains=@htmlTop + links to htmlH4 +htmlH6 xxx start=/<h6\>/ end=+</h6>+me=e-5 contained contains=@htmlTop + links to htmlH5 +htmlTitle xxx start=/<title\>/ end=+</title>+me=e-8 contained contains=htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,javaScript,@htmlPreproc + links to Title +htmlHead xxx start=/<head\>/ end=/<h[1-6]\>/me=e-3 end=/<body\>/me=e-5 end=+</head>+me=e-7 contained contains=htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLink,htmlTitle,javaScript,cssStyle,@htmlPreproc + links to PreProc +javaCommentTitle xxx matchgroup=javaDocComment start=+/\*\*+ matchgroup=javaCommentTitle end=+\*/+me=s-1,he=s-1 end=/[^{]@/me=s-2,he=s-1 end=/\.[ \t\r<&]/me=e-1 end=/\.$/ contained keepend contains=@javaHtml,javaCommentStar,javaTodo,@Spell,javaDocTags,javaDocSeeTag + links to SpecialComment +javaDocTags xxx start=/{@\(code\|link\|linkplain\|inherit[Dd]oc\|doc[rR]oot\|value\)/ end=/}/ contained + match /@\(param\|exception\|throws\|since\)\s\+\S\+/ contained contains=javaDocParam + match /@\(version\|author\|return\|deprecated\|serial\|serialField\|serialData\)\>/ contained + links to Special +javaDocSeeTag xxx matchgroup=javaDocTags start=/@see\s\+/ matchgroup=NONE end=/\_./re=e-1 contained contains=javaDocSeeTagParam +javaDocComment xxx start=+/\*\*+ end=+\*/+ keepend contains=javaCommentTitle,@javaHtml,javaDocTags,javaDocSeeTag,javaTodo,@Spell + links to Comment +javaDocParam xxx match /\s\S\+/ contained + links to Function +javaDocSeeTagParam xxx match @"\_[^"]\+"\|<a\s\+\_.\{-}</a>\|\(\k\|\.\)*\(#\k\+\((\_[^)]\+)\)\=\)\=@ contained extend + links to Function +javaSpecialError xxx match /\\./ contained + links to Error +javaSpecialCharError xxx match /[^']/ contained + links to Error +javaParenT1 xxx matchgroup=javaParen1 start=/(/ end=/)/ contained transparent contains=@javaTop,javaParenT2 + matchgroup=javaParen1 start=/\[/ end=/\]/ contained transparent contains=@javaTop,javaParenT2 +javaParenT xxx matchgroup=javaParen start=/(/ end=/)/ transparent contains=@javaTop,javaParenT1 + matchgroup=javaParen start=/\[/ end=/\]/ transparent contains=@javaTop,javaParenT1 +javaParenT2 xxx matchgroup=javaParen2 start=/(/ end=/)/ contained transparent contains=@javaTop,javaParenT + matchgroup=javaParen2 start=/\[/ end=/\]/ contained transparent contains=@javaTop,javaParenT +javaParenError xxx match /)/ + match /\]/ + links to javaError +javaTop cluster=javaError,javaError,javaError,javaError2,javaExternal,javaConditional,javaRepeat,javaBoolean,javaConstant,javaTypedef,javaOperator,javaType,javaType,javaStatement,javaStorageClass,javaExceptions,javaAssert,javaMethodDecl,javaClassDecl,javaClassDecl,javaClassDecl,javaAnnotation,javaBranch,javaVarArg,javaScopeDecl,javaLangObject,javaLabel,javaNumber,javaCharacter,javaLabelRegion,javaUserLabel,javaSpecial,javaComment,javaLineComment,javaString,javaStringError +Spell cluster=NONE +javaCommentSpecial cluster=NONE +javaCommentSpecial2 cluster=NONE +javaHtml cluster=htmlError,htmlSpecialChar,htmlEndTag,htmlTag,htmlComment,htmlPreProc,htmlLink,htmlBold,htmlUnderline,htmlItalic,htmlH1,htmlH2,htmlH3,htmlH4,htmlH5,htmlH6,htmlTitle,htmlHead +htmlPreproc cluster=NONE +htmlArgCluster cluster=NONE +htmlTagNameCluster cluster=NONE +htmlTop cluster=@Spell,htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLink,javaScript,@htmlPreproc +htmlJavaScript cluster=@htmlPreproc +htmlVbScript cluster=NONE +htmlCss cluster=NONE +javaClasses cluster=NONE + diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/php_syntax b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/php_syntax new file mode 100644 index 0000000..10105dc --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/php_syntax @@ -0,0 +1,1862 @@ + + +--- Syntax items --- +htmlValue xxx match /=[\t ]*[^'" \t>][^ \t>]*/hs=s+1 contained contains=javaScriptExpression,@htmlPreproc + links to Normal +trailingWhitespace xxx match /\v\s+%#@<!$/ containedin=ALLBUT,trailingWhitespace,literalTab + match /\v\s+%#@<!$/ contained containedin=ALLBUT,trailingWhitespace,literalTab + match /\v\s+%#@<!$/ contained containedin=ALLBUT,trailingWhitespace,literalTab + match /\v\s+%#@<!$/ contained containedin=ALLBUT,trailingWhitespace,literalTab + links to Todo +literalTab xxx match /\v\t/ containedin=ALL + match /\v\t/ contained containedin=ALL + match /\v\t/ contained containedin=ALL + match /\v\t/ contained containedin=ALL + links to Todo +cCustomFunc xxx match /\w\+\s*\((\)\@=/ + links to Function +cCustomClass xxx match /\w\+\s*\(::\)\@=/ + links to Function +OperatorChars xxx match #?\|+\|-\|\*\|;\|:\|,\|<\|>\|&\||\|!\|\~\|%\|=\|)\|(\|{\|}\|\.\|\[\|\]\|/\(/\|*\)\@!# +htmlTagName xxx contained path hgroup feBlend animateTransform glyphRef altGlyphItem feImage altGlyph embed feOffset glyph g ellipse feMerge symbol details clipPath canvas section view data vkern command altGlyphDef radialGradient bdi output image feSpecularLighting meter filter stop font-face-format header + contained textPath feConvolveMatrix tspan rp rt svg polygon mark font hkern figure datalist feComposite template font-face-name feDisplacementMap feMergeNode circle feSpotLight mask wbr main nav font-face tref line rect foreignObject missing-glyph audio figcaption pattern content video article time + contained footer fePointLight feGaussianBlur defs switch aside feComponentTransfer animate source feFlood set animateMotion linearGradient feTile font-face-uri polyline marker feDiffuseLighting ruby font-face-src dialog menu feDistantLight feTurbulence summary feColorMatrix text color-profile + contained feFuncA feFuncB feFuncG progress feFuncR keygen mpath desc feMorphology track shadow cursor animateColor use + contained marquee a p q s noframes blockquote button caption big meta address form img ilayer ins var fieldset option applet link frameset br dd dl dt noscript bdo tbody nobr cite li strike colgroup acronym select ol blink td th tr tt ul kbd textarea thead table input param center layer base tfoot + contained samp nolayer code font sub sup col optgroup iframe menu object hr span del xmp dfn html legend small dir div abbr isindex pre basefont spacer area map frame label + match /\<[a-z_]\+\(\-[a-z_]\+\)\+\>/ contained + match /\<\(b\|i\|u\|h[1-6]\|em\|strong\|head\|body\|title\)\>/ contained + links to htmlStatement +htmlArg xxx contained accumulate font-stretch font-stretch stdDeviation keySplines color list strikethrough-position clip-path path edgeMode marker-mid maskContentUnits opacity media media onselect local onloadeddata glyphRef onvolumechange scale ondragstart onseeking transform targetX targetY primitiveUnits + contained fx text-anchor v-mathematical onkeypress onmousemove onmousemove direction additive string onsuspend d contenteditable ascent format format glyph-orientation-vertical numOctaves in2 r u x y operator kind srclang name pubdate spreadMethod xlink:href marker-end glyph-orientation-horizontal + contained k onloadstart preserveAspectRatio itemprop xlink:role color-interpolation-filters stitchTiles formtarget orientation placeholder diffuseConstant onforminput azimuth fy onafterprint writing-mode onresize onresize onfocusin onplaying attributeType onzoom alignment-baseline stroke-linecap + contained contextmenu zoomAndPan g1 g2 onreadystatechange ondblclick patternTransform spacing onblur onblur ry ononline itemid tabindex origin ondragover repeatDur dominant-baseline limitingConeAngle intercept method font-variant font-variant onmessage requiredFeatures filter onredo vert-origin-x + contained kernelMatrix step markerUnits 1 slope async ideographic oncanplaythrough offset offset result alphabetic icon controls onended x2 descent onemptied min min onpause type ondrag x1 gradientUnits ondragenter divisor keyPoints v-alphabetic overline-thickness preload stroke-dasharray + contained xlink:type overline-position attributeName from elevation bbox rx formnovalidate font-size-adjust class class externalResourcesRequired visibility accent-height stroke rotate amplitude vert-adv-y viewBox oninput onmouseout onmouseout onerror onerror onerror loop lengthAdjust + contained enable-background fill fill onshow xml:space xml:space radius onabort onabort mathematical onplay k2 contentScriptType onprogress onoffline unicode-bidi word-spacing maskUnits onfocusout charset mode lighting-color stroke-width id id onmouseover onmouseover poster restart in mask + contained fill-opacity is onscroll onscroll formaction underline-thickness v-ideographic markerWidth version oncontextmenu onchange onmousewheel patternUnits clip max max target hanging font-family font-family calcMode arabic-form begin vert-origin-y color-interpolation rendering-intent to onsubmit + contained stroke-opacity pointsAtX pointsAtY pointsAtZ requiredExtensions exponent pathLength onrepeat stroke-linejoin onstalled onfocus onfocus onwaiting z baseline-shift itemtype u2 width oncanplay flood-opacity underline-position xlink:title units-per-em onformchange k1 onpopstate k3 end stemh + contained specularConstant onbeforeprint order stemv label unicode-range onkeyup points oninvalid onmouseup onmouseup text-decoration itemscope onclick onclick dir baseProfile onload onload onload onload onbeforeunload contentStyleType values onactivate specularExponent widths hidden autofocus + contained autofocus cap-height repeatCount onloadedmetadata height translate strikethrough-thickness draggable bias startOffset xlink:actuate xlink:actuate ondrop accesskey systemLanguage xChannelSelector shape-rendering stop-opacity color-rendering clipPathUnits formmethod title title ondragleave + contained panose-1 horiz-origin-y text-rendering glyph-name pointer-events overflow flood-color onhashchange stop-color autoplay xlink:show xlink:show onbegin font-size font-size form letter-spacing filterUnits fill-rule clip-rule refX refY by onkeydown markerHeight stroke-dashoffset xmlns lang + contained lang kernelUnitLength font-style font-style orient open style unicode gradientTransform horiz-adv-x v-hanging preserveAlpha onend onmousedown onmousedown display dur patternContentUnits seed kerning k4 onunload onunload ondragend y1 baseFrequency textLength cx cy dx spellcheck + contained autocomplete x-height font-weight font-weight color-profile ontimeupdate itemref onstorage viewTarget onseeked image-rendering ondurationchange marker-start xml:base xml:base required yChannelSelector track keyTimes filterRes surfaceScale select datetime xml:lang xml:lang cursor + contained stroke-miterlimit onratechange formenctype dy y2 xlink:arcrole tableValues onundo + contained usemap target bgcolor ismap shape language scheme headers content axis noshade style vlink nohref left disabled color classid alt marginheight data cellpadding gutter class scrolling link codebase longdesc rel rev lang datetime archive media noresize start hspace cols hreflang visibility + contained charset id id version width compact border charoff accesskey cite codetype valuetype enctype rows for valign profile value face text bordercolor defer multiple lowsrc pagex pagey checked declare above maxlength nowrap colspan align scope code src cellspacing standby accept coords wrap + contained alink size action prompt type below name object readonly rowspan span selected vspace top dir height frameborder summary char abbr method rules tabindex background clear clip url marginwidth frame + match /\<\(data\(\-[a-z]\+\)\+\)\=\>/ contained + match /\<\(http-equiv\|href\|title\)=/me=e-1 contained + match /\<z-index\>/ contained + match /\<\(accept-charset\|label\)\>/ contained + links to Type +htmlError xxx match /[<>&]/ + links to Error +htmlSpecialChar xxx match /&#\=[0-9A-Za-z]\{1,8};/ + links to Special +javaScriptExpression xxx start=/&{/ end=/};/ contained keepend contains=@htmlJavaScript,@htmlPreproc + links to javaScript +htmlString xxx start=/"/ end=/"/ contained contains=htmlSpecialChar,javaScriptExpression,@htmlPreproc + start=/'/ end=/'/ contained contains=htmlSpecialChar,javaScriptExpression,@htmlPreproc + links to String +htmlTagN xxx match /<\s*[-a-zA-Z0-9]\+/hs=s+1 contained contains=htmlTagName,htmlSpecialTagName,@htmlTagNameCluster + match =</\s*[-a-zA-Z0-9]\+=hs=s+2 contained contains=htmlTagName,htmlSpecialTagName,@htmlTagNameCluster +htmlTagError xxx match /[^>]</ms=s+1 contained + links to htmlError +htmlEndTag xxx start=+</+ end=/>/ contains=htmlTagN,htmlTagError + links to Identifier +htmlEvent xxx start=/\<on\a\+\s*=[\t ]*'/ end=/'/ contained keepend contains=htmlEventSQ + start=/\<on\a\+\s*=[\t ]*"/ end=/"/ contained keepend contains=htmlEventDQ + links to javaScript +htmlCssDefinition xxx matchgroup=htmlArg start=/style="/ matchgroup=htmlString end=/"/ keepend contains=cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssLength,cssColor,cssURL,cssImportant,cssError,cssString,@htmlPreproc + links to Special +htmlTag xxx start=+<[^/]+ end=/>/ fold contains=htmlTagN,htmlString,htmlArg,htmlValue,htmlTagError,htmlEvent,htmlCssDefinition,@htmlPreproc,@htmlArgCluster + links to Function +htmlSpecialTagName xxx contained style script + links to Exception +htmlCommentPart xxx start=/--/ end=/--\s*/ contained contains=@htmlPreproc,@Spell + links to Comment +htmlCommentError xxx match /[^><!]/ contained + links to htmlError +htmlComment xxx start=/<!/ end=/>/ contains=htmlCommentPart,htmlCommentError,@Spell + start=/<!DOCTYPE/ end=/>/ keepend + links to Comment +htmlPreStmt xxx match /<!--#\(config\|echo\|exec\|fsize\|flastmod\|include\|printenv\|set\|if\|elif\|else\|endif\|geoguide\)\>/ contained + links to PreProc +htmlPreError xxx match /<!--#\S*/ms=s+4 contained + links to Error +htmlPreAttr xxx match /\w\+=[^"]\S\+/ contained contains=htmlPreProcAttrError,htmlPreProcAttrName + start=/\w\+="/ skip=/\\\\\|\\"/ end=/"/ contained keepend contains=htmlPreProcAttrName + links to String +htmlPreProc xxx start=/<!--#/ end=/-->/ contains=htmlPreStmt,htmlPreError,htmlPreAttr + links to PreProc +htmlPreProcAttrError xxx match /\w\+=/he=e-1 contained + links to Error +htmlPreProcAttrName xxx match /\(expr\|errmsg\|sizefmt\|timefmt\|var\|cgi\|cmd\|file\|virtual\|value\)=/he=e-1 contained + links to PreProc +htmlLink xxx start=/<a\>\_[^>]*\<href\>/ end=+</a>+me=e-4 contains=@Spell,htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLeadingSpace,javaScript,@htmlPreproc + links to Underlined +javaScript xxx start=/<script\_[^>]*>/ end=+</script>+me=s-1 keepend contains=@htmlJavaScript,htmlCssStyleComment,htmlScriptTag,@htmlPreproc + start=/<script \_[^>]*language *=\_[^>]*vbscript\_[^>]*>/ end=+</script>+me=s-1 keepend contains=@htmlVbScript,htmlCssStyleComment,htmlScriptTag,@htmlPreproc + links to Special +htmlBoldUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic +htmlBoldItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop,htmlBoldItalicUnderline + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop,htmlBoldItalicUnderline +htmlBold xxx start=/<b\>/ end=+</b>+me=e-4 contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic + start=/<strong\>/ end=+</strong>+me=e-9 contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic +htmlBoldUnderlineItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop +htmlBoldItalicUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic + links to htmlBoldUnderlineItalic +htmlUnderlineBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop,htmlUnderlineBoldItalic + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop,htmlUnderlineBoldItalic + links to htmlBoldUnderline +htmlUnderlineItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop,htmlUnderlineItalicBold + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop,htmlUnderlineItalicBold +htmlUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contains=@htmlTop,htmlUnderlineBold,htmlUnderlineItalic +htmlUnderlineBoldItalic xxx start=/<i\>/ end=+</i>+me=e-4 contained contains=@htmlTop + start=/<em\>/ end=+</em>+me=e-5 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlUnderlineItalicBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlItalicBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop,htmlItalicBoldUnderline + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop,htmlItalicBoldUnderline + links to htmlBoldItalic +htmlItalicUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop,htmlItalicUnderlineBold + links to htmlUnderlineItalic +htmlItalic xxx start=/<i\>/ end=+</i>+me=e-4 contains=@htmlTop,htmlItalicBold,htmlItalicUnderline + start=/<em\>/ end=+</em>+me=e-5 contains=@htmlTop +htmlItalicBoldUnderline xxx start=/<u\>/ end=+</u>+me=e-4 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlItalicUnderlineBold xxx start=/<b\>/ end=+</b>+me=e-4 contained contains=@htmlTop + start=/<strong\>/ end=+</strong>+me=e-9 contained contains=@htmlTop + links to htmlBoldUnderlineItalic +htmlLeadingSpace xxx match /^\s\+/ contained + links to None +htmlH1 xxx start=/<h1\>/ end=+</h1>+me=e-5 contains=@htmlTop + links to Title +htmlH2 xxx start=/<h2\>/ end=+</h2>+me=e-5 contains=@htmlTop + links to htmlH1 +htmlH3 xxx start=/<h3\>/ end=+</h3>+me=e-5 contains=@htmlTop + links to htmlH2 +htmlH4 xxx start=/<h4\>/ end=+</h4>+me=e-5 contains=@htmlTop + links to htmlH3 +htmlH5 xxx start=/<h5\>/ end=+</h5>+me=e-5 contains=@htmlTop + links to htmlH4 +htmlH6 xxx start=/<h6\>/ end=+</h6>+me=e-5 contains=@htmlTop + links to htmlH5 +htmlTitle xxx start=/<title\>/ end=+</title>+me=e-8 contains=htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,javaScript,@htmlPreproc + links to Title +cssStyle xxx start=/<style/ end=+</style>+ keepend contains=@htmlCss,htmlTag,htmlEndTag,htmlCssStyleComment,@htmlPreproc +htmlHead xxx start=/<head\>/ end=/<h[1-6]\>/me=e-3 end=/<body\>/me=e-5 end=+</head>+me=e-7 contains=htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLink,htmlTitle,javaScript,cssStyle,@htmlPreproc + links to PreProc +javaScriptCommentTodo xxx contained tbd todo fixme xxx + links to Todo +javaScriptLineComment xxx match +\/\/.*+ contained contains=@Spell,javaScriptCommentTodo + links to Comment +javaScriptCommentSkip xxx match /^[ \t]*\*\($\|[ \t]\+\)/ contained +javaScriptComment xxx start=+/\*+ end=+\*/+ contained contains=@Spell,javaScriptCommentTodo + links to Comment +javaScriptSpecial xxx match /\\\d\d\d\|\\./ contained + links to Special +javaScriptStringD xxx start=/"/ skip=/\\\\\|\\"/ end=/"\|$/ contained contains=javaScriptSpecial,@htmlPreproc + links to String +javaScriptStringS xxx start=/'/ skip=/\\\\\|\\'/ end=/'\|$/ contained contains=javaScriptSpecial,@htmlPreproc + links to String +javaScriptSpecialCharacter xxx match /'\\.'/ contained + links to javaScriptSpecial +javaScriptNumber xxx match /-\=\<\d\+L\=\>\|0[xX][0-9a-fA-F]\+\>/ contained + links to javaScriptValue +javaScriptRegexpString xxx start=+/[^/*]+me=e-1 skip=+\\\\\|\\/+ end=+/[gim]\{0,2\}\s*[;.,)\]}]+me=e-1 end=+/[gim]\{0,2\}\s*$+ contained oneline contains=@htmlPreproc + links to String +javaScriptConditional xxx contained switch if else + links to Conditional +javaScriptRepeat xxx contained do for while in + links to Repeat +javaScriptBranch xxx contained continue break + links to Conditional +javaScriptOperator xxx contained new typeof instanceof delete + links to Operator +javaScriptType xxx contained number function array string boolean regexp object date + links to Type +javaScriptStatement xxx contained return with + links to Statement +javaScriptBoolean xxx contained false true + links to Boolean +javaScriptNull xxx contained undefined null + links to Keyword +javaScriptIdentifier xxx contained this var arguments let + links to Identifier +javaScriptLabel xxx contained case default + links to Label +javaScriptException xxx contained catch try finally throw + links to Exception +javaScriptMessage xxx contained status confirm prompt alert + links to Keyword +javaScriptGlobal xxx contained window self parent top + links to Keyword +javaScriptMember xxx contained event location document + links to Keyword +javaScriptDeprecated xxx contained unescape escape + links to Exception +javaScriptReserved xxx contained const import enum debugger int implements extends class synchronized final goto static boolean float interface short byte super protected export long public native double package transient private volatile char abstract throws + links to Keyword +javaScriptFunction xxx contained function + links to Function +javaScriptBraces xxx match /[{}\[\]]/ contained + links to Function +javaScriptParens xxx match /[()]/ contained +htmlCssStyleComment xxx match /\(<!--\|-->\)/ contained + links to Comment +htmlScriptTag xxx start=/<script/ end=/>/ contained fold contains=htmlTagN,htmlString,htmlArg,htmlValue,htmlTagError,htmlEvent + links to htmlTag +htmlEventSQ xxx start=/'/ms=s+1 end=/'/me=s-1 contained contains=@htmlJavaScript + links to htmlEvent +htmlEventDQ xxx start=/"/ms=s+1 end=/"/me=s-1 contained contains=@htmlJavaScript + links to htmlEvent +vbConditional xxx contained elseif if case select then else + links to Conditional +vbOperator xxx contained addressof imp mod like and eqv or is to not byref byval xor in + match #[()+.,\-/*=&]# contained + match /[<>]=\=/ contained + match /<>/ contained + match /\s\+_$/ contained + links to Operator +vbBoolean xxx contained false true + links to Boolean +vbConst xxx contained null nothing + links to Constant +vbRepeat xxx contained wend step do to for next until loop while foreach + links to Repeat +vbEvents xxx contained devicequeryremovefailed nodeclick queryclose seriesselected deactivate endrequest pointlabelupdated gotfocus begintrans devmodechange dataarrival splitchange linkclose infomessage dblclick beginrequest afterwritefile expand powerquerysuspend keyup devicearrival displaychanged oncomm + contained heightchanged seriesupdated pointlabelselected itemactivated processingtimeout rollbacktrans buttonlostfocus footnoteselected powersuspend validationerror beforeupdate willchangedata deviceremovecomplete unboundadddata willupdaterows columnclick scroll asyncreadprogress change + contained querycompleted querytimeout validate buttongotfocus axislabelselected decommandremoved retainedproject willassociate rowcurrencychange asyncreadcomplete titleactivated beforecoledit axistitleupdated dataupdated beforeinsert plotactivated visiblerecordchanged keypress settingchanged + contained deconnectionpropertychanged unformat sendcomplete editquery afterlabeledit start plotselected timer configchanged dragover activerowchanged dogetnewfilename chartupdated configchagecancelled requestwritefile footnoteupdated show resultschanged statechanged panelclick objectmove + contained dateclicked dragdrop legendselected deconnectionremoved beforelabeledit mouseup devicequeryremove iniproperties pointlabelactivated exitfocus userevent itemrenamed willdissociate afterclosefile beforedelete closeup connect pathchange committrans itemseletected beforeclick dropdown + contained terminate itemcheck enterfocus rowstatuschanged unload associate querycomplete statusupdate ambientchanged olecompletedrag legendupdated aftercoledit fontchanged format decommandpropertychanged requestchangefilename unboundreaddata done compare buttonclick callbackkeydown afterupdate + contained paint afterremovefile itemclick itemremoved connectionrequest keydown leavecell accesskeypress writeproperties axisupdated axisselected axistitleselected footnoteactivated dissociate onaddnew close editproperty axislabelupdated click afterinsert deviceotherevent oledragdrop buttondropdown + contained disconnect entercell currentrecordchanged chartselected olesetdata seriesactivated titleselected mousemove rowresize beforeloadfile afteraddfile beforeconnect datachanged donepainting linkexecute linknotify changed patternchange formatsize updated sendprogress titleupdated mousedown + contained lostfocus linkerror readproperties axislabelactivated afterchangefilename aftercolupdate selectionchanged repeatedcontrolloaded upclick resize axisactivated olegivefeedback initproperties axistitleactivated applychanges powerstatuschanged paneldblclick repeatedcontrolunloaded itemadded + contained headclick configchangedcancelled activate legendactivated afterdelete initialize queryunload selchange processtag pointactivated buttoncompleted itemreloaded olestartdrag asyncprogress chartactivated beforecolupdate linkopen unboundgetrelativebookmark syscolorschanged pointselected + contained unboundwritedata plotupdated downclick collapse deconnectionadded querychangeconfig powerresume rowcolchange oledragover timechanged nodecheck unbounddeleterow closequery reposition willexecute pointupdated colresize objectevent deviceremovepending coledit hide decommandadded load + links to Special +vbFunction xxx contained clng nper vartype mirr abs doevents isnull space weekdayname msgbox cdate second mid min trim ascb ascw year iif cvdate join ismissing chrb chrw createobject switch loadresstring left int inputbox weekday isempty var eof command now ubound environ leftb lenb tab inputb atn rgb syd ltrim + contained instr avg instrb cint minute fileattr datepart fv error formatdatetime hex timer isobject cvar asc count fix rnd time loadrespicture cdbl imestatus array npv cbyte qbcolor string freefile replace lcase loadresdata strreverse cstr oct lbound seek right sgn timeserial format sin isdate + contained input month getallstrings partition sln chr callbyname ipmt filterfix ucase spc sqr monthname round loadpicture formatcurrency typename dateadd str max rtrim getobject tan sum cos hour dateserial strcomp csng strconv filedatetime day stdevp isnumeric curdir len iserror split timevalue ddb + contained getautoserversettings cverr dir midb isarray exp datediff stdev cbool bof loc lof log ccur date val formatnumber pv getsetting filelen rate cdec choose datevalue pmt formatpercent rightb shell getattr varp ppmt + links to Identifier +vbMethods xxx contained skip createtoolwindow addfromfile getfile movenext folderexists showwhatsthis propertychanged removeaddinfromtoolbar savetoolbar createfolder navigateto add copyfolder getclipstring import paste openquerydef finditem begintrans settext findprevious registerdatabase appendchunk enddoc + contained writeproperty drag readall refresh createrelation expand urlfor establishconnection loadresstring oledrag open captureimage edit editcopy rollbacktrans scale getselection resolvename printreport makereplica gettempname showcolor writetemplate createpreparedstatement whatsthismode + contained printform scroll pastspecialdlg repairdatabase line exists arrange createembed bind nextrecordset createindex randomdatafill rowbookmark startlogging peekdata linkrequest paintpicture savetofile tag execute trace rebind makecompilefile updaterecord removeitem readline ensurevisible rowtop + contained fileexists showsave rowcontaining scalex scaley stop startlabeledit setsize point saveas createdatabase newpage lines createquerydef fetch loadfile circle savetoole1file doverb compactdatabase count deselectall show columnsize loadrespicture fillcache initializelabels getdrive + contained deletecolumnlabels clearstructure linksend findfirst getformat zorder setselection validatecontrols selectall addnew deletelines hittest buildpath colcontaining loadresdata listen editpaste driveexists render movelast files connect findnext value committrans set item createquery + contained refreshlink linkpoke update getselectedpart releaseinstance draw cancelasyncread beginqueryedit removeall goback move deletefile layout onaddinsupdate moveprevious restoretoolbar getbookmark deletefolder addfromstring resync clone insertrows replyall reload openastextstream updatecontrols + contained todefaults onstartupcomplete deleterows cancelupdate showprinter clearfields remove aboutbox find keys export append appendappendchunk getabsolutepathname insert clearselcols copy send openresultset refill insertlines print onconnection writeblanklines newpassword close showfont + contained insertrowlabels pset getvisiblecount getdata write randomfillcolumns getfolder requery signon cls createfield idle randomfillrows extracticon createlink opendatabase addfromtemplate additem cancel addcustom showopen holdfields read reply canpropertychange populatepartial showhelp + contained writeline ondisconnection fetchverbs exportreport selprint customize linkexecute readfromfile getspecialfolder addfromguid accept movefile gettext insertfile goforward addtoolboxprogid deleterowlabels save readproperty createpropery setdata size deletecolumns clearsel cut addfile delete + contained openrecordset typebycharttype movefolder openurl setfocus skipline split setviewport signoff replaceline textwidth span selectpart resetcustomlabel addtoaddintoolbar popupmenu creategroup synchronize getfilename getheader insertcolumnlabels textheight activate rollback cancelbatch + contained savefile getchunk rdocreateenvironment getlinefromchar play getdrivename rdoregisterdatasource updaterow forward movedata getrows createtextfile logevent makecompiledfile collapseall insertobjdlg findlast insertcolumns createworkspace splitcontaining copyfile senddata getbasename + contained createtabledef upto setoption celltext createuser designerwindow openconnection copyquerydef quit resetcustom movefirst overlay clear batchupdate cellvalue asyncread createdragimage compose raise twipstochartpart getparentfoldername getnumticks getfirstvisible assert setautoserversettings + contained hide moreresults killdoc + links to PreProc +vbStatement xxx contained const wend mid setattr defint elseif open enum randomize implements end event erase step explicit function option as rem raiseevent do savepicture error call stop preserve reset defbool width sendkeys sendkeys time goto static return on kill for beep defobj exit deletesetting next begin + contained savesetting set unload seek lineinput defdate unlock get lock lset filecopy defsng alias resume onerror declare until base close defstr write deftype sub gosub gosub loop public while redim redim defcur chdir chdrive each defdbl with property type defdec let name private lib foreach + contained deflng dim rmdir mkdir rset date defvar put appactivate load defbyte + links to Statement +vbKeyword xxx contained empty publicnotcreateable mid onnewprocesssingleuse globalmultiuse step option as new optional error is time static withevents me on string byref byval set insameprocessmultiuse seek get lock input resume binary paramarray print null nothing friend public property len private date + links to Statement +vbTodo xxx contained todo + links to Todo +vbTypes xxx contained currency empty single string boolean byte variant long double integer object date decimal + links to Type +vbDefine xxx contained vbkeyback vbyesno vbcyan vbcr vbcurrency vbhidden vbkeyf10 vbkeyf11 vbkeyf13 vbkeyf14 vbkeyf15 vbkeyf16 vbfirstfourdays vbmonday vbimeoff vbcalgreg vbinformation vbdesktop vbkeytab dbfloat dbcurrency vbblack vbkeyseparator vbvolume dblong vbwednesday vbimenoop dbsingle vblf vbgreen + contained vbkeynumlock vbkeyhome vbkeypagedown vbno vbarray vbok vbokonly vb3dshadow vbimemodekatakana vbimemodealphafull vbimemodekatakanahalf vbexclamation vbmsgboxrtlreading vbkeydivide vbkeydown vbsystem vbthursday vbwindowbackground vb3dlight vbretrycancel vbkeyright vbsystemmodal vbfirstjan1 + contained dbchar vbkeypause vbyes vbsingle vbvariant vbabort vbformfeed vbmenubar vbdataobject vbsaturday vbkeydecimal vbhighlighttext vbalias vbkeylbutton vbscrollbars vbimemodealpha vbgraytext vbwindowtext vbinfotext vbfirstfullweek vbkeyselect vbkeysnapshot vbkeyreturn vbnormalnofocus vbback + contained vbmagenta vbkeyprint vbnarrow vbkey6 vbkeyrbutton vbkeydelete dbinteger vbapplicationmodal vbcancel vbdefaultbutton2 vbbuttonshadow vblowercase dbdecimal vbbinarycompare vbkeyi vbmsgboxsetforeground vbformmdiform dbbinary vbkeyo vbkeyp vbwindowframe vbkeycapital vbkeyadd vbkatakana + contained vbkeyf12 vbstring vbverticaltab vbformcode vbignore vberror vbquestion vbbyte vbkeypageup vbimemodehiragana vbfriday vbred dbmemo dbboolean vbretry vbmenutext vbwide vbimedisable vbimemodeoff vbinactivetitlebar vbkeyinsert vbokcancel vbmsgboxright vbkeyend vbkey0 vbkey1 vbkey2 vbkey3 + contained vbkey4 vbkey5 vbkey7 vbkey8 vbkey9 vbkeya vbkeyb vbkeyc vbkeyd vbkeye vbkeyf vbkeyg vbkeyh vbkeyj vbkeyk vbkeyl vbkeym vbkeyn vbkeyq vbkeyr vbkeys vbkeyt vbkeyu vbkeyv vbkeyw vbkeyx vbkeyy vbkeyz vbwhite vbnormal vbinactiveborder dbdate vbformcontrolmenu vbkeymenu vbkeyexecute + contained vbyesnocancel vbtitlebartext vbtextcompare dbdouble vbunicode vbnull vbimekatakanasng vbkeymultiply vbinteger vbkeysubtract vbkeyshift vbmsgboxhelpbutton vbkeycancel vbimemodehangulfull vb3dhighlight dbnumeric vbminimizednofocus dbguid vbdecimal vbcrlf vbsunday vbimealphasng + contained vbminimizedfocus vbapplicationworkspace vbimemodedisable vbkeyescape vbobjecterror vbimemodenocontrol vbtuesday vbkeyclear vbcritical vbusesystem vbkeyhelp vbkeyleft vbnormalfocus dblongbinary vbhiragana vbfromunicode vbcalhijri vbboolean vbkeycontrol vbmsgboxtext vbnullchar + contained vbinfobackground vbactiveborder dbtime vb3ddkshadow vbimeon vbkeyf1 vbkeyf2 vbkeyf3 vbkeyf4 vbkeyf5 vbkeyf6 vbkeyf7 vbkeyf8 vbkeyf9 vbkeynumpad3 vbreadonly vbkeynumpad5 vbkeynumpad0 vbkeynumpad1 vbkeynumpad2 vbkeynumpad4 vbkeynumpad6 vbkeynumpad7 vbkeynumpad8 vbkeynumpad9 vbempty vbdouble + contained vbkeyspace vbappwindows vbimekatakanadbl vbmsgbox vbactivetitlebar vbyellow vbapptaskmanager vbobject vbkeymbutton vbmaximizedfocus dbvarbinary vbimealphadbl vbdatabasecompare vbimehiragana vbusesystemdayofweek vbdate vbhighlight vbpropercase vbdirectory dbtimestamp vbuppercase + contained vbnullstring vbblue vbdefaultbutton1 vbdefaultbutton3 vbdefaultbutton4 vbbuttonface vbimemodehangul vbimemodeon vbbuttontext dbtext vbarchive vbtab dbbyte vblong vbabortretryignore vbinactivecaptiontext vbnewline dbbigint vbkeyup vbhide vb3dface + links to Constant +vbNumber xxx match /\<\d\+\>/ contained + match /\<\d\+\.\d*\>/ contained + match /\.\d\+\>/ contained + links to Number +vbFloat xxx match /[-+]\=\<\d\+[eE][\-+]\=\d\+/ contained + match /[-+]\=\<\d\+\.\d*\([eE][\-+]\=\d\+\)\=/ contained + match /[-+]\=\<\.\d\+\([eE][\-+]\=\d\+\)\=/ contained + links to Float +vbString xxx start=/"/ end=/"\|$/ contained + links to String +vbComment xxx start=/\(^\|\s\)REM\s/ end=/$/ contained contains=vbTodo + start=/\(^\|\s\)\'/ end=/$/ contained contains=vbTodo + links to Comment +vbLineNumber xxx match /^\d\+\(\s\|$\)/ contained + links to Comment +vbTypeSpecifier xxx match /[a-zA-Z0-9][\$%&!#]/ms=s+1 contained + match /#[a-zA-Z0-9]/me=e-1 contained + links to Type +cssTagName xxx contained a a b b p p q q s s u u noframes noframes blockquote blockquote source source source source button button caption caption big big mark mark mark mark meta meta mask mask address address i i article article article article title title style style form form img img img img ins ins meter + contained meter meter meter data data data data var var command command fieldset fieldset option option applet applet nav nav nav nav link link frameset frameset br br track track track track dd dd dl dl dt dt noscript noscript bdo bdo em em canvas canvas canvas canvas section section section + contained section bdi bdi bdi bdi h1 h1 h2 h2 h3 h3 h4 h4 h5 h5 tbody tbody time time time time audio audio audio audio cite cite li li strike strike colgroup colgroup acronym acronym progress progress progress progress select select ol ol embed embed embed embed rtc rtc output output output output + contained wbr wbr wbr wbr rb rb rp rp rp rp datalist datalist datalist datalist template template td td th th tr tr tt tt ul ul kbd kbd textarea textarea menuitem menuitem thead thead rt rt rt rt hgroup hgroup table table input input param param center center base base tfoot tfoot samp samp ruby + contained ruby ruby ruby code code details details font font sub sub sup sup col col svg svg optgroup optgroup figcaption figcaption figcaption figcaption iframe iframe video video video video dialog dialog h6 h6 menu menu script script object object hr hr span span del del dfn dfn html html legend + contained legend small small dir dir div div body body strong strong summary summary keygen keygen keygen keygen abbr abbr isindex isindex figure figure figure figure pre pre basefont basefont header header header header main main main main area area map map frame frame label label footer footer + contained footer footer aside aside aside aside head head + match /\*/ contained + match /\*/ contained + links to Statement +cssDeprecated xxx contained noframes noframes big big applet applet frameset frameset strike strike acronym acronym tt tt center center font font dir dir basefont basefont frame frame + links to Error +cssSelectorOp xxx match /[,>+~]/ contained + match /[,>+~]/ contained + match /[|]/ contained + match /[|]/ contained + links to Special +cssSelectorOp2 xxx match /[~|^$*]\?=/ contained + match /[~|^$*]\?=/ contained + match +/deep/+ contained + match +/deep/+ contained + links to Special +cssUnicodeEscape xxx match /\\\x\{1,6}\s\?/ contained + match /\\\x\{1,6}\s\?/ contained + links to Special +cssStringQ xxx start=/'/ skip=/\\\\\|\\'/ end=/'/ contained contains=cssUnicodeEscape,cssSpecialCharQ + start=/'/ skip=/\\\\\|\\'/ end=/'/ contained contains=cssUnicodeEscape,cssSpecialCharQ + links to String +cssStringQQ xxx start=/"/ skip=/\\\\\|\\"/ end=/"/ contained contains=cssUnicodeEscape,cssSpecialCharQQ + start=/"/ skip=/\\\\\|\\"/ end=/"/ contained contains=cssUnicodeEscape,cssSpecialCharQQ + links to String +cssAttributeSelector xxx matchgroup=cssSelectorOp start=/\[/ end=/]/ contained contains=cssUnicodeEscape,cssSelectorOp2,cssStringQ,cssStringQQ + matchgroup=cssSelectorOp start=/\[/ end=/]/ contained contains=cssUnicodeEscape,cssSelectorOp2,cssStringQ,cssStringQQ + links to String +cssClassNameDot xxx match /\./ contained + match /\./ contained + links to Function +cssClassName xxx match /\.[A-Za-z][A-Za-z0-9_-]\+/ contained contains=cssClassNameDot + match /\.[A-Za-z][A-Za-z0-9_-]\+/ contained contains=cssClassNameDot + links to Function +cssIdentifier xxx match /#[A-Za-z<c0>-<ff>_@][A-Za-z<c0>-<ff>0-9_@-]*/ contained + match /#[A-Za-z<c0>-<ff>_@][A-Za-z<c0>-<ff>0-9_@-]*/ contained + links to Function +cssUnitDecorators xxx match /\(#\|-\|%\|mm\|cm\|in\|pt\|pc\|em\|ex\|px\|rem\|dpi\|dppx\|dpcm\|Hz\|kHz\|s\|ms\|deg\|grad\|rad\)/ contained + match /\(#\|-\|%\|mm\|cm\|in\|pt\|pc\|em\|ex\|px\|rem\|dpi\|dppx\|dpcm\|Hz\|kHz\|s\|ms\|deg\|grad\|rad\)/ contained + links to Number +cssValueInteger xxx match /[-+]\=\d\+/ contained contains=cssUnitDecorators + match /[-+]\=\d\+/ contained contains=cssUnitDecorators + links to Number +cssValueNumber xxx match /[-+]\=\d\+\(\.\d*\)\=/ contained contains=cssUnitDecorators + match /[-+]\=\d\+\(\.\d*\)\=/ contained contains=cssUnitDecorators + match /[01]\(.\d\+\)\=fr/ contained + match /\d\+gd/ contained + match /[-+]\=\d\+\(dB\|st\)/ contained + match /[-+]\=\d\+\(\.\d*\)\=dp\(i\|cm\|px\)/ contained + match /[-+]\=\d\+\(dB\|st\)/ contained + match /[-+]\=\d\+\(\.\d*\)\=dp\(i\|cm\|px\)/ contained + match /[01]\(.\d\+\)\=fr/ contained + match /\d\+gd/ contained + links to Number +cssValueLength xxx match /[-+]\=\d\+\(\.\d*\)\=\(%\|mm\|cm\|in\|pt\|pc\|em\|ex\|px\|rem\|dpi\|dppx\|dpcm\)/ contained contains=cssUnitDecorators + match /[-+]\=\d\+\(\.\d*\)\=\(%\|mm\|cm\|in\|pt\|pc\|em\|ex\|px\|rem\|dpi\|dppx\|dpcm\)/ contained contains=cssUnitDecorators + match /[-+]\=\d\+\(\.\d*\)\=\(ch\|rem\|vw\|vh\|vmin\|vmax\)/ contained + match /[-+]\=\d\+\(\.\d*\)\=\(ch\|rem\|vw\|vh\|vmin\|vmax\)/ contained + links to Number +cssValueAngle xxx match /[-+]\=\d\+\(\.\d*\)\=\(deg\|grad\|rad\)/ contained contains=cssUnitDecorators + match /[-+]\=\d\+\(\.\d*\)\=\(deg\|grad\|rad\)/ contained contains=cssUnitDecorators + match /[-+]\=\d\+\(\.\d*\)\=turn/ contained + match /[-+]\=\d\+\(\.\d*\)\=turn/ contained + links to Number +cssValueTime xxx match /+\=\d\+\(\.\d*\)\=\(ms\|s\)/ contained contains=cssUnitDecorators + match /+\=\d\+\(\.\d*\)\=\(ms\|s\)/ contained contains=cssUnitDecorators + links to Number +cssValueFrequency xxx match /+\=\d\+\(\.\d*\)\=\(Hz\|kHz\)/ contained contains=cssUnitDecorators + match /+\=\d\+\(\.\d*\)\=\(Hz\|kHz\)/ contained contains=cssUnitDecorators + links to Number +cssIncludeKeyword xxx match /@\(-[a-z]+-\)\=\(media\|keyframes\|import\|charset\|namespace\|page\)/ contained + match /@\(-[a-z]+-\)\=\(media\|keyframes\|import\|charset\|namespace\|page\)/ contained + links to atKeyword +cssMediaProp xxx contained orientation orientation width width grid grid height height scan scan + match /\(\(device\)-\)\=aspect-ratio/ contained + match /\(\(max\|min\)-\)\=device-pixel-ratio/ contained + match /\(\(max\|min\)-\)\=device-\(height\|width\)/ contained + match /\(\(max\|min\)-\)\=\(height\|width\|resolution\|monochrome\|color\(-index\)\=\)/ contained + match /\(\(device\)-\)\=aspect-ratio/ contained + match /\(\(max\|min\)-\)\=device-pixel-ratio/ contained + match /\(\(max\|min\)-\)\=device-\(height\|width\)/ contained + match /\(\(max\|min\)-\)\=\(height\|width\|resolution\|monochrome\|color\(-index\)\=\)/ contained + links to cssProp +cssMediaKeyword xxx contained and and not not only only + links to Statement +cssMediaAttr xxx contained interlace interlace portrait portrait progressive progressive landscape landscape + links to cssAttr +cssVendor xxx match /\(-\(webkit\|moz\|o\|ms\)-\)/ contained + match /\(-\(webkit\|moz\|o\|ms\)-\)/ contained + links to Comment +cssMediaType xxx contained all + contained all + contained aural + contained aural + contained tv + contained tv + contained speech + contained speech + contained handheld + contained handheld + contained print + contained print + contained screen + contained screen + contained embossed + contained embossed + contained projection + contained projection + contained braille + contained braille + contained tty + contained tty + links to Special +cssMediaComma xxx match /,/ contained + match /,/ contained + links to Normal +cssComment xxx start=+/\*+ end=+\*/+ contained fold contains=@Spell + start=+/\*+ end=+\*/+ contained fold contains=@Spell + links to Comment +cssMediaBlock xxx matchgroup=cssBraces start=/{/ end=/}/ contained transparent fold contains=cssMediaAttr,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssTagName,cssClassName,cssIdentifier,cssPseudoClass,cssSelectorOp,cssSelectorOp2,cssAttributeSelector + matchgroup=cssBraces start=/{/ end=/}/ contained transparent fold contains=cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssTagName,cssClassName,cssIdentifier,cssPseudoClass,cssSelectorOp,cssSelectorOp2,cssAttributeSelector +cssInclude xxx start=/@media\>/ end=/\ze{/ contained contains=cssMediaProp,cssValueLength,cssMediaKeyword,cssValueInteger,cssMediaAttr,cssVendor,cssMediaType,cssIncludeKeyword,cssMediaComma,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@import\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword,cssURL,cssMediaProp,cssValueLength,cssMediaKeyword,cssValueInteger,cssMediaAttr,cssVendor,cssMediaType + start=/@charset\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword + start=/@namespace\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword + start=/@media\>/ end=/\ze{/ contained contains=cssMediaProp,cssValueLength,cssMediaKeyword,cssValueInteger,cssMediaAttr,cssVendor,cssMediaType,cssIncludeKeyword,cssMediaComma,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@import\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword,cssURL,cssMediaProp,cssValueLength,cssMediaKeyword,cssValueInteger,cssMediaAttr,cssVendor,cssMediaType + start=/@charset\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword + start=/@namespace\>/ end=/\ze;/ contained transparent contains=cssStringQ,cssStringQQ,cssUnicodeEscape,cssComment,cssIncludeKeyword + start=/@counter-style\>/ end=/\ze{/ contained contains=cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssValueInteger,cssValueLength,cssMediaKeyword,cssVendor,cssIncludeKeyword,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@scope\>/ end=/\ze{/ contained nextgroup=cssMediaBlock skipwhite skipnl + start=/@supports\>/ end=/\ze{/ contained contains=cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssValueInteger,cssValueLength,cssMediaKeyword,cssVendor,cssIncludeKeyword,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@supports\>/ end=/\ze{/ contained contains=cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssValueInteger,cssValueLength,cssMediaKeyword,cssVendor,cssIncludeKeyword,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@counter-style\>/ end=/\ze{/ contained contains=cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssValueInteger,cssValueLength,cssMediaKeyword,cssVendor,cssIncludeKeyword,cssComment nextgroup=cssMediaBlock skipwhite skipnl + start=/@scope\>/ end=/\ze{/ contained nextgroup=cssMediaBlock skipwhite skipnl + links to Include +cssBraces xxx match /[{}]/ contained + match /[{}]/ contained + links to Function +cssColor xxx contained GrayText GrayText ThreeDShadow ThreeDShadow ThreeDFace ThreeDFace ButtonHighlight ButtonHighlight Scrollbar Scrollbar ActiveBorder ActiveBorder ThreeDDarkShadow ThreeDDarkShadow ButtonShadow ButtonShadow InfoBackground InfoBackground Highlight Highlight ThreeDLightShadow ThreeDLightShadow + contained Background Background InfoText InfoText CaptionText CaptionText ButtonText ButtonText ThreeDHighlight ThreeDHighlight ButtonFace ButtonFace ActiveCaption ActiveCaption WindowText WindowText HighlightText HighlightText MenuText MenuText InactiveCaptionText InactiveCaptionText Window Window + contained AppWorkspace AppWorkspace WindowFrame WindowFrame Menu Menu InactiveBorder InactiveBorder InactiveCaption InactiveCaption + contained indianred indianred purple purple lavender lavender cyan cyan linen linen cornflowerblue cornflowerblue lemonchiffon lemonchiffon orange orange sienna sienna plum plum moccasin moccasin midnightblue midnightblue cornsilk cornsilk orchid orchid lime lime chartreuse chartreuse teal teal red + contained red deepskyblue deepskyblue peru peru blanchedalmond blanchedalmond thistle thistle aliceblue aliceblue pink pink black black silver silver papayawhip papayawhip blue blue maroon maroon slategray slategray gainsboro gainsboro chocolate chocolate indigo indigo bisque bisque gray gray olive + contained olive ivory ivory antiquewhite antiquewhite cadetblue cadetblue coral coral seagreen seagreen firebrick firebrick aquamarine aquamarine olivedrab olivedrab azure azure rosybrown rosybrown tomato tomato khaki khaki dimgray dimgray oldlace oldlace wheat wheat brown brown dimgrey dimgrey + contained crimson crimson peachpuff peachpuff springgreen springgreen burlywood burlywood goldenrod goldenrod grey grey tan tan hotpink hotpink mintcream mintcream magenta magenta yellowgreen yellowgreen ghostwhite ghostwhite sandybrown sandybrown floralwhite floralwhite slateblue slateblue + contained royalblue royalblue salmon salmon yellow yellow blueviolet blueviolet aqua aqua limegreen limegreen gold gold snow snow turquoise turquoise deeppink deeppink skyblue skyblue slategrey slategrey fuchsia fuchsia powderblue powderblue seashell seashell navy navy whitesmoke whitesmoke green + contained green beige beige greenyellow greenyellow lavenderblush lavenderblush violet violet navajowhite navajowhite orangered orangered lawngreen lawngreen saddlebrown saddlebrown steelblue steelblue forestgreen forestgreen honeydew honeydew dodgerblue dodgerblue mistyrose mistyrose + match /dark\(blue\|cyan\|goldenrod\|gray\|green\|grey\|khaki\)/ contained + match /dark\(magenta\|olivegreen\|orange\|orchid\|red\|salmon\|seagreen\)/ contained + match /darkslate\(blue\|gray\|grey\)/ contained + match /dark\(turquoise\|violet\)/ contained + match /light\(blue\|coral\|cyan\|goldenrodyellow\|gray\|green\)/ contained + match /light\(grey\|pink\|salmon\|seagreen\|skyblue\|yellow\)/ contained + match /light\(slategray\|slategrey\|steelblue\)/ contained + match /medium\(aquamarine\|blue\|orchid\|purple\|seagreen\)/ contained + match /medium\(slateblue\|springgreen\|turquoise\|violetred\)/ contained + match /pale\(goldenrod\|green\|turquoise\|violetred\)/ contained + match /\<transparent\>/ contained + match /\<white\>/ contained + match /#[0-9A-Fa-f]\{3\}\>/ contained contains=cssUnitDecorators + match /#[0-9A-Fa-f]\{6\}\>/ contained contains=cssUnitDecorators + match /dark\(blue\|cyan\|goldenrod\|gray\|green\|grey\|khaki\)/ contained + match /dark\(magenta\|olivegreen\|orange\|orchid\|red\|salmon\|seagreen\)/ contained + match /darkslate\(blue\|gray\|grey\)/ contained + match /dark\(turquoise\|violet\)/ contained + match /light\(blue\|coral\|cyan\|goldenrodyellow\|gray\|green\)/ contained + match /light\(grey\|pink\|salmon\|seagreen\|skyblue\|yellow\)/ contained + match /light\(slategray\|slategrey\|steelblue\)/ contained + match /medium\(aquamarine\|blue\|orchid\|purple\|seagreen\)/ contained + match /medium\(slateblue\|springgreen\|turquoise\|violetred\)/ contained + match /pale\(goldenrod\|green\|turquoise\|violetred\)/ contained + match /\<transparent\>/ contained + match /\<white\>/ contained + match /#[0-9A-Fa-f]\{3\}\>/ contained contains=cssUnitDecorators + match /#[0-9A-Fa-f]\{6\}\>/ contained contains=cssUnitDecorators + match /\<currentColor\>/ contained + match /\<currentColor\>/ contained + links to Constant +cssURL xxx matchgroup=cssFunctionName start=/\<url\s*(/ end=/)/ contained oneline extend + matchgroup=cssFunctionName start=/\<url\s*(/ end=/)/ contained oneline extend + links to String +cssImportant xxx match /!\s*important\>/ contained + match /!\s*important\>/ contained + links to Special +cssError xxx match /{@<>/ contained + match /{@<>/ contained + links to Error +cssFunction xxx matchgroup=cssFunctionName start=/\<\(rgb\|clip\|attr\|counter\|rect\|cubic-bezier\|steps\)\s*(/ end=/)/ contained oneline contains=cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma + matchgroup=cssFunctionName start=/\<\(rgba\|hsl\|hsla\|color-stop\|from\|to\)\s*(/ end=/)/ contained oneline contains=cssColor,cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma,cssFunction + matchgroup=cssFunctionName start=/\<\(linear-\|radial-\)\=\gradient\s*(/ end=/)/ contained oneline contains=cssColor,cssValueInteger,cssValueNumber,cssValueLength,cssFunction,cssGradientAttr,cssFunctionComma + matchgroup=cssFunctionName start=/\<\(matrix\(3d\)\=\|scale\(3d\|X\|Y\|Z\)\=\|translate\(3d\|X\|Y\|Z\)\=\|skew\(X\|Y\)\=\|rotate\(3d\|X\|Y\|Z\)\=\|perspective\)\s*(/ end=/)/ contained oneline contains=cssValueInteger,cssValueNumber,cssValueLength,cssValueAngle,cssFunctionComma + matchgroup=cssFunctionName start=/\<\(rgb\|clip\|attr\|counter\|rect\|cubic-bezier\|steps\)\s*(/ end=/)/ contained oneline contains=cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma + matchgroup=cssFunctionName start=/\<\(rgba\|hsl\|hsla\|color-stop\|from\|to\)\s*(/ end=/)/ contained oneline contains=cssColor,cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma,cssFunction + matchgroup=cssFunctionName start=/\<\(linear-\|radial-\)\=\gradient\s*(/ end=/)/ contained oneline contains=cssColor,cssValueInteger,cssValueNumber,cssValueLength,cssFunction,cssGradientAttr,cssFunctionComma + matchgroup=cssFunctionName start=/\<\(matrix\(3d\)\=\|scale\(3d\|X\|Y\|Z\)\=\|translate\(3d\|X\|Y\|Z\)\=\|skew\(X\|Y\)\=\|rotate\(3d\|X\|Y\|Z\)\=\|perspective\)\s*(/ end=/)/ contained oneline contains=cssValueInteger,cssValueNumber,cssValueLength,cssValueAngle,cssFunctionComma + matchgroup=cssFunctionName start=/\<symbols\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(string\|running\|element\|leader\|target-\(counter\|counters\|text\)\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(minmax\|repeat\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<round\(down\|up\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<counters\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(inset\|circle\|ellipse\|polygon\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<var\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(rgba\|hsla\=\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(stylistic\|styleset\|character-variant\|swash\|ornaments\|annotation\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(image\|\(repeating-\)\=\(linear\|radial\)-gradient\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(matrix\(3d\)\=\|translate\(3d\|X\|Y\|Z\)\=\|scale\(3d\|X\|Y\|Z\)\=\|rotate\(3d\|X\|Y\|Z\)\=\|skew\(X\|Y\)\=\|perspective\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(steps\|cubic-bezier\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(calc\|toggle\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(rgba\|hsla\=\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(stylistic\|styleset\|character-variant\|swash\|ornaments\|annotation\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(image\|\(repeating-\)\=\(linear\|radial\)-gradient\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(matrix\(3d\)\=\|translate\(3d\|X\|Y\|Z\)\=\|scale\(3d\|X\|Y\|Z\)\=\|rotate\(3d\|X\|Y\|Z\)\=\|skew\(X\|Y\)\=\|perspective\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(steps\|cubic-bezier\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(calc\|toggle\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<symbols\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(string\|running\|element\|leader\|target-\(counter\|counters\|text\)\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(minmax\|repeat\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<round\(down\|up\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<counters\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<\(inset\|circle\|ellipse\|polygon\)\s*(/ end=/)/ contained oneline keepend + matchgroup=cssFunctionName start=/\<var\s*(/ end=/)/ contained oneline keepend + links to Constant +cssDefinition xxx matchgroup=cssBraces start=/{/ end=/}/ contained keepend transparent fold contains=cssAttrRegion,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks + matchgroup=cssBraces start=/{/ end=/}/ contained keepend transparent fold contains=cssAttrRegion,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks,@cssColors + matchgroup=cssBraces start=/{/ end=/}/ contained keepend transparent fold contains=cssAttrRegion,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks + matchgroup=cssBraces start=/{/ end=/}/ contained keepend transparent fold contains=cssAttrRegion,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks,@cssColors + matchgroup=cssBraces start=/{/ end=/}/ contained keepend transparent fold contains=cssAttrRegion,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks,@cssColors,@cssColors +cssPseudoClass xxx match /:[A-Za-z0-9_-]*/ contained contains=cssNoise,cssPseudoClassId,cssUnicodeEscape,cssVendor,cssPseudoClassFn + match /:[A-Za-z0-9_-]*/ contained contains=cssNoise,cssPseudoClassId,cssUnicodeEscape,cssVendor,cssPseudoClassFn +cssPagePseudo xxx match /:\(left\|right\|first\|blank\)/ contained + match /:\(left\|right\|first\|blank\)/ contained + links to PreProc +cssPageWrap xxx matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssPageMargin,cssPageProp,cssAttrRegion,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks + matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssPageMargin,cssPageProp,cssAttrRegion,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,cssVendor,cssDefinition,cssHacks +cssPage xxx match /@page\>[^{]*{\@=/ contained transparent contains=cssPagePseudo,cssIncludeKeyword nextgroup=cssPageWrap skipwhite skipnl + match /@page\>[^{]*{\@=/ contained transparent contains=cssPagePseudo,cssIncludeKeyword nextgroup=cssPageWrap skipwhite skipnl + links to atKeyword +cssPageMargin xxx match /@\(\(top\|left\|right\|bottom\)-\(left\|center\|right\|middle\|bottom\)\)\(-corner\)\=/ contained nextgroup=cssDefinition skipwhite skipnl + match /@\(\(top\|left\|right\|bottom\)-\(left\|center\|right\|middle\|bottom\)\)\(-corner\)\=/ contained nextgroup=cssDefinition skipwhite skipnl + links to atKeyword +cssPageProp xxx contained content content orphans orphans widows widows size size + links to cssProp +cssAttrRegion xxx start=/:/ end=/;/ contained keepend contains=cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssColor,cssImportant,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFunction,cssStringQQ,cssStringQ,cssURL,cssComment,cssUnicodeEscape,cssVendor,cssError,cssAttrComma,cssNoise + start=/transition\s*:/ end=/;/ contained keepend contains=cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssColor,cssImportant,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFunction,cssStringQQ,cssStringQ,cssURL,cssComment,cssUnicodeEscape,cssVendor,cssError,cssAttrComma,cssNoise + start=/:/ end=/;/ contained keepend contains=cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssColor,cssImportant,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFunction,cssString,cssStringQQ,cssStringQ,cssURL,cssComment,cssUnicodeEscape,cssVendor,cssError,cssAttrComma,cssNoise + start=/transition\s*:/ end=/;/ contained keepend contains=cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssColor,cssImportant,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFunction,cssString,cssStringQQ,cssStringQ,cssURL,cssComment,cssUnicodeEscape,cssVendor,cssError,cssAttrComma,cssNoise +cssHacks xxx match /\(_\|*\)/ contained + match /\(_\|*\)/ contained + links to Comment +cssKeyFrameWrap xxx matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssKeyFrameSelector + matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssKeyFrameSelector +cssKeyFrame xxx match /@\(-[a-z]+-\)\=keyframes\>[^{]*{\@=/ contained transparent contains=cssVendor,cssIncludeKeyword nextgroup=cssKeyFrameWrap skipwhite skipnl + match /@\(-[a-z]+-\)\=keyframes\>[^{]*{\@=/ contained transparent contains=cssVendor,cssIncludeKeyword nextgroup=cssKeyFrameWrap skipwhite skipnl + links to atKeyword +cssKeyFrameSelector xxx match /\(\d*%\|from\|to\)\=/ contained nextgroup=cssDefinition skipwhite skipnl + match /\(\d*%\|from\|to\)\=/ contained nextgroup=cssDefinition skipwhite skipnl + links to Constant +cssFontDescriptorBlock xxx matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssComment,cssError,cssUnicodeEscape,cssFontProp,cssFontAttr,cssCommonAttr,cssStringQ,cssStringQQ,cssFontDescriptorProp,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFontDescriptorFunction,cssUnicodeRange,cssFontDescriptorAttr + matchgroup=cssBraces start=/{/ end=/}/ contained transparent contains=cssComment,cssError,cssUnicodeEscape,cssFontProp,cssFontAttr,cssCommonAttr,cssStringQ,cssStringQQ,cssFontDescriptorProp,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssFontDescriptorFunction,cssUnicodeRange,cssFontDescriptorAttr +cssFontDescriptor xxx match /@font-face\>/ contained nextgroup=cssFontDescriptorBlock skipwhite skipnl + match /@font-face\>/ contained nextgroup=cssFontDescriptorBlock skipwhite skipnl + links to Special +cssFontProp xxx contained all all columns columns order order isolation isolation + match /\<font\(-\(family\|\|feature-settings\|kerning\|language-override\|size\(-adjust\)\=\|stretch\|style\|synthesis\|variant\(-\(alternates\|caps\|east-asian\|ligatures\|numeric\|position\)\)\=\|weight\)\)\=\>/ contained + match /\<font-smooth\>/ contained + match /\<font\(-\(family\|\|feature-settings\|kerning\|language-override\|size\(-adjust\)\=\|stretch\|style\|synthesis\|variant\(-\(alternates\|caps\|east-asian\|ligatures\|numeric\|position\)\)\=\|weight\)\)\=\>/ contained + match /\<font-smooth\>/ contained + match /\<\(mix\|background\)-blend-mode\>/ contained + match /\<display-\(inside\|outside\|extras\|box\)\>/ contained + match /\<flex\(-\(basis\|direction\|flow\|grow\|shrink\|wrap\)\)\=\>/ contained + match /\<grid-template\(-\(columns\|rows\|areas\)\)\=\>/ contained + match /\<grid-auto-\(columns\|rows\|flow\|position\)\>/ contained + match /\<grid-\(row\|column\)\(-\(start\|end\)\)\=\>/ contained + match /\<grid-area\>/ contained + match /\<line-\(grid\|snap\|slack\)/ contained + match /\<box-snap\>/ contained + match /\<clip-\(path\|rule\)\>/ contained + match /\<mask\(-\(image\|mode\|repeat\|position\|clip\|origin\|size\|composite\|type\)\)\=\>/ contained + match /\<mask-border\(-\(source\|mode\|slice\|width\|outset\|repeat\)\)\=\>/ contained + match /\<max-lines\>/ contained + match /\<ruby-\(position\|merge\|align\)/ contained + match /\<shape-\(outside\|image-threshold\|margin\)\>/ contained + match /\<var-[A-Za-z_][A-Za-z0-9_-]\+\>/ contained + match /\<will-change\>/ contained + match /\<text-\(orientation\|combine-horizontal\)\>/ contained + match /\<writing-mode\>/ contained + match /\<\(justify\|align\)-\(self\|content\|items\)\>/ contained + match /\<animation\(-\(name\|duration\|timing-function\|iteration-count\|direction\|play-state\|delay\|fill-mode\)\)\=\>/ contained + match /\<background-\(clip\|origin\|size\)\>/ contained + match /\<border-image\(-\(source\|slice\|width\|outset\|repeat\)\)\=\>/ contained + match /\<border-\(\(top-right\|bottom-right\|bottom-left\|top-left\)-\)\=radius\>/ contained + match /\<box-shadow\>/ contained + match /\<break-\(after\|before\|inside\)\>/ contained + match /\<box-decoration-break\>/ contained + match /\<wrap-\(flow\|through\)\>/ contained + match /\<font-feature-settings\>/ contained + match /\<font-kerning\>/ contained + match /\<font-language-override\>/ contained + match /\<font-synthesis\>/ contained + match /\<font-variant-\(alternates\|caps\|east-asian\|ligatures\|numeric\|position\)\>/ contained + match /\<target\(-\(name\|new\|position\)\)\=\>/ contained + match /\<object-\(fit\|position\)\>/ contained + match /\<image-\(resolution\|orientation\)\>/ contained + match /\<alignment-\(adjust\|baseline\)\>/ contained + match /\<baseline-shift\>/ contained + match /\<dominate-baseline\>/ contained + match /\<drop-initial-\(after-\(adjust\|align\)\|before-\(adjust\|align\)\|size\|value\)\>/ contained + match /\<inline-box-align\>/ contained + match /\<line-stacking\(-\(ruby\|shift\|strategy\)\)\=\>/ contained + match /\<text-height\>/ contained + match /\<marquee-\(direction\|play-count\|speed\|style\)\>/ contained + match /\<column-\(count\|fill\|gap\|rule\(-\(color\|style\|width\)\)\=\|span\|width\)\>/ contained + match /\<presentation-level\>/ contained + match /\<flow-\(into\|from\)\>/ contained + match /\<region-fragment\>/ contained + match /\<backface-visibility\>/ contained + match /\<perspective\(-origin\)\=\>/ contained + match /\<transform\(-\(origin\|style\)\)\=\>/ contained + match /\<transition\(-\(property\|duration\|timing-function\|delay\)\)\=\>/ contained + match /\<\(mix\|background\)-blend-mode\>/ contained + match /\<\(justify\|align\)-\(self\|content\|items\)\>/ contained + match /\<animation\(-\(name\|duration\|timing-function\|iteration-count\|direction\|play-state\|delay\|fill-mode\)\)\=\>/ contained + match /\<background-\(clip\|origin\|size\)\>/ contained + match /\<border-image\(-\(source\|slice\|width\|outset\|repeat\)\)\=\>/ contained + match /\<border-\(\(top-right\|bottom-right\|bottom-left\|top-left\)-\)\=radius\>/ contained + match /\<box-shadow\>/ contained + match /\<break-\(after\|before\|inside\)\>/ contained + match /\<box-decoration-break\>/ contained + match /\<wrap-\(flow\|through\)\>/ contained + match /\<font-feature-settings\>/ contained + match /\<font-kerning\>/ contained + match /\<font-language-override\>/ contained + match /\<font-synthesis\>/ contained + match /\<font-variant-\(alternates\|caps\|east-asian\|ligatures\|numeric\|position\)\>/ contained + match /\<target\(-\(name\|new\|position\)\)\=\>/ contained + match /\<object-\(fit\|position\)\>/ contained + match /\<image-\(resolution\|orientation\)\>/ contained + match /\<alignment-\(adjust\|baseline\)\>/ contained + match /\<baseline-shift\>/ contained + match /\<dominate-baseline\>/ contained + match /\<drop-initial-\(after-\(adjust\|align\)\|before-\(adjust\|align\)\|size\|value\)\>/ contained + match /\<inline-box-align\>/ contained + match /\<line-stacking\(-\(ruby\|shift\|strategy\)\)\=\>/ contained + match /\<text-height\>/ contained + match /\<marquee-\(direction\|play-count\|speed\|style\)\>/ contained + match /\<column-\(count\|fill\|gap\|rule\(-\(color\|style\|width\)\)\=\|span\|width\)\>/ contained + match /\<presentation-level\>/ contained + match /\<flow-\(into\|from\)\>/ contained + match /\<region-fragment\>/ contained + match /\<backface-visibility\>/ contained + match /\<perspective\(-origin\)\=\>/ contained + match /\<transform\(-\(origin\|style\)\)\=\>/ contained + match /\<transition\(-\(property\|duration\|timing-function\|delay\)\)\=\>/ contained + match /\<display-\(inside\|outside\|extras\|box\)\>/ contained + match /\<flex\(-\(basis\|direction\|flow\|grow\|shrink\|wrap\)\)\=\>/ contained + match /\<grid-template\(-\(columns\|rows\|areas\)\)\=\>/ contained + match /\<grid-auto-\(columns\|rows\|flow\|position\)\>/ contained + match /\<grid-\(row\|column\)\(-\(start\|end\)\)\=\>/ contained + match /\<grid-area\>/ contained + match /\<line-\(grid\|snap\|slack\)/ contained + match /\<box-snap\>/ contained + match /\<clip-\(path\|rule\)\>/ contained + match /\<mask\(-\(image\|mode\|repeat\|position\|clip\|origin\|size\|composite\|type\)\)\=\>/ contained + match /\<mask-border\(-\(source\|mode\|slice\|width\|outset\|repeat\)\)\=\>/ contained + match /\<max-lines\>/ contained + match /\<ruby-\(position\|merge\|align\)/ contained + match /\<shape-\(outside\|image-threshold\|margin\)\>/ contained + match /\<var-[A-Za-z_][A-Za-z0-9_-]\+\>/ contained + match /\<will-change\>/ contained + match /\<text-\(orientation\|combine-horizontal\)\>/ contained + match /\<writing-mode\>/ contained + links to cssProp +cssFontAttr xxx contained grande grande space space zapf zapf caption caption add add backwards backwards content content create create geneva geneva color color flat flat arial arial any any contain contain mathematical mathematical mixed mixed maximum maximum flex flex front front tab tab oblique oblique + contained simplified simplified new new new new balance balance jis04 jis04 paused paused york york symbol symbol fantasy fantasy saturation saturation georgia georgia black black times times unset unset palatino palatino monospace monospace row row alpha alpha jis83 jis83 webdings webdings jis90 + contained jis90 stretch stretch ms ms minimum minimum comic comic tahoma tahoma smaller smaller on on rows rows back back icon icon impact impact plaintext plaintext difference difference recto recto dingbats dingbats cover cover italic italic nonzero nonzero wingdings wingdings helvetica helvetica + contained roman roman grid grid off off forwards forwards luminance luminance courier courier local local reverse reverse safe safe contents contents evenodd evenodd multiply multiply infinite infinite clone clone subtract subtract fill fill color-burn color-burn columns columns window window + contained traditional traditional trebuchet trebuchet luminosity luminosity before before exclude exclude same same antiqua antiqua monaco monaco round round true true screen screen snap snap after after unicase unicase unicase unicase wrap wrap central central bolder bolder running running + contained exclusion exclusion menu menu subgrid subgrid cursive cursive hard-light hard-light charcoal charcoal span span alternate alternate ordinal ordinal verdana verdana lighten lighten lighter lighter linotype linotype neue neue forward forward modal modal lucida lucida break break linear + contained linear color-dodge color-dodge fragments fragments increment increment soft-light soft-light isolate isolate slice slice element element slide slide current current overlay overlay unicode unicode bold bold roboto roboto darken darken dense dense intersect intersect gadget gadget hue hue + contained book book verso verso jis78 jis78 larger larger + match /\<small-\(caps\|caption\)\>/ contained + match /\<message-box\>/ contained + match /\<status-bar\>/ contained + match /\<\(x\{1,2\}-\)\=\(large\|small\)\>/ contained + match /\<\(sans-\)\=serif\>/ contained + match /\<\(\(ultra\|extra\|semi\)-\)\=\(condensed\|expanded\)\>/ contained + match /\<\(all-\)\=\(small-\|petite-\|titling-\)caps\>/ contained + match /\<\(subpixel-\)\=\antialiased\>/ contained + match /\<small-\(caps\|caption\)\>/ contained + match /\<message-box\>/ contained + match /\<status-bar\>/ contained + match /\<\(x\{1,2\}-\)\=\(large\|small\)\>/ contained + match /\<\(sans-\)\=serif\>/ contained + match /\<\(\(ultra\|extra\|semi\)-\)\=\(condensed\|expanded\)\>/ contained + match /\<\(all-\)\=\(small-\|petite-\|titling-\)caps\>/ contained + match /\<\(subpixel-\)\=\antialiased\>/ contained + match /\<\(block\|inline\)-level\>/ contained + match /\<inline-list-item\>/ contained + match /\<inline-flex\>/ contained + match /\<\(row\|column\|wrap\)-reverse\>/ contained + match /\<inline-grid\>/ contained + match /\<half-border\>/ contained + match /\<\(fill\|stroke\|view\)-box\>/ contained + match /\<no-clip\>/ contained + match /\<paged-\(x\|y\)\(-controls\)\=\>/ contained + match /\<ruby-\(base\|text\)-container\>/ contained + match /\<inter-character\>/ contained + match /\<margin-box\>/ contained + match /\<scroll-position\>/ contained + match /\<\(upright\|sideways\(-right\|-left\)\=\|use-glyph-orientation\)\>/ contained + match /\<isolate-override\>/ contained + match /\<\(horizontal-tb\|vertical-\(rl\|lr\)\)\>/ contained + match /\<\(self\|flex\)-\(start\|end\)\>/ contained + match /\<space-\(between\|around\|evenly\)\>/ contained + match /\<alternate-reverse\>/ contained + match /\<\(padding\|border\|content\)-box\>/ contained + match /\<\(no-\)\=\(common\|discretionary\|historical\)-ligatures\>/ contained + match /\<\(no-\)\=contextual\>/ contained + match /\<historical-forms\>/ contained + match /\<all-small-caps\>/ contained + match /\<\(all-\)\=petite-caps\>/ contained + match /\<titling-caps\>/ contained + match /\<\(lining\|oldstyle\|proportional\|tabular\)-nums\>/ contained + match /\<\(diagonal\|stacked\)-fractions\>/ contained + match /\<slashed-zero\>/ contained + match /\<proportional-width\>/ contained + match /\<from-image\>/ contained + match /\<scale-down\>/ contained + match /\<\(text-\)\=\(before\|after\)-edge\>/ contained + match /\<use-script\>/ contained + match /\<caps-height\>/ contained + match /\<\(exclude\|include\)-ruby\>/ contained + match /\<\(consider\|disregard\)-shift\>/ contained + match /\<\(\(inline\|block\)-line\|max\|grid\)-height\>/ contained + match /\<\(font\|text\|max\)-size\>/ contained + match /\<marquee-\(line\|block\)\>/ contained + match /\<\(avoid-\)\=column\>/ contained + match /\<\(avoid-\)\=page\>/ contained + match /\<\(avoid-\)\=region\>/ contained + match /\<\(\(min\|max\|fit\)-content\|fill-available\|repudiate-floats\)\>/ contained + match /\<contain-floats\>/ contained + match /\<preserve-3d\>/ contained + match /\<ease\(-\(in\|out\|in-out\)\)\=\>/ contained + match /\<step-\(start\|end\)\>/ contained + match /\<\(self\|flex\)-\(start\|end\)\>/ contained + match /\<space-\(between\|around\|evenly\)\>/ contained + match /\<alternate-reverse\>/ contained + match /\<\(padding\|border\|content\)-box\>/ contained + match /\<\(no-\)\=\(common\|discretionary\|historical\)-ligatures\>/ contained + match /\<\(no-\)\=contextual\>/ contained + match /\<historical-forms\>/ contained + match /\<all-small-caps\>/ contained + match /\<\(all-\)\=petite-caps\>/ contained + match /\<titling-caps\>/ contained + match /\<\(lining\|oldstyle\|proportional\|tabular\)-nums\>/ contained + match /\<\(diagonal\|stacked\)-fractions\>/ contained + match /\<slashed-zero\>/ contained + match /\<proportional-width\>/ contained + match /\<from-image\>/ contained + match /\<scale-down\>/ contained + match /\<\(text-\)\=\(before\|after\)-edge\>/ contained + match /\<use-script\>/ contained + match /\<caps-height\>/ contained + match /\<\(exclude\|include\)-ruby\>/ contained + match /\<\(consider\|disregard\)-shift\>/ contained + match /\<\(\(inline\|block\)-line\|max\|grid\)-height\>/ contained + match /\<\(font\|text\|max\)-size\>/ contained + match /\<marquee-\(line\|block\)\>/ contained + match /\<\(avoid-\)\=column\>/ contained + match /\<\(avoid-\)\=page\>/ contained + match /\<\(avoid-\)\=region\>/ contained + match /\<\(\(min\|max\|fit\)-content\|fill-available\|repudiate-floats\)\>/ contained + match /\<contain-floats\>/ contained + match /\<preserve-3d\>/ contained + match /\<ease\(-\(in\|out\|in-out\)\)\=\>/ contained + match /\<step-\(start\|end\)\>/ contained + match /\<\(block\|inline\)-level\>/ contained + match /\<inline-list-item\>/ contained + match /\<inline-flex\>/ contained + match /\<\(row\|column\|wrap\)-reverse\>/ contained + match /\<inline-grid\>/ contained + match /\<half-border\>/ contained + match /\<\(fill\|stroke\|view\)-box\>/ contained + match /\<no-clip\>/ contained + match /\<paged-\(x\|y\)\(-controls\)\=\>/ contained + match /\<ruby-\(base\|text\)-container\>/ contained + match /\<inter-character\>/ contained + match /\<margin-box\>/ contained + match /\<scroll-position\>/ contained + match /\<\(upright\|sideways\(-right\|-left\)\=\|use-glyph-orientation\)\>/ contained + match /\<isolate-override\>/ contained + match /\<\(horizontal-tb\|vertical-\(rl\|lr\)\)\>/ contained + links to cssAttr +cssCommonAttr xxx contained all all none none stretch stretch initial initial auto auto inherit inherit bottom bottom normal normal visible visible center center top top hidden hidden default default + links to cssAttr +cssFontDescriptorProp xxx contained src src + match /\<unicode-range\>/ contained + match /\<unicode-range\>/ contained + links to cssProp +cssFontDescriptorFunction xxx matchgroup=cssFunctionName start=/\<\(uri\|url\|local\|format\)\s*(/ end=/)/ contained oneline keepend contains=cssStringQ,cssStringQQ + matchgroup=cssFunctionName start=/\<\(uri\|url\|local\|format\)\s*(/ end=/)/ contained oneline keepend contains=cssStringQ,cssStringQQ + links to Constant +cssUnicodeRange xxx match /U+[0-9A-Fa-f?]\+/ contained + match /U+\x\+-\x\+/ contained + match /U+[0-9A-Fa-f?]\+/ contained + match /U+\x\+-\x\+/ contained + links to Constant +cssFontDescriptorAttr xxx contained all all + links to cssAttr +cssFunctionComma xxx match /,/ contained + match /,/ contained + links to Function +cssGradientAttr xxx contained left left at at ellipse ellipse cover cover bottom bottom right right center center top top middle middle + links to cssAttr +cssAnimationProp xxx match /\<animation\(-\(delay\|direction\|duration\|fill-mode\|name\|play-state\|timing-function\|iteration-count\)\)\=\>/ contained + match /\<animation\(-\(delay\|direction\|duration\|fill-mode\|name\|play-state\|timing-function\|iteration-count\)\)\=\>/ contained + links to cssProp +cssAnimationAttr xxx contained both both backwards backwards paused paused forwards forwards reverse reverse running running alternate alternate + match /\<alternate-reverse\>/ contained + match /\<alternate-reverse\>/ contained + links to cssAttr +cssBackgroundProp xxx match /\<background\(-\(attachment\|clip\|color\|image\|origin\|position\|repeat\|size\)\)\=\>/ contained + match /\<background\(-\(attachment\|clip\|color\|image\|origin\|position\|repeat\|size\)\)\=\>/ contained + links to cssProp +cssBackgroundAttr xxx contained space space left left contain contain scroll scroll fixed fixed cover cover bottom bottom right right local local center center round round top top + match /\<no-repeat\>/ contained + match /\<repeat\(-[xy]\)\=\>/ contained + match /\<no-repeat\>/ contained + match /\<repeat\(-[xy]\)\=\>/ contained + links to cssAttr +cssBorderProp xxx match /\<border\(-\(top\|right\|bottom\|left\)\)\=\(-\(width\|color\|style\)\)\=\>/ contained + match /\<border\(-\(top\|bottom\)-\(left\|right\)\)\=-radius\>/ contained + match /\<border-image\(-\(outset\|repeat\|slice\|source\|width\)\)\=\>/ contained + match /\<box-decoration-break\>/ contained + match /\<box-shadow\>/ contained + match /\<border\(-\(top\|right\|bottom\|left\)\)\=\(-\(width\|color\|style\)\)\=\>/ contained + match /\<border\(-\(top\|bottom\)-\(left\|right\)\)\=-radius\>/ contained + match /\<border-image\(-\(outset\|repeat\|slice\|source\|width\)\)\=\>/ contained + match /\<box-decoration-break\>/ contained + match /\<box-shadow\>/ contained + links to cssProp +cssBorderAttr xxx contained space space solid solid thin thin inset inset groove groove stretch stretch thick thick clone clone fill fill round round ridge ridge double double dashed dashed slice slice outset outset dotted dotted medium medium + links to cssAttr +cssBoxProp xxx match /\<padding\(-\(top\|right\|bottom\|left\)\)\=\>/ contained + match /\<margin\(-\(top\|right\|bottom\|left\)\)\=\>/ contained + match /\<overflow\(-\(x\|y\|style\)\)\=\>/ contained + match /\<rotation\(-point\)\=\>/ contained + match /\<padding\(-\(top\|right\|bottom\|left\)\)\=\>/ contained + match /\<margin\(-\(top\|right\|bottom\|left\)\)\=\>/ contained + match /\<overflow\(-\(x\|y\|style\)\)\=\>/ contained + match /\<rotation\(-point\)\=\>/ contained + match /\<overflow-\(style\|x\|y\)\>/ contained + match /\<rotation\(-point\)\=\>/ contained + match /\<overflow-\(style\|x\|y\)\>/ contained + match /\<rotation\(-point\)\=\>/ contained + links to cssProp +cssBoxAttr xxx contained marquee marquee scroll scroll auto auto visible visible panner panner scrollbar scrollbar hidden hidden + match /\<no-\(display\|content\)\>/ contained + match /\<no-\(display\|content\)\>/ contained + match /\<ruby\(-\(base\(-group\)\=\|text\(-group\)\=\)\)\=\>/ contained + match /\<no-\(display\|content\)\>/ contained + match /\<ruby\(-\(base\(-group\)\=\|text\(-group\)\=\)\)\=\>/ contained + match /\<no-\(display\|content\)\>/ contained + links to cssAttr +cssColorProp xxx contained opacity opacity opacity opacity + match /\<color-profile\>/ contained + match /\<rendering-intent\>/ contained + match /\<color-profile\>/ contained + match /\<rendering-intent\>/ contained + links to cssProp +cssDimensionProp xxx contained width width height height + match /\<\(min\|max\)-\(width\|height\)\>/ contained + match /\<\(min\|max\)-\(width\|height\)\>/ contained + links to cssProp +cssFlexibleBoxProp xxx match /\<box-\(align\|direction\|flex\|ordinal-group\|orient\|pack\|shadow\|sizing\)\>/ contained + match /\<box-\(align\|direction\|flex\|ordinal-group\|orient\|pack\|shadow\|sizing\)\>/ contained + links to cssProp +cssFlexibleBoxAttr xxx contained baseline baseline end end single single start start horizontal horizontal mulitple mulitple reverse reverse + match /\<vertical\(-align\)\@!\>/ contained + match /\<\(inline\|block\)-axis\>/ contained + match /\<vertical\(-align\)\@!\>/ contained + match /\<\(inline\|block\)-axis\>/ contained + links to cssAttr +cssMultiColumnProp xxx contained columns columns + match /\<break-\(after\|before\|inside\)\>/ contained + match /\<column-\(count\|fill\|gap\|rule\(-\(color\|style\|width\)\)\=\|span\|width\)\>/ contained + match /\<page\(-break-\(before\|after\|inside\)\)\=\>/ contained + match /\<break-\(after\|before\|inside\)\>/ contained + match /\<column-\(count\|fill\|gap\|rule\(-\(color\|style\|width\)\)\=\|span\|width\)\>/ contained + match /\<page\(-break-\(before\|after\|inside\)\)\=\>/ contained + links to cssProp +cssMultiColumnAttr xxx contained left left column column balance balance always always right right page page avoid avoid medium medium + match /\<avoid-\(page\|column\)\>/ contained + match /\<avoid-\(page\|column\)\>/ contained + links to cssAttr +cssGeneratedContentProp xxx contained system system range range negative negative prefix prefix crop crop pad pad running running quotes quotes suffix suffix fallback fallback + match /\<counter-\(reset\|increment\)\>/ contained + match /\<move-to\>/ contained + match /\<page-policy\>/ contained + match /\<counter-\(reset\|increment\)\>/ contained + match /\<move-to\>/ contained + match /\<page-policy\>/ contained + match /\<\(additive-\)\=symbols\>/ contained + match /\<speak-as\>/ contained + match /\<string-set\>/ contained + match /\<footnote-\(display\|policy\)\>/ contained + match /\<bookmark-\(label\|level\|state\)\>/ contained + match /\<marker-side\>/ contained + match /\<counter-set\>/ contained + match /\<move-to\>/ contained + match /\<page-policy\>/ contained + match /\<move-to\>/ contained + match /\<page-policy\>/ contained + match /\<\(additive-\)\=symbols\>/ contained + match /\<speak-as\>/ contained + match /\<string-set\>/ contained + match /\<footnote-\(display\|policy\)\>/ contained + match /\<bookmark-\(label\|level\|state\)\>/ contained + match /\<marker-side\>/ contained + match /\<counter-set\>/ contained + links to cssProp +cssGeneratedContentAttr xxx contained words words first first open open footnote footnote extends extends here here line line marker marker last last additive additive symbolic symbolic inhibit inhibit bullets bullets numbers numbers closed closed cyclic cyclic + match /\<\(no-\)\=\(open\|close\)-quote\>/ contained + match /\<\(no-\)\=\(open\|close\)-quote\>/ contained + match /\<cjk-decimal\>/ contained + match /\<disclosure-\(open\|closed\)\>/ contained + match /\<simp-chinese-\(in\)\=formal\>/ contained + match /\<trad-chinese-\(in\)\=formal\>/ contained + match /\<ethiopic-numeric\>/ contained + match /\<list-container\>/ contained + match /\<cjk-decimal\>/ contained + match /\<disclosure-\(open\|closed\)\>/ contained + match /\<simp-chinese-\(in\)\=formal\>/ contained + match /\<trad-chinese-\(in\)\=formal\>/ contained + match /\<ethiopic-numeric\>/ contained + match /\<list-container\>/ contained + links to cssAttr +cssGridProp xxx match /\<grid-\(columns\|rows\)\>/ contained + match /\<grid-\(columns\|rows\)\>/ contained + links to cssProp +cssHyerlinkProp xxx match /\<target\(-\(name\|new\|position\)\)\=\>/ contained + match /\<target\(-\(name\|new\|position\)\)\=\>/ contained + links to cssProp +cssListProp xxx match /\<list-style\(-\(type\|position\|image\)\)\=\>/ contained + match /\<list-style\(-\(type\|position\|image\)\)\=\>/ contained + links to cssProp +cssListAttr xxx contained outside outside disc disc hebrew hebrew armenian armenian circle circle inside inside square square georgian georgian + match /\<\(lower\|upper\)-\(roman\|alpha\|greek\|latin\)\>/ contained + match /\<\(hiragana\|katakana\)\(-iroha\)\=\>/ contained + match /\<\(decimal\(-leading-zero\)\=\|cjk-ideographic\)\>/ contained + match /\<\(lower\|upper\)-\(roman\|alpha\|greek\|latin\)\>/ contained + match /\<\(hiragana\|katakana\)\(-iroha\)\=\>/ contained + match /\<\(decimal\(-leading-zero\)\=\|cjk-ideographic\)\>/ contained + links to cssAttr +cssPositioningProp xxx contained display display left left visibility visibility float float bottom bottom right right top top clear clear clip clip position position + match /\<z-index\>/ contained + match /\<z-index\>/ contained + links to cssProp +cssPositioningAttr xxx contained absolute absolute both both left left relative relative compact compact static static fixed fixed block block right right + match /\<table\(-\(row-group\|\(header\|footer\)-group\|row\|column\(-group\)\=\|cell\|caption\)\)\=\>/ contained + match /\<list-item\>/ contained + match /\<inline\(-\(block\|box\|table\)\)\=\>/ contained + match /\<table\(-\(row-group\|\(header\|footer\)-group\|row\|column\(-group\)\=\|cell\|caption\)\)\=\>/ contained + match /\<list-item\>/ contained + match /\<inline\(-\(block\|box\|table\)\)\=\>/ contained + links to cssAttr +cssPrintAttr xxx contained cross cross always always portrait portrait crop crop landscape landscape avoid avoid + links to cssAttr +cssTableProp xxx match /\<\(caption-side\|table-layout\|border-collapse\|border-spacing\|empty-cells\)\>/ contained + match /\<\(caption-side\|table-layout\|border-collapse\|border-spacing\|empty-cells\)\>/ contained + links to cssProp +cssTableAttr xxx contained separate separate show show always always fixed fixed once once collapse collapse hide hide + links to cssAttr +cssTextProp xxx contained direction direction color color hyphens hyphens + match /\<\(\(word\|letter\)-spacing\|text\(-\(decoration\|transform\|align\|index\|shadow\)\)\=\|vertical-align\|unicode-bidi\|line-height\)\>/ contained + match /\<text-\(justify\|outline\|warp\|align-last\|size-adjust\|rendering\|stroke\|indent\)\>/ contained + match /\<word-\(break\|\wrap\)\>/ contained + match /\<white-space\>/ contained + match /\<hanging-punctuation\>/ contained + match /\<punctuation-trim\>/ contained + match /\<\(\(word\|letter\)-spacing\|text\(-\(decoration\|transform\|align\|index\|shadow\)\)\=\|vertical-align\|unicode-bidi\|line-height\)\>/ contained + match /\<text-\(justify\|outline\|warp\|align-last\|size-adjust\|rendering\|stroke\|indent\)\>/ contained + match /\<word-\(break\|\wrap\)\>/ contained + match /\<white-space\>/ contained + match /\<hanging-punctuation\>/ contained + match /\<punctuation-trim\>/ contained + match /\<line-break\>/ contained + match /\<overflow-wrap\>/ contained + match /\<tab-size\>/ contained + match /\<text-\(decoration\(-\(color\|line\|skip\|style\)\)\=\|underline-position\|emphasis\(-\(color\|position\|style\)\)\=\)\>/ contained + match /\<line-break\>/ contained + match /\<overflow-wrap\>/ contained + match /\<tab-size\>/ contained + match /\<text-\(decoration\(-\(color\|line\|skip\|style\)\)\=\|underline-position\|emphasis\(-\(color\|position\|style\)\)\=\)\>/ contained + links to cssProp +cssTextAttr xxx contained baseline baseline optimizespeed optimizespeed loose loose first first ink ink end end hanging hanging optimizelegibility optimizelegibility strict strict start start alphabetic alphabetic last last ellipsis ellipsis overline overline objects objects embed embed blink blink rtl rtl dot dot + contained lowercase lowercase distribute distribute suppress suppress manual manual filled filled super super super super over over nowrap nowrap justify justify under under hyphenate hyphenate sub sub sub sub triangle triangle capitalize capitalize edges edges wavy wavy kashida kashida adjacent + contained adjacent underline underline middle middle unrestricted unrestricted sesame sesame ltr ltr uppercase uppercase clip clip spaces spaces + match /\<line-through\>/ contained + match /\<\(text-\)\=\(top\|bottom\)\>/ contained + match /\<pre\(-\(line\|wrap\)\)\=\>/ contained + match /\<\(allow\|force\)-end\>/ contained + match /\<inter-\(word\|ideographic\|cluster\)\>/ contained + match /\<break-all\>/ contained + match /\<break-word\>/ contained + match /\<bidi-override\>/ contained + match /\<line-through\>/ contained + match /\<\(text-\)\=\(top\|bottom\)\>/ contained + match /\<pre\(-\(line\|wrap\)\)\=\>/ contained + match /\<\(allow\|force\)-end\>/ contained + match /\<inter-\(word\|ideographic\|cluster\)\>/ contained + match /\<break-all\>/ contained + match /\<break-word\>/ contained + match /\<bidi-override\>/ contained + match /\<match-parent\>/ contained + match /\<each-line\>/ contained + match /\<full-width\>/ contained + match /\<box-decoration\>/ contained + match /\<match-parent\>/ contained + match /\<each-line\>/ contained + match /\<full-width\>/ contained + match /\<box-decoration\>/ contained + links to cssAttr +cssTransformProp xxx match /\<transform\(-\(origin\|style\)\)\=\>/ contained + match /\<perspective\(-origin\)\=\>/ contained + match /\<backface-visibility\>/ contained + match /\<transform\(-\(origin\|style\)\)\=\>/ contained + match /\<perspective\(-origin\)\=\>/ contained + match /\<backface-visibility\>/ contained + links to cssProp +cssTransitionProp xxx match /\<transition\(-\(delay\|duration\|property\|timing-function\)\)\=\>/ contained + match /\<transition\(-\(delay\|duration\|property\|timing-function\)\)\=\>/ contained + links to cssProp +cssTransitionAttr xxx match /\<linear\(-gradient\)\@!\>/ contained + match /\<ease\(-\(in-out\|out\|in\)\)\=\>/ contained + match /\<step\(-start\|-end\)\=\>/ contained + match /\<linear\(-gradient\)\@!\>/ contained + match /\<ease\(-\(in-out\|out\|in\)\)\=\>/ contained + match /\<step\(-start\|-end\)\=\>/ contained + links to cssAttr +cssUIProp xxx contained icon icon icon icon cursor cursor appearance appearance resize resize resize resize + match /\<box-sizing\>/ contained + match /\<ime-mode\>/ contained + match /\<nav-\(down\|index\|left\|right\|up\)\=\>/ contained + match /\<outline\(-\(width\|style\|color\|offset\)\)\=\>/ contained + match /\<text-overflow\>/ contained + match /\(tap-highlight-color\|user-select\|touch-callout\)/ contained + match /\<box-sizing\>/ contained + match /\<ime-mode\>/ contained + match /\<nav-\(down\|index\|left\|right\|up\)\=\>/ contained + match /\<outline\(-\(width\|style\|color\|offset\)\)\=\>/ contained + match /\<text-overflow\>/ contained + match /\(tap-highlight-color\|user-select\|touch-callout\)/ contained + match /\<box-sizing\>/ contained + match /\<ime-mode\>/ contained + match /\<nav-\(index\|up\|right\|down\|left\)/ contained + match /\<outline-offset\>/ contained + match /\<text-overflow\>/ contained + match /\<box-sizing\>/ contained + match /\<ime-mode\>/ contained + match /\<nav-\(index\|up\|right\|down\|left\)/ contained + match /\<outline-offset\>/ contained + match /\<text-overflow\>/ contained + links to cssProp +cssUIAttr xxx contained button button both both help help disabled disabled disabled disabled vertical vertical vertical vertical cell cell root root ellipsis ellipsis ellipsis ellipsis pointer pointer progress progress horizontal horizontal horizontal horizontal icon icon invert invert text text move move move + contained move alias alias window window copy copy wait wait document document menu menu field field inactive inactive inactive inactive active active active active crosshair crosshair clip clip clip clip + match /\<\(content\|padding\|border\)\(-box\)\=\>/ contained + match /\<\(\([ns]\=[ew]\=\)\|col\|row\|nesw\|nwse\)-resize\>/ contained + match /\<context-menu\>/ contained + match /\<no-drop\>/ contained + match /\<not-allowed\>/ contained + match /\<all-scroll\>/ contained + match /\<\(vertical-\)\=text\>/ contained + match /\<zoom\(-in\|-out\)\=\>/ contained + match /\(preserve-3d\)/ contained + match /\<\(content\|padding\|border\)\(-box\)\=\>/ contained + match /\<\(\([ns]\=[ew]\=\)\|col\|row\|nesw\|nwse\)-resize\>/ contained + match /\<context-menu\>/ contained + match /\<no-drop\>/ contained + match /\<not-allowed\>/ contained + match /\<all-scroll\>/ contained + match /\<\(vertical-\)\=text\>/ contained + match /\<zoom\(-in\|-out\)\=\>/ contained + match /\(preserve-3d\)/ contained + links to cssAttr +cssIEUIAttr xxx match /\(bicubic\)/ contained + match /\(bicubic\)/ contained + links to cssAttr +cssIEUIProp xxx match /\(interpolation-mode\|zoom\|filter\)/ contained + match /\(interpolation-mode\|zoom\|filter\)/ contained + links to cssProp +cssAuralProp xxx contained volume volume richness richness stress stress during during azimuth azimuth elevation elevation + match /\<\(pause\|cue\)\(-\(before\|after\)\)\=\>/ contained + match /\<\(play-during\|speech-rate\|voice-family\|pitch\(-range\)\=\|speak\(-\(punctuation\|numeral\|header\)\)\=\)\>/ contained + match /\<\(pause\|cue\)\(-\(before\|after\)\)\=\>/ contained + match /\<\(play-during\|speech-rate\|voice-family\|pitch\(-range\)\=\|speak\(-\(punctuation\|numeral\|header\)\)\=\)\>/ contained + match /\<voice-\(volume\|balance\|rate\|pitch\|range\|stress\|duration\)\>/ contained + match /\<rest\(-\(before\|after\)\)\=\>/ contained + match /\<voice-\(volume\|balance\|rate\|pitch\|range\|stress\|duration\)\>/ contained + match /\<rest\(-\(before\|after\)\)\=\>/ contained + links to cssProp +cssAuralAttr xxx contained mix mix rightwards rightwards neutral neutral behind behind moderate moderate silent silent higher higher preserve preserve non non young young faster faster leftwards leftwards female female old old above above continuous continuous code code reduced reduced below below lower lower + contained digits digits slower slower level level child child male male + match /\<\(x-\)\=\(soft\|loud\)\>/ contained + match /\<spell-out\>/ contained + match /\<\(left\|right\)-side\>/ contained + match /\<\(far\|center\)-\(left\|center\|right\)\>/ contained + match /\<\(x-\)\=\(slow\|fast\|low\|high\)\>/ contained + match /\<\(x-\)\=\(soft\|loud\)\>/ contained + match /\<spell-out\>/ contained + match /\<\(left\|right\)-side\>/ contained + match /\<\(far\|center\)-\(left\|center\|right\)\>/ contained + match /\<\(x-\)\=\(slow\|fast\|low\|high\)\>/ contained + match /\<\(literal\|no\)-punctuation\>/ contained + match /\<\(x-\)\=\(weak\|strong\)\>/ contained + match /\<\(literal\|no\)-punctuation\>/ contained + match /\<\(x-\)\=\(weak\|strong\)\>/ contained + links to cssAttr +cssMobileTextProp xxx match /\<text-size-adjust\>/ contained + match /\<text-size-adjust\>/ contained + links to cssProp +cssBraceError xxx match /}/ contained + match /}/ contained + links to Error +cssAttrComma xxx match /,/ contained + match /,/ contained + links to Special +cssNoise xxx match +\(:\|;\|\/\)+ contained + match +\(:\|;\|\/\)+ contained + links to Noise +cssPseudoClassId xxx contained empty empty empty empty target target target target content content left left disabled disabled disabled disabled link link marker marker optional optional root root root root valid valid future future slot slot past past region region blank blank right right invalid invalid invalid + contained invalid checked checked checked checked before before scope scope host host after after required required indeterminate indeterminate active active shadow shadow enabled enabled hover hover visited visited enable enable current current default default + match /\<first-\(line\|letter\)\>/ contained + match /\<\(first\|last\|only\)-\(of-type\|child\)\>/ contained + match /\<selection\>/ contained + match /\<focus\(-inner\)\=\>/ contained + match /\<\(input-\)\=placeholder\>/ contained + match /\<first-\(line\|letter\)\>/ contained + match /\<\(first\|last\|only\)-\(of-type\|child\)\>/ contained + match /\<selection\>/ contained + match /\<focus\(-inner\)\=\>/ contained + match /\<\(input-\)\=placeholder\>/ contained + match /\<footnote-\(call\|marker\)\>/ contained + match /\<\(scope\|host\)-context\>/ contained + match /\<last-\(child\|of-type\)\>/ contained + match /\<first-of-type\>/ contained + match /\<only-\(child\|of-type\)\>/ contained + match /\<\(any\|local\)-link\>/ contained + match /\<read-\(only\|write\)\>/ contained + match /\<placeholder-shown\>/ contained + match /\<\(in\|out-of\)-range\>/ contained + match /\<user-error\>/ contained + match /\<\(active\|valid\|invalid\)-drop-target\>/ contained + match /\<last-\(child\|of-type\)\>/ contained + match /\<first-of-type\>/ contained + match /\<only-\(child\|of-type\)\>/ contained + match /\<footnote-\(call\|marker\)\>/ contained + match /\<\(scope\|host\)-context\>/ contained + match /\<\(any\|local\)-link\>/ contained + match /\<read-\(only\|write\)\>/ contained + match /\<placeholder-shown\>/ contained + match /\<\(in\|out-of\)-range\>/ contained + match /\<user-error\>/ contained + match /\<\(active\|valid\|invalid\)-drop-target\>/ contained + links to PreProc +cssPseudoClassFn xxx matchgroup=cssFunctionName start=/\<\(not\|lang\|\(nth\|nth-last\)-\(of-type\|child\)\)(/ end=/)/ contained + matchgroup=cssFunctionName start=/\<\(not\|lang\|\(nth\|nth-last\)-\(of-type\|child\)\)(/ end=/)/ contained +cssSpecialCharQQ xxx match /\\\\\|\\"/ contained + match /\\\\\|\\"/ contained +cssSpecialCharQ xxx match /\\\\\|\\'/ contained + match /\\\\\|\\'/ contained +cssPseudoClassLang xxx matchgroup=cssPseudoClassId start=/:\(host\)(/ end=/)/ contained oneline + matchgroup=cssPseudoClassId start=/:\(nth\(-last\)\=-\(child\|of-type\)\|not\)(/ end=/)/ contained oneline + matchgroup=cssPseudoClassId start=/:\(matches\|dir\|local-link\|current\|nth\(-last\)\=-\(match\|column\)\|column\)(/ end=/)/ contained oneline + matchgroup=cssPseudoClassId start=/:\(nth\(-last\)\=-\(child\|of-type\)\|not\)(/ end=/)/ contained oneline + matchgroup=cssPseudoClassId start=/:\(host\)(/ end=/)/ contained oneline + matchgroup=cssPseudoClassId start=/:\(matches\|dir\|local-link\|current\|nth\(-last\)\=-\(match\|column\)\|column\)(/ end=/)/ contained oneline + links to Constant +cssColor800000 xxx contained maroon maroon maroon +cssColorff0000 xxx contained red red red +cssColorffA500 xxx contained orange orange orange +cssColorffff00 xxx contained yellow yellow yellow +cssColor808000 xxx contained olive olive olive +cssColor800080 xxx contained purple purple purple +cssColorff00ff xxx contained magenta magenta magenta fuchsia fuchsia fuchsia +cssColorffffff xxx contained white white white +cssColor00ff00 xxx contained lime lime lime +cssColor008000 xxx contained green green green +cssColor000080 xxx contained navy navy navy +cssColor0000ff xxx contained blue blue blue +cssColor00ffff xxx contained cyan cyan cyan aqua aqua aqua +cssColor008080 xxx contained teal teal teal +cssColor000000 xxx contained black black black +cssColorc0c0c0 xxx contained silver silver silver +cssColor808080 xxx contained gray gray gray grey grey grey +cssColorF0F8FF xxx contained aliceblue aliceblue aliceblue +cssColorFAEBD7 xxx contained antiquewhite antiquewhite antiquewhite +cssColor7FFFD4 xxx contained aquamarine aquamarine aquamarine +cssColorF0FFFF xxx contained azure azure azure +cssColorF5F5DC xxx contained beige beige beige +cssColorFFE4C4 xxx contained bisque bisque bisque +cssColorFFEBCD xxx contained blanchedalmond blanchedalmond blanchedalmond +cssColor8A2BE2 xxx contained blueviolet blueviolet blueviolet +cssColorA52A2A xxx contained brown brown brown +cssColorDEB887 xxx contained burlywood burlywood burlywood +cssColor5F9EA0 xxx contained cadetblue cadetblue cadetblue +cssColor7FFF00 xxx contained chartreuse chartreuse chartreuse +cssColorD2691E xxx contained chocolate chocolate chocolate +cssColorFF7F50 xxx contained coral coral coral +cssColor6495ED xxx contained cornflowerblue cornflowerblue cornflowerblue +cssColorFFF8DC xxx contained cornsilk cornsilk cornsilk +cssColorDC143C xxx contained crimson crimson crimson +cssColor00008B xxx contained darkblue darkblue darkblue +cssColor008B8B xxx contained darkcyan darkcyan darkcyan +cssColorB8860B xxx contained darkgoldenrod darkgoldenrod darkgoldenrod +cssColorA9A9A9 xxx contained darkgray darkgray darkgray darkgrey darkgrey darkgrey +cssColor006400 xxx contained darkgreen darkgreen darkgreen +cssColorBDB76B xxx contained darkkhaki darkkhaki darkkhaki +cssColor8B008B xxx contained darkmagenta darkmagenta darkmagenta +cssColor556B2F xxx contained darkolivegreen darkolivegreen darkolivegreen +cssColorFF8C00 xxx contained darkorange darkorange darkorange +cssColor9932CC xxx contained darkorchid darkorchid darkorchid +cssColor8B0000 xxx contained darkred darkred darkred +cssColorE9967A xxx contained darksalmon darksalmon darksalmon +cssColor8FBC8F xxx contained darkseagreen darkseagreen darkseagreen +cssColor483D8B xxx contained darkslateblue darkslateblue darkslateblue +cssColor2F4F4F xxx contained darkslategray darkslategray darkslategray darkslategrey darkslategrey darkslategrey +cssColor00CED1 xxx contained darkturquoise darkturquoise darkturquoise +cssColor9400D3 xxx contained darkviolet darkviolet darkviolet +cssColorFF1493 xxx contained deeppink deeppink deeppink +cssColor00BFFF xxx contained deepskyblue deepskyblue deepskyblue +cssColor696969 xxx contained dimgray dimgray dimgray dimgrey dimgrey dimgrey +cssColor1E90FF xxx contained dodgerblue dodgerblue dodgerblue +cssColorB22222 xxx contained firebrick firebrick firebrick +cssColorFFFAF0 xxx contained floralwhite floralwhite floralwhite +cssColor228B22 xxx contained forestgreen forestgreen forestgreen +cssColorDCDCDC xxx contained gainsboro gainsboro gainsboro +cssColorF8F8FF xxx contained ghostwhite ghostwhite ghostwhite +cssColorFFD700 xxx contained gold gold gold +cssColorDAA520 xxx contained goldenrod goldenrod goldenrod +cssColorADFF2F xxx contained greenyellow greenyellow greenyellow +cssColorF0FFF0 xxx contained honeydew honeydew honeydew +cssColorFF69B4 xxx contained hotpink hotpink hotpink +cssColorCD5C5C xxx contained indianred indianred indianred +cssColor4B0082 xxx contained indigo indigo indigo +cssColorFFFFF0 xxx contained ivory ivory ivory +cssColorF0E68C xxx contained khaki khaki khaki +cssColorE6E6FA xxx contained lavender lavender lavender +cssColorFFF0F5 xxx contained lavenderblush lavenderblush lavenderblush +cssColor7CFC00 xxx contained lawngreen lawngreen lawngreen +cssColorFFFACD xxx contained lemonchiffon lemonchiffon lemonchiffon +cssColorADD8E6 xxx contained lightblue lightblue lightblue +cssColorF08080 xxx contained lightcoral lightcoral lightcoral +cssColorE0FFFF xxx contained lightcyan lightcyan lightcyan +cssColorFAFAD2 xxx contained lightgoldenrodyellow lightgoldenrodyellow lightgoldenrodyellow +cssColorD3D3D3 xxx contained lightgray lightgray lightgray lightgrey lightgrey lightgrey +cssColor90EE90 xxx contained lightgreen lightgreen lightgreen +cssColorFFB6C1 xxx contained lightpink lightpink lightpink +cssColorFFA07A xxx contained lightsalmon lightsalmon lightsalmon +cssColor20B2AA xxx contained lightseagreen lightseagreen lightseagreen +cssColor87CEFA xxx contained lightskyblue lightskyblue lightskyblue +cssColor778899 xxx contained lightslategrey lightslategrey lightslategrey lightslategray lightslategray lightslategray +cssColorB0C4DE xxx contained lightsteelblue lightsteelblue lightsteelblue +cssColorFFFFE0 xxx contained lightyellow lightyellow lightyellow +cssColor32CD32 xxx contained limegreen limegreen limegreen +cssColorFAF0E6 xxx contained linen linen linen +cssColor66CDAA xxx contained mediumaquamarine mediumaquamarine mediumaquamarine +cssColor0000CD xxx contained mediumblue mediumblue mediumblue +cssColorBA55D3 xxx contained mediumorchid mediumorchid mediumorchid +cssColor9370D8 xxx contained mediumpurple mediumpurple mediumpurple +cssColor3CB371 xxx contained mediumseagreen mediumseagreen mediumseagreen +cssColor7B68EE xxx contained mediumslateblue mediumslateblue mediumslateblue +cssColor00FA9A xxx contained mediumspringgreen mediumspringgreen mediumspringgreen +cssColor48D1CC xxx contained mediumturquoise mediumturquoise mediumturquoise +cssColorC71585 xxx contained mediumvioletred mediumvioletred mediumvioletred +cssColor191970 xxx contained midnightblue midnightblue midnightblue +cssColorF5FFFA xxx contained mintcream mintcream mintcream +cssColorFFE4E1 xxx contained mistyrose mistyrose mistyrose +cssColorFFE4B5 xxx contained moccasin moccasin moccasin +cssColorFFDEAD xxx contained navajowhite navajowhite navajowhite +cssColorFDF5E6 xxx contained oldlace oldlace oldlace +cssColor6B8E23 xxx contained olivedrab olivedrab olivedrab +cssColorFF4500 xxx contained orangered orangered orangered +cssColorDA70D6 xxx contained orchid orchid orchid +cssColorEEE8AA xxx contained palegoldenrod palegoldenrod palegoldenrod +cssColor98FB98 xxx contained palegreen palegreen palegreen +cssColorAFEEEE xxx contained paleturquoise paleturquoise paleturquoise +cssColorD87093 xxx contained palevioletred palevioletred palevioletred +cssColorFFEFD5 xxx contained papayawhip papayawhip papayawhip +cssColorFFDAB9 xxx contained peachpuff peachpuff peachpuff +cssColorCD853F xxx contained peru peru peru +cssColorFFC0CB xxx contained pink pink pink +cssColorDDA0DD xxx contained plum plum plum +cssColorB0E0E6 xxx contained powderblue powderblue powderblue +cssColorBC8F8F xxx contained rosybrown rosybrown rosybrown +cssColor4169E1 xxx contained royalblue royalblue royalblue +cssColor8B4513 xxx contained saddlebrown saddlebrown saddlebrown +cssColorFA8072 xxx contained salmon salmon salmon +cssColorF4A460 xxx contained sandybrown sandybrown sandybrown +cssColor2E8B57 xxx contained seagreen seagreen seagreen +cssColorFFF5EE xxx contained seashell seashell seashell +cssColorA0522D xxx contained sienna sienna sienna +cssColor87CEEB xxx contained skyblue skyblue skyblue +cssColor6A5ACD xxx contained slateblue slateblue slateblue +cssColor708090 xxx contained slategray slategray slategray slategrey slategrey slategrey +cssColorFFFAFA xxx contained snow snow snow +cssColor00FF7F xxx contained springgreen springgreen springgreen +cssColor4682B4 xxx contained steelblue steelblue steelblue +cssColorD2B48C xxx contained tan tan tan +cssColorD8BFD8 xxx contained thistle thistle thistle +cssColorFF6347 xxx contained tomato tomato tomato +cssColor40E0D0 xxx contained turquoise turquoise turquoise +cssColorEE82EE xxx contained violet violet violet +cssColorF5DEB3 xxx contained wheat wheat wheat +cssColorF5F5F5 xxx contained whitesmoke whitesmoke whitesmoke +cssColor9ACD32 xxx contained yellowgreen yellowgreen yellowgreen +lessDefinition xxx matchgroup=cssBraces start=/{/ end=/}/ contained transparent fold contains=cssRenderAttr,cssTransformAttr,cssSpeechAttr,cssRubyAttr,cssPagedMediaAttr,cssPaddingAttr,cssMarqueeAttr,cssMarginAttr,cssLineboxAttr,cssHyerlinkAttr,cssGridAttr,cssDimensionAttr,cssContentForPagedMediaAttr,cssAttr,cssAuralAttr,cssIEUIAttr,cssUIAttr,cssTransitionAttr,cssTextAttr,cssTableAttr,cssPrintAttr,cssPositioningAttr,cssListAttr,cssGeneratedContentAttr,cssMultiColumnAttr,cssFlexibleBoxAttr,cssBoxAttr,cssBorderAttr,cssBackgroundAttr,cssAnimationAttr,cssGradientAttr,cssFontDescriptorAttr,cssCommonAttr,cssFontAttr,cssMediaAttr,cssRenderProp,cssSpeechProp,cssRubyProp,cssPrintProp,cssPagedMediaProp,cssMarqueeProp,cssLineboxProp,cssContentForPagedMediaProp,cssProp,cssMobileTextProp,cssAuralProp,cssIEUIProp,cssUIProp,cssTransitionProp,cssTransformProp,cssTextProp,cssTableProp,cssPositioningProp,cssListProp,cssHyerlinkProp,cssGridProp,cssGeneratedContentProp,cssMultiColumnProp,cssFlexibleBoxProp,cssDimensionProp,cssColorProp,cssBoxProp,cssBorderProp,cssBackgroundProp,cssAnimationProp,cssFontDescriptorProp,cssFontProp,cssPageProp,cssMediaProp,cssComment,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,cssColor,cssTagName,cssPseudoClass,cssURL,cssImportant,cssError,cssStringQ,cssStringQQ,cssFunction,cssUnicodeEscape,lessDefinition,lessComment,lessClassChar,lessVariable,lessMixinChar,lessAmpersandChar,lessFunction,lessNestedSelector,@cssColors +lessComment xxx match +//.*$+ contained contains=@Spell + links to Comment +lessVariable xxx match /@[[:alnum:]_-]\+/ contained + match /@[[:alnum:]_-]\+/ contained nextgroup=lessVariableAssignment skipwhite + links to Special +lessMixinChar xxx match /\.[[:alnum:]_-]\@=/ contained nextgroup=lessClass + links to Special +lessAmpersandChar xxx match /&/ contained nextgroup=lessClass,cssPseudoClass + links to Special +lessFunction xxx contained containedin=cssDefinition % + contained containedin=cssDefinition e + contained containedin=cssDefinition mix + contained containedin=cssDefinition luma + contained containedin=cssDefinition greyscale + contained containedin=cssDefinition rgba + contained containedin=cssDefinition average + contained containedin=cssDefinition red + contained containedin=cssDefinition ceil + contained containedin=cssDefinition spin + contained containedin=cssDefinition rgb + contained containedin=cssDefinition fadein + contained containedin=cssDefinition unit + contained containedin=cssDefinition negation + contained containedin=cssDefinition saturation + contained containedin=cssDefinition contrast + contained containedin=cssDefinition blue + contained containedin=cssDefinition fadeout + contained containedin=cssDefinition alpha + contained containedin=cssDefinition desaturate + contained containedin=cssDefinition difference + contained containedin=cssDefinition lightness + contained containedin=cssDefinition multiply + contained containedin=cssDefinition hsla + contained containedin=cssDefinition percentage + contained containedin=cssDefinition softlight + contained containedin=cssDefinition floor + contained containedin=cssDefinition round + contained containedin=cssDefinition screen + contained containedin=cssDefinition hsva + contained containedin=cssDefinition exclusion + contained containedin=cssDefinition saturate + contained containedin=cssDefinition lighten + contained containedin=cssDefinition hardlight + contained containedin=cssDefinition argb + contained containedin=cssDefinition green + contained containedin=cssDefinition escape + contained containedin=cssDefinition overlay + contained containedin=cssDefinition fade + contained containedin=cssDefinition hsl + contained containedin=cssDefinition hsv + contained containedin=cssDefinition darken + contained containedin=cssDefinition hue + links to Function +lessNestedSelector xxx match +[^/]* {+me=e-1 contained contains=cssTagName,cssAttributeSelector,lessAmpersandChar,lessVariable,lessMixinChar,lessFunction,lessNestedProperty +lessVariableAssignment xxx match /:/ contained nextgroup=lessVariableValue skipwhite +lessVariableValue xxx match /.*;/me=e-1 contained contains=lessVariable,lessOperator,lessDefault,cssValueFrequency,cssValueTime,cssValueAngle,cssValueLength,cssValueNumber,cssValueInteger,@cssColors + links to Constant +lessOperator xxx match /+/ contained + match /-/ contained + match +/+ contained + match /*/ contained +lessDefault xxx match /!default/ contained + links to Special +lessNestedProperty xxx match /[[:alnum:]]\+:/me=e-1 contained + links to Type +lessClass xxx match /[[:alnum:]_-]\+/ contained + links to PreProc +lessStyle xxx start=+<style [^>]*type *=[^>]*text/less[^>]*>+ end=+</style>+ keepend contains=@htmlLess,htmlTag,htmlEndTag,htmlCssStyleComment,@htmlPreproc containedin=htmlHead +phpRegion xxx matchgroup=Delimiter start=/<?\(php\)\=/ end=/?>/ keepend contains=@phpClTop +phpRegionSc xxx matchgroup=Delimiter start=/<script language="php">/ end=+</script>+ keepend contains=@phpClTop +sqlSpecial xxx contained false true null + links to Special +sqlKeyword xxx contained add cluster share rowlabel desc end maxextents function into option validate synonym exclusive pctfree as smallint by column start compress if is asc values resource row whenever to nocompress offline return then of on index rows procedure initial for immediate privileges unique begin + contained connect user modify session cursor nowait table identified file trigger order else having loop public exception size with access type view where from using elsif mode rownum check increment online current level decimal default group successful uid + links to sqlSpecial +sqlOperator xxx contained some all like and any exists or not between sysdate prior out in escape minus intersect union distinct + links to sqlStatement +sqlStatement xxx contained create comment execute alter audit noaudit revoke select set grant update lock drop insert truncate explain delete rename rollback analyze savepoint commit + links to Statement +sqlType xxx contained rowid number varray raw boolean varchar2 float varchar long integer char mlslabel date character + links to Type +sqlString xxx start=/"/ skip=/\\\\\|\\"/ end=/"/ contained + start=/'/ skip=/\\\\\|\\'/ end=/'/ contained + links to String +sqlNumber xxx match /-\=\<\d*\.\=[0-9_]\>/ contained + links to Number +sqlTodo xxx contained note todo debug fixme xxx + links to Todo +sqlComment xxx start=+/\*+ end=+\*/+ contained contains=sqlTodo + match /--.*$/ contained contains=sqlTodo + links to Comment +phpEnvVar xxx contained SERVER_SIGNATURE HTTP_USER_AGENT SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE GATEWAY_INTERFACE HTTP_ENCODING SCRIPT_FILENAME SERVER_PORT REQUEST_METHOD SERVER_ADMIN HTTP_ACCEPT_CHARSET REMOTE_PORT HTTP_HOST HTTP_CONNECTION QUERY_STRING HTTP_ACCEPT_LANGUAGE HTTP_REFERER HTTP_ACCEPT + contained DOCUMENT_ROOT REQUEST_URI SCRIPT_NAME PATH_TRANSLATED REMOTE_ADDR + links to Identifier +phpIntVar xxx contained _COOKIE HTTP_ENV_VARS GLOBALS _SERVER _SERVER HTTP_SESSION_VARS _REQUEST HTTP_RAW_POST_DATA _SESSION _GET HTTP_SERVER_VARS PHP_SELF HTTP_GET_VARS HTTP_STATE_VARS _FILES PHP_ERRMSG HTTP_COOKIE_VARS _ENV _POST HTTP_POST_FILES HTTP_POST_VARS + links to Identifier +phpCoreConstant xxx contained E_PARSE E_WARNING PHP_VERSION E_ALL PHP_OUTPUT_HANDLER_CONT PHP_LOCALSTATEDIR PHP_OUTPUT_HANDLER_START E_NOTICE E_USER_ERROR E_CORE_WARNING PHP_SYSCONFDIR E_USER_WARNING PHP_BINDIR DEFAULT_INCLUDE_PATH E_STRICT E_COMPILE_ERROR E_CORE_ERROR PEAR_EXTENSION_DIR E_COMPILE_WARNING E_ERROR + contained PHP_OUTPUT_HANDLER_END PHP_EXTENSION_DIR PHP_OS PHP_LIBDIR PHP_CONFIG_FILE_PATH PHP_DATADIR E_USER_NOTICE PEAR_INSTALL_DIR + links to Constant +phpConstant xxx contained __function__ __line__ __class__ __namespace__ __method__ __dir__ __file__ + links to Constant +phpFunctions xxx contained gzclose yaz_syntax html_entity_decode fbsql_read_blob png2wbmp mssql_init cpdf_set_title gztell fbsql_insert_id empty cpdf_restore mysql_field_type closelog swftext ldap_search curl_errno gmp_div_r mssql_data_seek getmyinode printer_draw_pie mcve_initconn ncurses_getmaxyx defined + contained localeconv socket_set_block is_file dio_close dbmclose array_change_key_case bcscale mysqli_use_result tidy_parse_file dba_sync bzcompress udm_alloc_agent fdf_set_flags ftp_nb_put ncurses_update_panels abs mb_regex_set_options msql_fetch_object stream_context_set_params cpdf_lineto uksort + contained symlink mcve_destroyconn mcal_event_set_class mssql_field_type sqlite_escape_string php_sapi_name ncurses_mvgetch pdf_open mb_convert_variables mssql_fetch_row sql_regcase fsockopen ncurses_slk_refresh imagecolorallocatealpha mcve_setssl ftp_pwd fbsql_autocommit vpopmail_alias_add + contained shm_remove mysqli_info msession_set_array ncurses_move_panel pdf_close_image mailparse_msg_create mysqli_fetch_field_direct mb_ereg_search_getregs pg_tty ccvs_status dbplus_freerlocks hw_getchildcoll get_extension_funcs tidy_get_head mcve_preauth fdf_enum_values yaz_ccl_conf + contained mysqli_get_server_info ora_errorcode ctype_alnum session_id cpdf_set_subject pdf_close_pdi stat mailparse_msg_extract_part_file dbplus_info mysql_list_processes pspell_check mcve_transinqueue dbplus_rcreate sizeof imap_renamemailbox ncurses_pnoutrefresh tidy_get_root stream_get_transports + contained addcslashes imap_fetch_overview mcve_liststats openssl_x509_checkpurpose get_resource_type ibase_timefmt ctype_space imap_set_quota openssl_private_encrypt ifx_prepare chop imagecreatetruecolor hw_insertanchors pdf_set_text_pos udm_crc32 socket_strerror mb_decode_mimeheader xpath_eval + contained quoted_printable_decode session_is_registered msql_fieldlen dbplus_undoprepare ob_get_status mcve_uwait ncurses_keypad mysqli_profiler swf_rotate stream_get_filters posix_ctermid min explode mcve_setssl_files trim hw_getobjectbyqueryobj fopen socket_create_pair pdf_setpolydash + contained pg_lo_unlink imap_get_quotaroot array_pop imagefill printer_select_font ifxus_write_slob ncurses_mouse_trafo imagecopymergegray mysql_error clearstatcache mssql_result ob_get_contents msql_listfields msession_create pg_free_result ini_restore cpdf_closepath_stroke ftp_close getmyuid + contained pg_field_type ftp_get_option ibase_blob_info fstat openssl_pkey_get_private ircg_set_on_die filepro ocicloselob sqlite_fetch_array mime_content_type pg_connection_reset mssql_close imagecreatefromjpeg get_browser sqlite_next array_fill file_exists get_class is_int swf_posround + contained posix_mkfifo yp_err_string mb_regex_encoding imap_clearflag_full mysqli_init ldap_dn2ufn filetype dbx_escape_string mysqli_param_count easter_date fmod sybase_pconnect msql_free_result ocinewcollection ifxus_free_slob join is_double udm_api_version ncurses_bottom_panel fbsql_field_name + contained swf_setfont ncurses_wgetch odbc_exec pdf_get_value imagecolorclosestalpha pg_cancel_query log1p recode_string mcve_setblocking bzread dbase_create ncurses_ungetch swf_translate ora_commit ncurses_init_color sesam_field_name imap_last_error pdf_open_file serialize cpdf_place_inline_image + contained swffill wddx_deserialize ocicollassign ftp_mdtm ncurses_nocbreak ociwritetemporarylob fbsql_result phpinfo preg_split mssql_fetch_batch mcal_event_set_recur_daily pdf_set_horiz_scaling printer_start_page filegroup cpdf_arc imagepsencodefont dbplus_close vpopmail_add_alias_domain_ex + contained stream_get_line ncurses_mvaddchstr ibase_pconnect ncurses_newwin notes_header_info strrpos openssl_x509_read sha1_file com_addref msql_pconnect yaz_wait closedir odbc_field_num mysql_errno udm_add_search_limit mb_send_mail floatval aspell_new pdf_place_pdi_page array_keys fdf_get_flags + contained imagesavealpha dba_insert swf_startsymbol is_readable printer_set_option zend_version jpeg2wbmp pdf_set_border_style ncurses_slk_clear is_object pg_put_line mcrypt_list_modes fdf_get_status strip_tags fbsql_list_fields ftp_systype fbsql_fetch_object pg_affected_rows cpdf_set_creator + contained ncurses_delwin ncurses_new_panel ob_list_handlers imap_errors filepro_fieldname hw_document_bodytag glob pdf_set_info_subject dio_seek strnatcmp ldap_modify hw_document_content ncurses_slk_attroff wddx_packet_end ibase_affected_rows sqlite_fetch_string mcve_transactionbatch + contained pg_fetch_object ociparse ncurses_pair_content imap_headerinfo deaggregate strftime ncurses_attrset pg_host disk_total_space socket_iovec_delete unregister_tick_function mb_ereg_search_init zip_entry_read w32api_deftype ezmlm_hash mysql_num_fields openssl_pkey_export tidy_is_xhtml + contained yaz_set_option gzgetc odbc_execute hw_getobjectbyquerycoll msql_connect ircg_register_format_messages image_type_to_mime_type spliti swf_ortho2 connection_aborted stream_set_write_buffer is_scalar ncurses_flushinp pdf_set_parameter set_include_path dbplus_runlink ncurses_mouseinterval + contained imagefilledpolygon ncurses_panel_window xml_set_character_data_handler vpopmail_auth_user ifx_connect getopt ncurses_mvaddstr stream_get_wrappers hw_insdoc gzuncompress fbsql_select_db get_include_path ctype_upper pcntl_wstopsig fgetcsv swfmovie dbplus_setindexbynumber jddayofweek + contained xmlrpc_server_add_introspection_data fbsql_create_blob odbc_errormsg fam_monitor_file mssql_query ocifreedesc rand cpdf_output_buffer pcntl_wexitstatus ifxus_close_slob dbx_close output_add_rewrite_var debug_print_backtrace ldap_set_option socket_create_listen socket_recvmsg + contained xml_get_error_code cpdf_setrgbcolor vprintf mb_preferred_mime_name imagepng mcal_date_compare session_set_save_handler stream_wrapper_register mb_strimwidth asin mb_output_handler cybercash_base64_encode pdf_stroke mysqli_stat socket_set_option ibase_blob_import ftp_nlist ncurses_mvvline + contained vpopmail_alias_get_all mcve_deluser easter_days imap_headers mysqli_slave_query ldap_mod_replace create_function readline_info udm_check_charset cpdf_rotate_text fbsql_database_password ncurses_has_key curl_init shm_remove_var mysql_create_db ncurses_attroff udm_close_stored cpdf_rect + contained set_file_buffer hw_new_document ncurses_wstandend set_magic_quotes_runtime hw_incollections array_udiff sybase_fetch_assoc printer_create_dc pdf_get_image_width hw_info cpdf_continue_text msql_drop_db ibase_free_result gmp_hamdist localtime mt_getrandmax ircg_html_encode posix_getsid + contained array_map nsapi_request_headers cal_to_jd ocicollgetelem ircg_set_current pdf_continue_text ibase_rollback_ret bindec socket_iovec_free ldap_compare imap_thread stripcslashes end odbc_free_result ocifreecollection mb_encode_mimeheader swf_shapemoveto mysqli_commit gregoriantojd + contained sybase_min_server_severity msession_get_array hw_identify ovrimos_prepare unpack fbsql_close connection_timeout ccvs_count sesam_fetch_row pdf_fill mcal_fetch_event ibase_gen_id ming_setscale sybase_fetch_row ncurses_curs_set iconv_mime_encode mcal_event_set_recur_yearly + contained ingres_field_scale mysql_pconnect ldap_next_reference gmp_init cpdf_save checkdnsrr strncmp is_a wordwrap pg_options domxml_xslt_stylesheet imagefontwidth stream_copy_to_stream imap_fetchstructure printer_end_doc readline_write_history imap_listsubscribed preg_quote swf_definepoly + contained swf_getbitmapinfo ftp_chdir mhash_count var_export pdf_endpath printer_select_brush get_magic_quotes_runtime mcve_initengine uasort pdf_add_locallink ifx_update_char ifxus_open_slob pdf_setrgbcolor_stroke mcal_expunge pdf_setgray_stroke swf_placeobject mcrypt_ofb bzwrite + contained mcve_iscommadelimited mcrypt_decrypt ircg_nickname_escape aggregate odbc_autocommit mcve_verifyconnection memory_get_usage notes_find_note mysqli_execute str_ireplace cpdf_set_action_url msession_get strstr unlink ircg_whois swf_closefile pdf_get_pdi_value session_decode lstat swfgradient + contained is_finite pcntl_exec http_build_query mcve_transactionauth tidy_setopt openssl_public_decrypt array_walk pack get_meta_tags ncurses_noecho mysql_field_seek pdf_add_launchlink cyrus_close ncurses_instr ncurses_wvline dbase_close vpopmail_del_domain crack_closedict ncurses_color_content + contained system odbc_tableprivileges ora_rollback diskfreespace recode_file tidy_get_status posix_getuid pg_field_prtlen posix_getpgid getmygid dbx_query imagecreatefromwbmp soundex fbsql_drop_db apache_child_terminate mcve_settle bcdiv ora_logoff ldap_err2str dbplus_restorepos + contained pdf_set_border_color fdf_open ftp_quit hw_inscoll curl_error mcve_deletetrans ociloadlob jdtogregorian odbc_setoption metaphone pdf_lineto gmp_intval pg_last_oid shmop_write imap_search shm_get_var ingres_connect pdf_place_image mysqli_bind_result srand mcrypt_enc_get_algorithms_name + contained checkdate mssql_field_name cpdf_set_char_spacing ibase_commit_ret mcal_event_set_title ovrimos_field_type openssl_x509_check_private_key pdf_get_font ccvs_done mysql_field_name xml_set_element_handler ingres_field_name ocibindbyname cpdf_page_init cpdf_moveto link mysqli_error + contained ifx_textasvarchar swf_addcolor array_diff_uassoc java_last_exception_get mysql_fetch_lengths iconv swf_definefont nl2br mssql_fetch_assoc msql_num_rows pdf_close_pdi_page gmp_prob_prime dbplus_tremove dbplus_sql ncurses_addnstr gmp_clrbit ovrimos_field_num sesam_execimm ob_clean + contained imap_getsubscribed hw_getobjectbyquery gmp_scan0 gmp_scan1 sqlite_current call_user_func ovrimos_connect mssql_fetch_array ifx_copy_blob dngettext shm_detach ldap_count_entries posix_geteuid ocicollassignelem urlencode parse_ini_file dns_get_record ovrimos_rollback odbc_error + contained msession_list swf_actiongotolabel yp_first fbsql_query ming_useswfversion range readline_list_history mysql_result odbc_result_all mysqli_thread_id sort dbase_get_header_info stream_filter_prepend swf_shapefilloff cpdf_set_word_spacing mhash_keygen_s2k sscanf mb_strpos gethostbyaddr + contained ncurses_delay_output ncurses_mvaddch ereg_replace posix_getpwuid dbplus_undo hw_document_size tidy_repair_string pg_insert pg_fetch_array pdf_show_xy passthru dbplus_rkeys juliantojd pdf_moveto lzf_decompress mcal_event_set_recur_weekly sleep tidy_config_count mssql_free_statement expm1 + contained gzfile ocistatementtype mysql_fetch_array mysql_data_seek ibase_param_info pdf_set_info_title muscat_setup_net mysqli_fetch hw_childrenobj is_writeable cpdf_set_keywords mysqli_fetch_array bcsqrt swfdisplayitem yp_master ncurses_slk_attron ftp_rawlist notes_create_note fdf_errno + contained ncurses_bkgd debugger_off dbx_fetch_row jdmonthname dio_write aggregate_methods_by_list import_request_variables pg_pconnect imap_get_quota ceil ocicancel socket_set_nonblock cpdf_circle ocicolumnscale cpdf_newpath php_ini_scanned_files com_release posix_setgid fdf_create imap_qprint + contained imap_deletemailbox pdf_show_boxed dbplus_freealllocks xmlrpc_get_type hypot swf_shapearc mcrypt_enc_is_block_algorithm cyrus_query fbsql_rollback mcve_numrows fileinode imagedestroy ncurses_panel_below socket_set_timeout ora_open mcal_event_init hw_stat str_word_count mcal_date_valid + contained fwrite imap_mail_move stream_set_timeout imap_reopen array_reverse pdf_set_value hw_errormsg nl_langinfo vpopmail_set_user_quota bin2hex java_last_exception_clear token_get_all dio_fcntl cpdf_set_leading imagepsloadfont hw_getremotechildren pdf_set_text_rise ascii2ebcdic aggregate_info + contained imagepsfreefont ftp_raw putenv msql_dbname hw_output_document ocinumcols mcve_transactionavs imagefontheight msession_count mssql_rows_affected printer_start_doc ltrim mcve_return openssl_pkcs7_verify imap_status xmlrpc_encode_request array_merge_recursive ifx_getsqlca ovrimos_longreadlen + contained dl printer_get_option strrchr msg_set_queue fdf_get_encoding fbsql_password mysqli_free_result mysqli_rpl_probe list pg_fetch_row domxml_open_file com_propset openssl_free_key mysql_connect atan2 odbc_prepare fgets pdf_open_image mcal_store_event array_diff_assoc mysqli_fetch_lengths + contained dbplus_curr ifx_nullformat fdf_add_doc_javascript posix_setegid readline mb_get_info imagecopy swf_textwidth ncurses_newpad readlink bcpow socket_getsockname pg_query com_load vpopmail_del_user ifxus_create_slob printer_draw_elipse swfbutton_keypress iconv_strpos msql_fieldtype + contained unserialize rsort yaz_addinfo mb_ereg call_user_method_array bzdecompress mb_split fpassthru imap_listscan pdf_rect printer_delete_brush ncurses_standout ifx_pconnect printer_end_page mysqli_disable_reads_from_master dbplus_tcl ncurses_wcolor_set atan pspell_save_wordlist domxml_new_doc + contained pspell_new_config pg_client_encoding ccvs_sale mysqli_num_fields odbc_cursor fbsql_affected_rows mcal_event_set_category array_udiff_uassoc ifx_create_blob acos imap_lsub mysql_close apache_getenv ovrimos_exec lzf_compress gzdeflate fbsql_pconnect ifx_byteasvarchar pg_lo_write dio_read + contained imagecreatefromgd2 cpdf_begin_text pg_update cpdf_rotate exif_imagetype is_dir mysqli_ping ncurses_reset_shell_mode pdf_setlinewidth ftell sybase_set_message_handler mysqli_prepare_result textdomain imagecreatefromstring hw_mapid mb_substr posix_setsid swf_startdoaction + contained mysqli_enable_reads_from_master cpdf_finalize posix_getppid imagecolorexact cpdf_set_viewer_preferences msql_listtables ncurses_slk_color mysqli_stmt_errno imagecolorresolve gmp_neg ncurses_def_prog_mode mysql_drop_db ovrimos_num_fields crack_opendict disk_free_space cpdf_setgray_fill + contained mcrypt_enc_self_test gmp_strval dbplus_last curl_multi_getcontent fam_pending krsort ldap_set_rebind_proc pdf_get_image_height imap_createmailbox getprotobynumber odbc_num_rows pg_result_seek mcve_gft stream_get_contents bzclose odbc_data_source pdf_skew mb_detect_order mcrypt_cfb + contained swf_fontslant ob_get_level swf_modifyobject readgzfile ociserverversion mysql_field_flags swf_endbutton ncurses_inch ifx_get_blob unset iconv_mime_decode_headers msession_timeout ini_set msg_stat_queue ncurses_noraw bzerrstr escapeshellarg domxml_xmltree implode func_get_args str_rot13 + contained ncurses_typeahead ibase_wait_event imagecolorset pdf_concat get_parent_class log10 fdf_get_attachment printer_draw_text xml_set_end_namespace_decl_handler pdf_get_parameter pdf_stringwidth filepro_fieldcount mysqli_field_count ifx_do pspell_config_runtogether ircg_lookup_format_messages + contained apache_setenv imagepalettecopy posix_setpgid hw_children filepro_fieldwidth fdf_save imap_num_msg hw_api_content yaz_database mysql_insert_id hw_unlock ftp_ssl_connect msql_numrows gmp_gcd get_included_files udm_free_ispell_data sybase_result mssql_select_db udm_error ircg_pconnect + contained socket_clear_error set_error_handler odbc_result acosh is_callable ifx_free_char xml_set_default_handler com_propget odbc_connect mysqli_query pspell_new getservbyname mysqli_stmt_close curl_multi_exec hebrevc ingres_fetch_object intval mysqli_prepare reset odbc_close_all session_destroy + contained print_r printer_delete_pen mcrypt_module_is_block_mode pdf_setfont convert_cyr_string ingres_field_precision mysqli_master_query ncurses_mvhline msql_tablename ftp_mkdir ldap_first_reference ibase_blob_add dbminsert ncurses_getch fdf_set_javascript_action tidy_warning_count hebrev usort + contained sqlite_last_error fdf_next_field_name sprintf ncurses_wnoutrefresh ncurses_mvaddchnstr dbplus_lockrel hw_getchilddoccoll fileperms rad2deg pcntl_wtermsig restore_include_path count ncurses_flash posix_getrlimit mt_srand compact base64_encode hw_pconnect htmlspecialchars imagefttext + contained mailparse_determine_best_xfer_encoding apache_get_version cpdf_setlinewidth zip_read swf_ortho ldap_get_option fbsql_list_dbs gzread session_register hw_getobjectbyquerycollobj ncurses_panel_above mcve_transactionssent dirname time sybase_min_error_severity fbsql_fetch_lengths + contained udm_get_doc_count mysql_affected_rows fputs fbsql_free_result snmpset imap_num_recent ldap_first_entry mcal_time_valid sybase_connect udm_find iconv_mime_decode json_last_error ucwords curl_setopt fbsql_warnings imagettftext call_user_func_array sqlite_column ldap_explode_dn + contained mcrypt_enc_get_block_size xpath_new_context ifx_fetch_row msession_connect mailparse_stream_encode pfpro_process in_array array_count_values pclose mcve_getcell msession_set atanh imagecreatefromgif mcve_getuserarg mcal_days_in_month ob_start iconv_get_encoding mcve_transactionitem + contained odbc_fetch_into sqlite_rewind wddx_serialize_vars ociwritelobtofile ingres_field_length mcal_create_calendar openssl_verify printer_logical_fontheight ncurses_border array_rand odbc_pconnect unixtojd getservbyport pspell_config_mode hw_gettext curl_version ociexecute ldap_rename + contained mssql_fetch_object pdf_setrgbcolor_fill aggregate_methods_by_regexp preg_replace_callback mysqli_stmt_store_result hwapi_hgcsp ncurses_nl xml_set_external_entity_ref_handler swfshape ob_get_clean get_html_translation_table swf_actiongeturl cal_info hw_getanchors ora_commitoff + contained socket_getpeername array_filter mktime domxml_open_mem xslt_set_sax_handler printer_open mcal_open pdf_add_bookmark ldap_sort ctype_alpha imagechar mcrypt_enc_get_modes_name mssql_get_last_message ncurses_reset_prog_mode odbc_primarykeys swf_polarview bzerrno udm_get_res_param + contained fbsql_tablename dbplus_prev ocinewdescriptor imageistruecolor bccomp mcal_reopen dbmreplace mcve_adduserarg udm_clear_search_limits msession_uniq ibase_add_user msql_numfields mysql_fetch_row mb_strwidth sem_get odbc_field_name mcal_delete_event vsprintf mysqli_field_seek array + contained msql_selectdb pdf_restore prev cpdf_set_font_map_file extension_loaded ncurses_insstr fclose imap_utf7_encode pcntl_waitpid socket_last_error fileatime pdf_arcn mysql_get_proto_info ncurses_insch ncurses_init com_isenum snmpwalkoid cpdf_scale mssql_guid_string imageantialias func_get_arg + contained ctype_cntrl openssl_pkey_export_to_file register_tick_function ncurses_meta socket_send sesam_diagnostic mysqli_connect imap_utf8 fbsql_field_flags exec session_get_cookie_params ip2long hw_cp pdf_circle printer_create_pen cpdf_import_jpeg php_uname xslt_set_scheme_handlers mb_strtolower + contained fgetc printer_create_brush is_integer parse_url sqlite_busy_timeout msql_fetch_array mysql_list_tables ocilogon ocisavelob pdf_add_pdflink bcadd imagepolygon cpdf_set_text_matrix mb_substitute_character levenshtein yaz_es_result ldap_unbind imagesetbrush class_exists cpdf_clip mysql_info + contained fdf_set_submit_form_action array_combine socket_sendto tanh strtoupper ibase_free_query zip_entry_close mysqli_dump_debug_info mcve_listusers pg_get_notify debugger_on sybase_select_db setlocale ncurses_slk_attrset pdf_open_memory_image ccvs_lookup pdf_save pcntl_fork iconv_substr + contained ncurses_wclear imagecolormatch xmlrpc_server_register_introspection_callback pg_lo_open fdf_set_value swf_perspective openssl_private_decrypt ncurses_vidattr ftp_cdup gzpassthru ocinlogon swf_enddoaction cpdf_setrgbcolor_stroke posix_uname ncurses_mousemask + contained mcal_event_set_recur_monthly_wday cpdf_rmoveto dbplus_savepos ingres_rollback pi ocinewcursor cpdf_set_font udm_free_agent aggregate_methods yaz_get_option ncurses_waddch ibase_blob_create pg_escape_string fbsql_get_autostart_info is_executable pg_lo_import msql_num_fields stristr + contained ifx_blobinfile_mode tidy_get_body get_defined_functions getrandmax mcal_rename_calendar mb_http_output ob_flush fdf_error ifxus_read_slob ldap_errno imap_8bit mysqli_fetch_assoc session_module_name yp_get_default_domain str_pad mcal_delete_calendar fileowner ovrimos_commit ncurses_timeout + contained strcoll error_log strncasecmp posix_ttyname udm_check_stored xml_parser_create_ns ifx_error cpdf_closepath ncurses_slk_restore hw_root dba_close com_load_typelib pdf_set_leading ibase_errmsg hw_who imageellipse ibase_fetch_object sybase_min_client_severity sesam_seek_row + contained ncurses_replace_panel ncurses_mvaddnstr cyrus_authenticate proc_open udm_open_stored imagewbmp ftp_fget strval hw_free_document ldap_error ingres_commit swf_shapecurveto imap_close pg_ping preg_match dbx_sort ircg_nickname_unescape is_numeric openssl_csr_sign stream_context_get_options + contained pg_set_client_encoding pdf_fill_stroke yaz_ccl_parse ftp_nb_continue fseek gzgetss mb_strcut ibase_field_info array_intersect_assoc odbc_columns dechex mssql_execute imap_list set_time_limit mysql_client_encoding yp_match ncurses_whline exit ora_close mcrypt_generic dbase_open + contained get_loaded_extensions ncurses_vline imagecreatefromxbm msql_list_fields strtolower ccvs_auth dba_delete fbsql_set_lob_mode substr_compare mcve_numcolumns mysqli_kill ora_exec ncurses_mvinch ifx_fieldproperties com_invoke mysqli_affected_rows cybercash_encr sybase_close mb_strlen + contained fam_suspend_monitor pdf_set_duration curl_multi_select hw_insertdocument pspell_store_replacement hw_setlinkroot array_chunk sesam_connect session_regenerate_id ftp_chmod imap_listmailbox ora_plogon hw_docbyanchor hw_error muscat_give utf8_encode pdf_open_ccitt ncurses_keyok mcve_ping + contained pdf_makespotcolor mysqli_ssl_set gmp_legendre mysql_escape_string stream_socket_accept sinh next strtotime ncurses_werase mcal_day_of_week mssql_field_length pdf_setgray dbase_replace_record imap_rfc822_parse_headers array_diff msql_result dba_replace dbmnextkey mcrypt_module_open + contained ftp_login fbsql_hostname dbx_connect pg_escape_bytea swf_fontsize odbc_statistics mysqli_real_escape_string ibase_num_fields odbc_field_scale mb_encode_numericentity ncurses_wattron msql stream_socket_get_name xslt_create fdf_remove_item gmp_cmp mssql_next_result mcal_next_recurrence + contained mb_strtoupper curl_exec xslt_free ncurses_qiflush udm_set_agent_param ncurses_slk_set mssql_bind dotnet_load pg_lo_close cybercash_decr ncurses_slk_attr openssl_x509_free mcve_connectionerror parse_str bcmod snmp_get_quick_print ncurses_termattrs pg_lo_export preg_replace hw_getrellink + contained headers_list qdom_tree ncurses_show_panel ncurses_termname ircg_join imap_timeout ereg mb_eregi ocirowcount hw_getparents mcve_void w32api_invoke_function imap_base64 imagecreatefromgd ksort sybase_num_fields pspell_add_to_session flock ingres_close pg_field_num hw_getusername + contained ncurses_scr_init dbmfirstkey msql_createdb ora_commiton hw_getremote openssl_x509_export socket_write mb_http_input aspell_suggest ctype_digit pdf_arc opendir cpdf_stringwidth ldap_free_result gmp_sub imap_mail_copy cpdf_setdash ncurses_has_colors imagerotate mailparse_msg_get_part + contained func_num_args fbsql_change_user imagefilltoborder mcrypt_module_get_algo_block_size imagecolorstotal vpopmail_alias_del imagepsbbox msession_lock notes_unread msql_select_db gethostbynamel odbc_columnprivileges mcal_popen natsort scandir zip_entry_compressedsize pg_copy_to getmypid + contained ctype_punct mysql_query iptcembed curl_multi_add_handle notes_list_msgs xml_parser_create ncurses_addchnstr ncurses_erase quotemeta imagetypes msql_close fbsql_start_db swf_popmatrix mcve_responseparam microtime pdf_findfont sqlite_libversion cpdf_setflat getcwd yp_cat cpdf_add_annotation + contained filesize dbplus_xunlockrel ldap_8859_to_t61 str_split odbc_fetch_row dbase_pack ifx_free_result fdf_add_template socket_connect array_udiff_assoc domxml_xslt_stylesheet_doc pg_lo_seek udm_load_ispell_data json_decode mysqli_change_user ldap_connect mysqli_select_db getprotobyname define + contained ncurses_can_change_color extract ociresult mb_ereg_search hw_mv get_current_user tidy_getopt ora_do zip_entry_filesize asinh ocicolumnisnull ircg_is_conn_alive imap_body swf_removeobject get_declared_classes ingres_pconnect usleep key gmp_div_q imap_fetchheader socket_get_status + contained shm_put_var imap_ping tidy_access_count openlog ctype_graph hexdec bzopen curl_close proc_get_status aggregation_info odbc_procedurecolumns get_defined_constants get_class_vars curl_getinfo fdf_header odbc_foreignkeys xptr_new_context dbase_numrecords sin pdf_curveto ldap_list + contained readline_clear_history odbc_field_type xmlrpc_set_type pspell_add_to_personal mb_ereg_search_pos dbplus_rcrtexact curl_multi_info_read swfsprite openssl_x509_parse stream_filter_register ibase_fetch_assoc sybase_fetch_field file_get_contents mysqli_close imageline ldap_get_entries + contained ocicolumnname stream_set_blocking mysqli_field_tell dbase_get_record ocifreecursor ncurses_nonl imap_mail pdf_closepath_stroke domxml_version ncurses_killchar ociinternaldebug cal_days_in_month gmp_sign swf_scale cal_from_jd ingres_fetch_array method_exists msession_find fbsql_commit + contained mcve_getheader dba_nextkey ifx_fieldtypes array_intersect mcal_event_set_end pdf_get_pdi_parameter socket_listen uniqid posix_times bcmul xmlrpc_server_register_method fbsql_fetch_array swfaction mysql_get_server_info mcve_transactioncv call_user_method ibase_free_event_handler + contained xml_parser_set_option openssl_pkcs7_decrypt mssql_num_rows cpdf_save_to_file stream_socket_recvfrom pdf_clip rewinddir zip_close cpdf_set_page_animation xmlrpc_server_create mysql_db_query imagecopyresized pdf_open_png mysql_num_rows ifx_update_blob sybase_fetch_object gmp_sqrtrem + contained wddx_packet_start zip_entry_open cpdf_open ncurses_clear mcve_chkpwd printer_draw_chord posix_getlogin ob_get_flush output_reset_rewrite_vars fprintf frenchtojd filepro_retrieve ora_getcolumn imap_mime_header_decode strnatcasecmp register_shutdown_function mysqli_real_query + contained mssql_min_error_severity msql_dropdb openssl_pkcs7_sign filepro_rowcount fbsql_db_query file openssl_pkey_get_public getmxrr ncurses_filter fribidi_log2vis imap_getmailboxes sybase_min_message_severity mysql_free_result getlastmod ibase_blob_echo ibase_prepare mcve_destroyengine + contained openssl_seal chgrp stream_socket_server odbc_fetch_array ora_parse yaz_record swf_actionplay ldap_mod_del posix_isatty imap_expunge mcve_getcommadelimited sybase_field_seek swf_pushmatrix fdf_get_value ncurses_use_default_colors yp_all ncurses_deleteln fdf_close dbplus_first + contained mysqli_rollback mcrypt_module_is_block_algorithm ncurses_mvcur sybase_unbuffered_query imagecopymerge xml_get_current_line_number openssl_pkey_new posix_getpwnam pdf_open_pdi_page crack_getlastmessage odbc_field_len fdf_set_version ocisetprefetch swffont msql_fieldtable + contained wddx_serialize_value mysqli_fetch_fields is_infinite imagecolorclosesthwb dbplus_find stream_context_set_option odbc_specialcolumns msql_affected_rows openssl_csr_export_to_file pg_copy_from pdf_open_tiff pfpro_cleanup substr_replace chr mysql_field_table getallheaders ibase_trans + contained imap_rfc822_parse_adrlist odbc_commit chown gd_info mysqli_get_client_info gmp_fact ora_numrows pdf_set_text_matrix gmp_or gethostbyname pfpro_process_raw strtok xmlrpc_parse_method_descriptions ncurses_echo getrusage is_null sem_release ocierror swf_setframe ncurses_insertln + contained swf_shapefillsolid ncurses_clrtoeol pg_delete aggregate_properties cpdf_global_set_document_limits yaz_schema mcve_preauthcompletion pdf_close printer_delete_font hw_objrec2array mb_ereg_search_getpos ovrimos_num_rows openssl_csr_new dbplus_open sqlite_unbuffered_query sqrt ctype_xdigit + contained mysqli_options xmlrpc_encode mcve_getuserparam ob_iconv_handler copy sqlite_create_function mhash gmp_div_qr ldap_close iconv_set_encoding restore_error_handler mysqli_real_connect mysqli_autocommit dbplus_rchperm ncurses_refresh mcve_bt pdf_add_weblink ncurses_getyx ftp_get iconv_strrpos + contained mcal_event_set_recur_none sqlite_popen filemtime pdf_closepath fdf_save_string imagedashedline imagecolorat ncurses_slk_noutrefresh fdf_get_ap pspell_new_personal mysqli_num_rows mhash_get_block_size swf_shapefillbitmaptile imagecreatefromxpm ncurses_init_pair ovrimos_free_result + contained udm_get_res_field imap_getacl imagecolorallocate ncurses_scr_restore mysql_get_client_info print is_bool mailparse_msg_get_structure dbplus_flush pg_connect fread chroot mcrypt_generic_deinit ncurses_putp dbplus_setindex imap_mailboxmsginfo pg_num_fields jewishtojd feof asort + contained msession_randstr apache_response_headers ignore_user_abort cpdf_set_text_rise strripos fdf_get_opt odbc_num_fields substr cyrus_connect sesam_errormsg ifxus_seek_slob count_chars pdf_begin_template hw_api_attribute is_array ncurses_insdelln mysql_change_user mysqli_enable_rpl_parse + contained mysqli_stmt_affected_rows imagefilledellipse ifx_num_rows getdate floor gzeof tempnam ncurses_addch imap_rfc822_write_address ctype_print vpopmail_add_alias_domain yaz_range mb_ereg_search_setpos dba_open printer_draw_rectangle ncurses_attron yp_errno basename dba_key_split + contained ibase_modify_user readfile dbplus_add fbsql_num_rows gzgets ob_implicit_flush swf_shapelinesolid stream_filter_append xpath_eval_expression dbplus_freelock mcve_transactionid pg_lo_tell assert_options curl_multi_close imap_setflag_full imap_bodystruct number_format gmp_xor pdf_setlinecap + contained posix_getgrgid ob_end_flush pg_send_query dbplus_unlockrel swf_shapefillbitmapclip ocicolumnprecision fdf_set_ap mysqli_disable_rpl_parse filepro_fieldtype imagecreate version_compare sybase_num_rows is_nan pdf_set_info ftp_pasv overload ovrimos_fetch_row posix_setuid ccvs_command + contained imap_setacl round pg_port mssql_connect iconv_strlen array_merge pdf_open_image_file mcve_override lcg_value odbc_do ftp_nb_get ftp_exec ncurses_prefresh imap_msgno ircg_notice printer_close crypt mysql_ping mcve_deleteresponse mb_ereg_match ucfirst ingres_query variant + contained imagecolorexactalpha swf_actionprevframe isset ibase_drop_db pdf_setcolor ncurses_waddstr ibase_rollback mysql_unbuffered_query ftp_fput ncurses_start_color trigger_error ncurses_scr_dump pdf_closepath_fill_stroke pspell_config_create socket_accept dns_check_record ircg_set_file + contained mcal_event_add_attribute is_subclass_of gzinflate constant sqlite_libencoding base_convert cpdf_setrgbcolor_fill notes_create_db socket_bind mcrypt_encrypt imagettfbbox ircg_fetch_error_msg gmp_div ncurses_addstr get_cfg_var socket_iovec_set posix_kill xml_parse_into_struct + contained imagepsextendfont shell_exec ovrimos_field_name tidy_get_config sqlite_query max mysqli_character_set_name imap_binary mcve_gl ncurses_bkgdset dbase_get_record_with_names odbc_gettypeinfo mysql_fetch_object pdf_set_border_dash mcrypt_get_iv_size sqlite_close mysqli_debug + contained swf_addbuttonrecord ibase_connect ibase_delete_user rtrim pdf_set_text_rendering get_defined_vars swf_startbutton ibase_commit tan xmlrpc_server_destroy ifx_get_char zip_entry_compressionmethod pg_end_copy mysql_tablename mailparse_msg_get_part_data printer_create_font mcve_disableuser + contained com yaz_scan odbc_fetch_object msql_field_seek cos chunk_split imagecreatefrompng swf_mulcolor gmp_pow udm_cat_list xslt_errno sqlite_array_query sqlite_seek imap_append pdf_set_font phpversion pdf_rotate mysqli_rpl_query_type mysqli_send_long_data zlib_get_coding_type mcve_text_code + contained sybase_fetch_array pg_fetch_all ncurses_wstandout mcrypt_ecb mysqli_fetch_field fbsql_db_status imagerectangle yaz_connect dbplus_unselect notes_mark_read dba_fetch fam_next_event dns_get_mx preg_grep ob_end_clean pdf_get_majorversion msql_freeresult vpopmail_passwd md5_file + contained mcrypt_get_block_size jdtojewish ocidefinebyname ncurses_longname imap_undelete mcve_deleteusersetup pdf_scale pg_result_status is_long apache_request_headers swf_showframe xslt_error shmop_read session_start ocifetchstatement ldap_start_tls exif_read_data dbplus_update ircg_kick + contained sesam_fetch_array swf_actiongotoframe vpopmail_add_user swf_actiontogglequality printer_draw_line hw_getobject mysqli_read_query_result imap_unsubscribe error_reporting gmp_sqrt wddx_add_vars gmp_random msql_list_tables com_set xmlrpc_decode_request umask pdf_setrgbcolor get_class_methods + contained cyrus_unbind mysqli_fetch_object ncurses_cbreak imap_check xslt_set_log posix_seteuid str_shuffle ncurses_isendwin mysqli_reload mcve_force xml_set_start_namespace_decl_handler is_real highlight_string dba_exists ncurses_halfdelay rewind pdf_setdash ldap_next_entry yaz_element + contained ncurses_wmove tidy_get_html gzputs fbsql_num_fields cybercash_base64_decode mcal_event_set_start ncurses_use_extended_names ldap_delete vpopmail_alias_del_domain swf_definebitmap fam_cancel_monitor ocicollmax ncurses_baudrate strpos sesam_rollback ircg_get_username gmp_abs + contained tidy_get_error_buffer mcal_event_set_recur_monthly_mday odbc_tables bind_textdomain_codeset muscat_setup dcngettext gettext mb_ereg_replace gzwrite ftp_nb_fget shmop_open session_encode vpopmail_del_domain_ex ocicommit dblist sesam_fetch_result dba_popen notes_nav_create pg_get_result + contained ora_logon swfbitmap ncurses_resetty msql_create_db array_reduce chdir mcrypt_get_key_size each ifx_errormsg hw_getchilddoccollobj get_required_files fdf_set_opt fbsql_set_transaction shmop_close mssql_min_message_severity pfsockopen dbmfetch snmpget dbmdelete yaz_present dbmexists + contained array_splice imagesetpixel imagesettile mcve_transsend ncurses_ungetmouse md5 mysqli_rpl_parse_enabled dio_open com_propput fbsql_fetch_assoc hw_getanchorsobj stream_socket_sendto msession_getdata pg_fetch_assoc imagejpeg apache_lookup_uri array_multisort ccvs_delete pg_num_rows + contained swf_endsymbol swf_shapelineto xslt_output_process ifx_num_fields posix_getpgrp mb_strrpos fnmatch gettimeofday aggregate_properties_by_regexp socket_iovec_alloc session_unset swf_fonttracking posix_getgrnam gmp_popcount socket_iovec_fetch array_unique tidy_set_encoding mcrypt_module_close + contained dio_stat ccvs_textvalue msql_fieldname ob_gzhandler escapeshellcmd imap_subscribe imap_alerts hw_array2objrec socket_sendmsg ingres_field_type mailparse_msg_parse_file ncurses_beep ifx_close cpdf_setgray shmop_delete ccvs_init mcve_transactiontext ifx_htmltbl_result socket_set_blocking + contained pspell_config_repl snmprealwalk gmp_setbit ircg_topic qdom_error pdf_add_thumbnail dbplus_errno shmop_size filectime openssl_error_string addslashes proc_terminate printer_draw_bmp mcve_monitor cpdf_stroke dbplus_ropen dbplus_rrename pg_convert posix_getgid vpopmail_error + contained xslt_set_sax_handlers msg_remove_queue bcpowmod mysql_fetch_field gmp_jacobi delete ccvs_add com_get cpdf_setlinecap readline_add_history pdf_set_char_spacing xml_parser_get_option pg_trace mb_language sybase_free_result ldap_parse_reference sesam_query imap_sort sem_acquire + contained mcrypt_enc_get_key_size ibase_name_result mssql_fetch_field xml_set_object money_format pg_get_pid pdf_open_gif imagegd ob_get_length ircg_part exif_thumbnail ncurses_noqiflush mysqli_store_result mcve_chngpwd pg_meta_data yaz_close mysql_get_host_info array_flip setcookie + contained xml_error_string posix_get_last_error imap_open dba_handlers yaz_itemorder ldap_bind mcve_sale session_write_close mcal_event_set_description tidy_repair_file split ccvs_report hw_close pdf_add_outline msession_unlock arsort sybase_deadlock_retry_count jdtofrench mcve_edituser + contained msession_inc imagefilledarc imagecolorresolvealpha gmp_invert is_float xslt_set_scheme_handler hw_modifyobject cpdf_fill_stroke dba_list mcve_checkstatus ftp_rmdir pspell_config_personal mysql_field_len msg_get_queue ibase_blob_open gzopen array_values ncurses_addchstr fbsql_read_clob + contained imap_scanmailbox cpdf_closepath_fill_stroke msql_list_dbs mcrypt_module_get_algo_key_size pg_last_error swf_nextid fbsql_username mcve_qc ncurses_wattrset pg_connection_status pdf_end_pattern msg_receive connection_status pdf_end_page mcal_snooze ncurses_wrefresh array_push + contained imagefilledrectangle ncurses_end ibase_errcode mcal_fetch_current_stream_event pdf_setmiterlimit pdf_initgraphics swf_shapecurveto3 getenv dbplus_chdir session_name dbplus_aql odbc_rollback swf_endshape cyrus_bind cpdf_show socket_iovec_add swf_actionnextframe imagegd2 swf_getframe + contained ldap_first_attribute swf_definetext session_set_cookie_params pspell_clear_session mcrypt_enc_get_supported_key_sizes zend_logo_guid pdf_setlinejoin readdir mdecrypt_generic pathinfo pfpro_init ibase_blob_close read_exif_data mcal_append_event cpdf_translate printer_list swf_startshape + contained socket_readv ifx_query crack_check dba_firstkey zip_open fbsql_database pdf_setflat pg_fetch_result ocicollsize sqlite_create_aggregate udm_cat_path dbx_error xml_get_current_byte_index flush sqlite_num_rows sybase_get_last_message ncurses_del_panel swfmorph pspell_config_ignore + contained fbsql_field_seek ncurses_delch readline_completion_function msql_error mcve_text_cv printer_draw_roundrect dbx_compare fdf_set_file hw_deleteobject stripslashes linkinfo ora_fetch_into rename ibase_close dbplus_resolve ocifreestatement mcve_text_avs headers_sent mb_internal_encoding + contained ingres_field_nullable sqlite_error_string sqlite_last_insert_rowid ncurses_use_env preg_match_all notes_mark_unread sqlite_changes ini_get recode ibase_blob_get hw_changeobject imap_mail_compose pcntl_wifsignaled posix_getgroups imagesetstyle odbc_field_precision session_unregister + contained fbsql_errno pdf_set_info_creator ncurses_assume_default_colors sesam_field_array hw_dummy is_uploaded_file pdf_get_buffer swf_defineline ldap_mod_add ora_numcols ncurses_doupdate ocicollappend printf is_link dbplus_rzap msession_listvar mssql_free_result mt_rand ovrimos_close + contained file_put_contents php_logo_guid hw_getparentsobj pdf_end_template sem_remove w32api_register_function str_repeat yaz_sort tidy_get_release dbplus_rsecindex ncurses_def_shell_mode fbsql_field_table mcrypt_create_iv ncurses_define_key ncurses_wattroff posix_getegid yaz_scan_result + contained mysqli_get_host_info ftp_nb_fput fbsql_error gmstrftime function_exists bzflush sqlite_has_more mysql_select_db ldap_parse_result mssql_num_fields udm_errno yaz_search cpdf_set_font_directories strlen session_cache_expire ftruncate mcve_ub imagestringup bindtextdomain swfbutton + contained apache_get_modules imagepscopyfont ncurses_hline sesam_affected_rows fbsql_create_db ifxus_tell_slob stream_register_wrapper msql_fetch_field fbsql_field_len mcve_gut zip_entry_name mcal_list_events shuffle mcve_getcellbynum doubleval ftp_delete ncurses_scrl imagecopyresampled pg_dbname + contained ociplogon mb_decode_numericentity die odbc_close ocicolumntyperaw tidy_diagnose imagecolorsforindex imap_fetchbody dir ccvs_return mysqli_get_server_version eval urldecode mcrypt_generic_init fdf_set_status cpdf_finalize_page mcve_completeauthorizations array_shift ftp_rename ord + contained pcntl_wifexited gzencode ncurses_standend cpdf_curveto ncurses_wborder rmdir imap_uid ftp_set_option gzcompress pg_untrace token_name cpdf_close openssl_sign pdf_add_note gmp_com mcrypt_module_get_supported_key_sizes touch fbsql_list_tables strchr xslt_set_encoding var_dump + contained hw_insertobject tidy_clean_repair rawurlencode ingres_num_rows muscat_get yaz_errno mysql_list_fields gmp_add ncurses_echochar cpdf_set_text_pos mysql_fetch_assoc utf8_decode exp ncurses_move sesam_settransaction imagegif hw_connect pos mcrypt_get_cipher_name sqlite_field_name pow + contained imagecolordeallocate printer_write imagesetthickness msql_query stream_context_create tidy_error_count array_sum mcve_transparam mb_convert_case mysqli_data_seek ncurses_has_ic cosh ncurses_has_il mcve_transnew gmp_divexact ibase_fetch_row ircg_disconnect tidy_get_html_ver + contained sybase_affected_rows ming_setcubicthreshold mcrypt_module_self_test ibase_query fam_resume_monitor mcve_adduser fdf_set_target_frame fam_monitor_directory ldap_get_values mysql_thread_id printer_select_pen pg_close msession_plugin ibase_execute sqlite_udf_encode_binary + contained mysql_real_escape_string settype ini_get_all virtual muscat_close pg_field_name strspn mcve_returnstatus mb_convert_encoding cpdf_set_current_page ingres_autocommit nsapi_virtual printer_abort dbplus_next notes_drop_db pfpro_version log ocirollback array_pad pcntl_signal ftp_connect + contained ncurses_scr_set socket_shutdown mysqli_warning_count imageloadfont gmp_perfect_square sesam_num_fields mkdir mysqli_errno msg_send ifx_affected_rows fdf_open_string swf_labelframe cpdf_rlineto array_slice mysqli_insert_id debug_backtrace fbsql_connect msql_data_seek pdf_set_info_keywords + contained udm_free_res tidy_parse_string imagecharup mcal_event_set_alarm tidy_reset_config pg_connection_busy imap_delete crc32 socket_select ircg_msg ovrimos_result_all pdf_delete mb_eregi_replace socket_read mcve_settimeout ocilogoff fbsql_create_clob hw_document_setcontent stripos mcve_setip + contained pdf_get_fontname highlight_file xmlrpc_server_call_method mailparse_rfc822_parse_addresses date array_key_exists ocifetch mailparse_msg_extract_part pdf_begin_page msql_fetch_row imagegammacorrect stream_get_meta_data deg2rad ctype_lower mhash_get_hash_name swf_viewport tidy_get_output + contained ifx_create_char imagestring xslt_set_base stream_socket_client swftextfield domxml_xslt_stylesheet_file cpdf_set_text_rendering mysql_stat phpcredits iptcparse openssl_pkcs7_encrypt pdf_get_fontsize swf_actionsettarget ftp_alloc pdf_get_minorversion gzseek imageftbbox mysqli_stmt_error + contained fflush ncurses_mvwaddstr openssl_x509_export_to_file ldap_get_dn str_replace xslt_set_error_handler cpdf_set_horiz_scaling pg_result_error mcve_maxconntimeout pdf_open_pdi xptr_eval pcntl_wifstopped pg_unescape_bytea swf_lookat gettype fbsql_field_type shm_attach sesam_free_result popen + contained dbmopen dbplus_errcode mcve_returncode ocicolltrim gmdate gmmktime ovrimos_fetch_into ibase_num_params pg_last_notice imagesx imagesy base64_decode proc_nice mysqli_fetch_row mysqli_thread_safe notes_body apache_note ocicolumnsize printer_delete_dc pdf_set_info_author swf_oncondition + contained strrev imagecreatefromgd2part hw_edittext yaz_hits mcve_enableuser mysqli_get_proto_info socket_recv tmpfile ingres_fetch_row ftp_site ocifetchinto snmp_set_quick_print show_source sybase_data_seek dbplus_rquery ldap_get_attributes pdf_set_word_spacing ovrimos_cursor + contained mcrypt_list_algorithms user_error header dcgettext ora_error similar_text socket_writev cpdf_setgray_stroke dbplus_xlockrel dio_truncate mssql_field_seek strcmp fbsql_data_seek notes_copy_db dbplus_getlock array_search json_encode mb_detect_encoding odbc_procedures fscanf fdf_get_version + contained mailparse_msg_free hw_getsrcbydestobj msession_destroy array_unshift cpdf_end_text octdec imagealphablending ora_columnsize ldap_read fam_close openssl_open fbsql_stop_db mcal_list_alarms current mb_ereg_search_regs cpdf_text ovrimos_field_len gmp_mod imagecolortransparent socket_close + contained curl_multi_remove_handle dbase_add_record fbsql_fetch_row mcal_is_leap_year imagearc cpdf_add_outline hw_getandlock mysql_list_dbs mcal_day_of_year imageinterlace mailparse_msg_parse posix_getcwd realpath openssl_get_privatekey w32api_set_call_method swf_actionstop msession_setdata + contained pdf_begin_pattern dbplus_getunique sybase_query vpopmail_add_domain ora_columntype swf_actionwaitforframe ingres_num_fields hw_api_object mail main pdf_show sesam_disconnect ircg_channel_mode get_magic_quotes_gpc ircg_ignore_del fam_open mcrypt_enc_is_block_mode pg_field_size + contained hw_document_attributes ora_fetch imagetruecolortopalette ncurses_top_panel imap_utf7_decode get_object_vars ibase_set_event_handler cpdf_setmiterlimit ncurses_clrtobot mb_convert_kana pg_field_is_null mcrypt_enc_is_block_algorithm_mode mcrypt_cbc gmp_gcdext vpopmail_alias_get notes_search + contained readline_read_history ccvs_new dio_tcsetattr posix_getpid gmp_sqrtrm pg_lo_read msession_disconnect rawurldecode gmp_powm ldap_add strcspn openssl_public_encrypt fgetss ovrimos_result mb_parse_str mcal_close mssql_pconnect cpdf_setlinejoin msql_listdbs ora_columnname dgettext ngettext + contained fdf_set_encoding pdf_attach_file posix_strerror mailparse_uudecode_all proc_close xml_parser_free w32api_init_dtype ldap_t61_to_8859 ifx_free_blob ncurses_hide_panel ircg_ignore_add stream_select pdf_open_jpeg xml_parse mb_substr_count yp_next substr_count sqlite_fetch_single assert + contained mcve_setdropfile htmlentities jdtojulian ncurses_getmouse dbase_numfields ncurses_wmouse_trafo bzerror openssl_csr_export pdf_translate xml_set_processing_instruction_handler getimagesize sha1 strtr pg_lo_create ldap_next_attribute pspell_config_save_repl odbc_longreadlen ora_bind + contained ibase_blob_cancel sqlite_udf_decode_binary hw_getchildcollobj gmp_and sesam_commit sqlite_open pdf_setmatrix ncurses_napms mysql_db_name mcve_initusersetup snmpwalk aspell_check ccvs_void mcve_parsecommadelimited yp_order mcve_connect fbsql_next_result fdf_get_file ftok socket_recvfrom + contained mcrypt_module_is_block_algorithm_mode hw_connection_info vpopmail_add_domain_ex xml_set_unparsed_entity_decl_handler notes_version eregi_replace xmlrpc_decode pdf_setgray_fill ini_alter is_writable ncurses_savetty jdtounix hw_docbyanchorobj yaz_error is_resource pdf_add_annotation + contained dba_optimize odbc_binmode long2ip nsapi_response_headers socket_create ocisavelobfile fbsql_fetch_field ldap_get_values_len session_cache_limiter hw_pipedocument ftp_size dbplus_rcrtlike mysqli_bind_param mcal_week_of_year msql_regcase gzrewind strcasecmp xml_set_notation_decl_handler + contained ncurses_color_set define_syslog_variables ocicolumntype imagepsslantfont ccvs_reverse chmod move_uploaded_file cpdf_show_xy cpdf_fill curl_multi_init ircg_nick sqlite_num_fields natcasesort eregi ovrimos_execute mcrypt_enc_get_iv_size openssl_get_publickey syslog + contained xml_get_current_column_number imap_header aggregate_properties_by_list lzf_optimized_for mcrypt_generic_end ebcdic2ascii fam_monitor_collection dbase_delete_record mysqli_send_query msql_fieldflags mcve_verifysslcert imagepstext ncurses_raw tidy_save_config pspell_suggest is_string + contained pg_lo_read_all tidy_load_config socket_get_option ftp_put image2wbmp swf_openfile ncurses_slk_touch ncurses_mvdelch pg_select pdf_new odbc_next_result session_save_path ncurses_erasechar decbin decoct swf_definerect swf_getfontinfo imagecolorclosest ncurses_slk_init gmp_mul bcsub + links to Function +phpMethods xxx contained target dump_node next_sibling setbackground add add setlinespacing multcolor content streammp3 identify addcolor drawcurveto title doctype notations previous_sibling xinclude append_child scale last_child set_attribute setover data create_cdata_section setmargins link setdown insertanchor + contained system_id is_xhtml getwidth getwidth getwidth setratio langdepvalue children children reason drawlineto setframes setframes process dstanchors owner_document child_nodes setcommitedversion has_children info drawline count count has_siblings setname setname get_attribute values + contained result_dump_mem rotateto rotateto tidy_node rotate getshape2 insert_before prev is_xml skewxto skewxto setleftfill document_element skewx skewy output is_asp replace ftstat setdimension is_html setspacing set_namespace next setup create_text_node setindentation user setaction value value + contained value insertcollection prefix dstofsrcanchors get_nodes get_elements_by_tagname get_elements_by_tagname attributes attributes create_comment get_content dump_file dcstat unlock key node_type description first_child lock move move get_attr create_attribute setheight setheight dbstat + contained drawcurve remove remove remove remove remove find insert insert copy set_name get_element_by_id checkin objectbyanchor moveto moveto moveto align setfont setfont setleftmargin setrightfill addstring addstring read mimetype addaction getshape1 addentry result_dump_file has_attribute + contained has_child_nodes skewyto skewyto save getheight create_processing_instruction addfill create_entity_reference type is_text name name remove_child setline parent_node object parents public_id is_blank_node setrightmargin srcanchors is_jste setbounds nextframe nextframe sethit set_content + contained create_element_ns movepen setcolor setcolor clone_node srcsofdst replace_node movepento create_element setdepth is_comment is_jsp unlink_node checkout append_sibling entities tagname remove_attribute setrate node_value attreditable scaleto scaleto add_namespace dump_mem internal_subset + contained replace_child has_attributes specified insertdocument assign node_name hwstat addshape get_attribute_node html_dump_mem userlist + links to Function +phpConditional xxx contained switch switch elseif if enddeclare declare else endswitch endif + links to Conditional +phpRepeat xxx contained as endfor do endforeach for endwhile while foreach + links to Repeat +phpLabel xxx contained switch case default + links to Label +phpStatement xxx contained goto return exit continue die break + links to Statement +phpKeyword xxx contained const var + links to Statement +phpType xxx contained inte int boole intege array string boolean float integ null double integer object bool real boolea + links to Type +phpStructure xxx contained implements extends class list + trait + contained interface namespace self parent instanceof abstract + links to Structure +phpOperator xxx match /[-=+%^&|*!.~?:]/ display contained + match #[-+*/%^&|.]=# display contained + match +/[^*/]+me=e-1 display contained + match /\$/ display contained + match /&&\|\<and\>/ display contained + match /||\|\<x\=or\>/ display contained + links to Operator +phpRelation xxx match /[!=<>]=/ display contained + match /[<>]/ display contained + links to Operator +phpMemberSelector xxx match /->/ display contained + links to Structure +phpVarSelector xxx match /\$/ display contained + links to Operator +phpIdentifier xxx match /$\h\w*/ display contained contains=phpEnvVar,phpIntVar,phpVarSelector + links to Identifier +phpParent xxx match /[({[\]})]/ contained + links to Delimiter +phpIdentifierSimply xxx match /${\h\w*}/ display contained contains=phpOperator,phpParent + links to Identifier +phpIdentifierComplexP xxx matchgroup=phpParent start=/\[/ end=/]/ contained contains=@phpClInside + matchgroup=phpParent start=/\[/ end=/]/ contained contains=@phpClInside +phpIdentifierComplex xxx matchgroup=phpParent start=/{\$/rs=e-1 end=/}/ contained extend contains=phpIdentifier,phpMemberSelector,phpVarSelector,phpIdentifierComplexP +phpBrackets xxx match /[][}{]/ display contained + links to Delimiter +phpInterpSimpleError xxx match /\[[^]]*\]/ display contained + match /->[^a-zA-Z_]/ display contained + links to Error +phpInterpBogusDollarCurley xxx match /${[^}]*}/ display contained + match /${\h\w*->}/ display contained + match /${\h\w*\[]}/ display contained + links to Error +phpinterpSimpleBracketsInner xxx match /\w\+/ contained + links to String +phpInterpSimpleBrackets xxx match /\[\h\w*]/ contained contains=phpBrackets,phpinterpSimpleBracketsInner + match /\[\d\+]/ contained contains=phpBrackets,phpinterpSimpleBracketsInner + match /\[0[xX]\x\+]/ contained contains=phpBrackets,phpinterpSimpleBracketsInner +phpInterpSimple xxx match /\$\h\w*\(\[[^]]*\]\|->\h\w*\)\?/ display contained contains=phpInterpSimpleBrackets,phpIdentifier,phpInterpSimpleError,phpMethods,phpMemberSelector +phpInterpVarname xxx match /\h\w*/ contained + links to Identifier +phpInterpMethodName xxx match /\h\w*/ contained +phpInterpSimpleCurly xxx match /\${\h\w*}/ contained extend contains=phpInterpVarname + links to Delimiter +phpInterpDollarCurley1Helper xxx matchgroup=phpParent start=/{/ end=/\[/ contained contains=phpInterpVarname +phpInterpDollarCurly1 xxx matchgroup=phpParent start=/\${\h\w*\[/rs=s+1 end=/]}/ contained extend contains=phpInterpDollarCurley1Helper,@phpClConst + links to Error +phpInterpDollarCurley2Helper xxx match /{\h\w*->/ contained contains=phpBrackets,phpInterpVarname,phpMemberSelector +phpInterpDollarCurly2 xxx matchgroup=phpParent start=/\${\h\w*->/rs=s+1 end=/}/ contained contains=phpInterpDollarCurley2Helper,phpInterpMethodName + links to Error +phpInterpComplex xxx matchgroup=phpParent start=/{\$/rs=e-1 end=/}/ contained extend contains=phpIdentifier,phpMemberSelector,phpVarSelector,phpIdentifierComplexP +phpMethodsVar xxx match /->\h\w*/ display contained contains=phpMethods,phpMemberSelector +phpInclude xxx contained use require require_once include include_once + links to Include +phpDefine xxx contained function new clone print echo + links to Define +phpBoolean xxx contained false true + links to Boolean +phpNumber xxx match /-\=\<\d\+\>/ display contained + match /\<0x\x\{1,8}\>/ display contained + links to Number +phpFloat xxx match /\(-\=\<\d+\|-\=\)\.\d\+\>/ display contained + links to Float +phpBackslashSequences xxx match /\\[fnrtv\\\"$]/ display contained + match /\\\d\{1,3}/ display contained contains=phpOctalError + match /\\x\x\{1,2}/ display contained + links to SpecialChar +phpOctalError xxx match /[89]/ display contained + links to Error +phpBackslashDoubleQuote xxx match /\\[\"]/ display contained + links to SpecialChar +phpBackslashSingleQuote xxx match /\\[\\']/ display contained + links to SpecialChar +phpTodo xxx contained todo fixme xxx + links to Todo +phpComment xxx start=+/\*+ end=+\*/+ contained extend contains=phpTodo + match /#.\{-}\(?>\|$\)\@=/ contained contains=phpTodo + match +//.\{-}\(?>\|$\)\@=+ contained contains=phpTodo + links to Comment +phpStringDouble xxx matchgroup=None start=/"/ skip=/\\\\\|\\"/ end=/"/ contained keepend extend contains=@phpAddStrings,phpBackslashSequences,phpBackslashDoubleQuote,@phpInterpDouble + links to String +phpBacktick xxx matchgroup=None start=/`/ skip=/\\\\\|\\"/ end=/`/ contained keepend extend contains=@phpAddStrings,phpIdentifier,phpBackslashSequences,phpIdentifierSimply,phpIdentifierComplex + links to String +phpStringSingle xxx matchgroup=None start=/'/ skip=/\\\\\|\\'/ end=/'/ contained keepend extend contains=@phpAddStrings,phpBackslashSingleQuote + links to String +phpHereDoc xxx matchgroup=Delimiter start=/\(<<<\)\@<=\(\"\=\)\z(\I\i*\)\2$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=phpIdentifier,phpIdentifierSimply,phpIdentifierComplex,phpBackslashSequences,phpMethodsVar + matchgroup=Delimiter start=/\(<<<\)\@<=\(\"\=\)\z(\(\I\i*\)\=\(html\)\c\(\i*\)\)\2$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@htmlTop,phpIdentifier,phpIdentifierSimply,phpIdentifierComplex,phpBackslashSequences,phpMethodsVar + matchgroup=Delimiter start=/\(<<<\)\@<=\(\"\=\)\z(\(\I\i*\)\=\(sql\)\c\(\i*\)\)\2$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@sqlTop,phpIdentifier,phpIdentifierSimply,phpIdentifierComplex,phpBackslashSequences,phpMethodsVar + matchgroup=Delimiter start=/\(<<<\)\@<=\(\"\=\)\z(\(\I\i*\)\=\(javascript\)\c\(\i*\)\)\2$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@htmlJavaScript,phpIdentifierSimply,phpIdentifier,phpIdentifierComplex,phpBackslashSequences,phpMethodsVar +phpNowDoc xxx matchgroup=Delimiter start=/\(<<<\)\@<='\z(\I\i*\)'$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend + matchgroup=Delimiter start=/\(<<<\)\@<='\z(\(\I\i*\)\=\(html\)\c\(\i*\)\)'$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@htmlTop + matchgroup=Delimiter start=/\(<<<\)\@<='\z(\(\I\i*\)\=\(sql\)\c\(\i*\)\)'$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@sqlTop + matchgroup=Delimiter start=/\(<<<\)\@<='\z(\(\I\i*\)\=\(javascript\)\c\(\i*\)\)'$/ end=/^\z1\(;\=$\)\@=/ contained keepend extend contains=@htmlJavaScript +phpException xxx contained catch try throw + links to Exception +phpStorageClass xxx contained final static protected public private global + links to StorageClass +phpSpecialFunction xxx containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle empty + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __construct + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __set + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __tostring + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __wakeup + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __set_state + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __isset + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __clone + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __call + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle unset + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle compact + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __get + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __destruct + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle extract + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __unset + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle isset + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle trigger_error + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier __sleep + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle eval + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar __autoload + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle user_error + links to phpOperator +phpClasses xxx containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar php_user_filter + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domprocessinginstruction + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar emptyiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar simplexmlelement + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar errorexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar directoryiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionextension + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domelement + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursivedirectoryiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionparameter + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar unexpectedvalueexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domdomerror + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domimplementationsource + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar pdorow + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnotation + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar invalidargumentexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar limititerator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar badmethodcallexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar spltempfileobject + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domcharacterdata + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnamednodemap + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar arrayobject + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domstringextend + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar arrayiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar pdo + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domuserdatahandler + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar xmlreader + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domerrorhandler + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domcomment + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnamespacenode + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domimplementation + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionmethod + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domconfiguration + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursivefilteriterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domentityreference + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar norewinditerator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar libxmlerror + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar underflowexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionfunction + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domtext + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar pdoexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar infiniteiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar splfileobject + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar runtimeexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar cachingiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar directory + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar badfunctioncallexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionclass + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar outofrangeexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domlocator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domdocumentfragment + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domentity + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnodelist + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursiveiteratoriterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar pdostatement + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar overflowexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionobject + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar splfileinfo + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar simplexmliterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domxpath + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domcdatasection + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar __php_incomplete_class + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domainexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar exception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnamelist + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar parentiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar xmlwriter + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar appenditerator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domnode + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar rangeexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar logicexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar iteratoriterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflectionproperty + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domstringlist + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domtypeinfo + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar outofboundsexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domimplementationlist + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar splobjectstorage + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursivearrayiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar lengthexception + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar stdclass + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursivecachingiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar filteriterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflection + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domdocumenttype + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domattr + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar domdocument + links to phpFunctions +phpInterfaces xxx containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar countable + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar iteratoraggregate + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar outeriterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar iterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar serializable + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar splobserver + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar arrayaccess + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar traversable + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar recursiveiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar seekableiterator + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar reflector + containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle,phpIdentifier,phpMethodsVar splsubject + links to phpConstant +phpAssignByRef xxx match /=\s*&/ containedin=ALLBUT,phpComment,phpStringDouble,phpStringSingle + links to Type +phpComparison xxx contained containedin=phpRegion instanceof + match /\v[=!]\=\=?/ contained containedin=phpRegion + match /\v[=<>-]@<![<>]\=?[<>]@!/ contained containedin=phpRegion + links to Statement +phpDocCustomTags xxx match /@[a-zA-Z]*\(\s\+\|\n\|\r\)/ containedin=phpComment + links to Type +phpDocTags xxx start=/{@\(example\|id\|internal\|inheritdoc\|link\|source\|toc\|tutorial\)/ end=/}/ containedin=phpComment + match /@\(abstract\|access\|author\|category\|copyright\|deprecated\|example\|final\|global\|ignore\|internal\|license\|link\|method\|name\|package\|param\|property\|return\|see\|since\|static\|staticvar\|subpackage\|tutorial\|uses\|var\|version\|contributor\|modified\|filename\|description\|filesource\|throws\)\(\s\+\)\?/ containedin=phpComment + links to PreProc +phpDocTodo xxx match /@\(todo\|fixme\|xxx\)\(\s\+\)\?/ containedin=phpComment + links to Todo +htmlPreproc cluster=phpRegion,phpRegionAsp,phpRegionSc +htmlArgCluster cluster=NONE +htmlTagNameCluster cluster=NONE +Spell cluster=NONE +htmlTop cluster=@Spell,htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLink,javaScript,@htmlPreproc +htmlJavaScript cluster=trailingWhitespace,literalTab,javaScriptLineComment,javaScriptCommentSkip,javaScriptComment,javaScriptSpecial,javaScriptStringD,javaScriptStringS,javaScriptSpecialCharacter,javaScriptNumber,javaScriptRegexpString,javaScriptConditional,javaScriptRepeat,javaScriptBranch,javaScriptOperator,javaScriptType,javaScriptStatement,javaScriptBoolean,javaScriptNull,javaScriptIdentifier,javaScriptLabel,javaScriptException,javaScriptMessage,javaScriptGlobal,javaScriptMember,javaScriptDeprecated,javaScriptReserved,javaScriptFunction,javaScriptBraces,javaScriptParens,@htmlPreproc +htmlVbScript cluster=vbConditional,vbOperator,vbBoolean,vbConst,vbRepeat,vbEvents,vbFunction,vbMethods,vbStatement,vbKeyword,vbTypes,vbDefine,vbNumber,vbFloat,vbString,vbComment,vbLineNumber,vbTypeSpecifier +htmlCss cluster=trailingWhitespace,literalTab,cssTagName,cssDeprecated,cssSelectorOp,cssSelectorOp2,cssUnicodeEscape,cssStringQ,cssStringQQ,cssAttributeSelector,cssClassName,cssIdentifier,cssComment,cssMediaBlock,cssInclude,cssDefinition,cssPseudoClass,cssPage,cssKeyFrame,cssFontDescriptor,cssFontProp,cssFontAttr,cssTextProp,cssBraceError,cssAttrComma,cssPseudoClassLang +cssColors cluster=cssColor800000,cssColorff0000,cssColorffA500,cssColorffff00,cssColor808000,cssColor800080,cssColorff00ff,cssColorffffff,cssColor00ff00,cssColor008000,cssColor000080,cssColor0000ff,cssColor00ffff,cssColor008080,cssColor000000,cssColorc0c0c0,cssColor808080,cssColorF0F8FF,cssColorFAEBD7,cssColor7FFFD4,cssColorF0FFFF,cssColorF5F5DC,cssColorFFE4C4,cssColorFFEBCD,cssColor8A2BE2,cssColorA52A2A,cssColorDEB887,cssColor5F9EA0,cssColor7FFF00,cssColorD2691E,cssColorFF7F50,cssColor6495ED,cssColorFFF8DC,cssColorDC143C,cssColor00008B,cssColor008B8B,cssColorB8860B,cssColorA9A9A9,cssColor006400,cssColorBDB76B,cssColor8B008B,cssColor556B2F,cssColorFF8C00,cssColor9932CC,cssColor8B0000,cssColorE9967A,cssColor8FBC8F,cssColor483D8B,cssColor2F4F4F,cssColor00CED1,cssColor9400D3,cssColorFF1493,cssColor00BFFF,cssColor696969,cssColor1E90FF,cssColorB22222,cssColorFFFAF0,cssColor228B22,cssColorDCDCDC,cssColorF8F8FF,cssColorFFD700,cssColorDAA520,cssColorADFF2F,cssColorF0FFF0,cssColorFF69B4,cssColorCD5C5C,cssColor4B0082,cssColorFFFFF0,cssColorF0E68C,cssColorE6E6FA,cssColorFFF0F5,cssColor7CFC00,cssColorFFFACD,cssColorADD8E6,cssColorF08080,cssColorE0FFFF,cssColorFAFAD2,cssColorD3D3D3,cssColor90EE90,cssColorFFB6C1,cssColorFFA07A,cssColor20B2AA,cssColor87CEFA,cssColor778899,cssColorB0C4DE,cssColorFFFFE0,cssColor32CD32,cssColorFAF0E6,cssColor66CDAA,cssColor0000CD,cssColorBA55D3,cssColor9370D8,cssColor3CB371,cssColor7B68EE,cssColor00FA9A,cssColor48D1CC,cssColorC71585,cssColor191970,cssColorF5FFFA,cssColorFFE4E1,cssColorFFE4B5,cssColorFFDEAD,cssColorFDF5E6,cssColor6B8E23,cssColorFF4500,cssColorDA70D6,cssColorEEE8AA,cssColor98FB98,cssColorAFEEEE,cssColorD87093,cssColorFFEFD5,cssColorFFDAB9,cssColorCD853F,cssColorFFC0CB,cssColorDDA0DD,cssColorB0E0E6,cssColorBC8F8F,cssColor4169E1,cssColor8B4513,cssColorFA8072,cssColorF4A460,cssColor2E8B57,cssColorFFF5EE,cssColorA0522D,cssColor87CEEB,cssColor6A5ACD,cssColor708090,cssColorFFFAFA,cssColor00FF7F,cssColor4682B4,cssColorD2B48C,cssColorD8BFD8,cssColorFF6347,cssColor40E0D0,cssColorEE82EE,cssColorF5DEB3,cssColorF5F5F5,cssColor9ACD32 +htmlLess cluster=trailingWhitespace,literalTab,cssTagName,cssDeprecated,cssSelectorOp,cssSelectorOp2,cssUnicodeEscape,cssStringQ,cssStringQQ,cssAttributeSelector,cssClassName,cssIdentifier,cssComment,cssMediaBlock,cssInclude,cssDefinition,cssPseudoClass,cssPage,cssKeyFrame,cssFontDescriptor,cssFontProp,cssFontAttr,cssTextProp,cssBraceError,cssAttrComma,cssPseudoClassLang,lessDefinition,lessComment,lessVariable +sqlTop cluster=sqlSpecial,sqlKeyword,sqlOperator,sqlStatement,sqlType,sqlNumber +phpClInside cluster=@phpClConst,phpComment,phpLabel,phpParent,phpParentError,phpInclude,phpHereDoc,phpNowDoc +phpClConst cluster=phpFunctions,phpIdentifier,phpConditional,phpRepeat,phpStatement,phpOperator,phpRelation,phpStringSingle,phpStringDouble,phpBacktick,phpNumber,phpFloat,phpKeyword,phpType,phpBoolean,phpStructure,phpMethodsVar,phpConstant,phpCoreConstant,phpException +phpInterpDouble cluster=phpInterpSimple,phpInterpSimpleCurly,phpInterpDollarCurly1,phpInterpDollarCurly2,phpInterpBogusDollarCurley,phpInterpComplex +phpAddStrings cluster=NONE +phpClFunction cluster=@phpClInside,phpDefine,phpParentError,phpStorageClass +phpClTop cluster=@phpClFunction,phpFoldFunction,phpFoldClass,phpFoldInterface,phpFoldTry,phpFoldCatch diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/python_syntax b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/python_syntax new file mode 100644 index 0000000..ec38776 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/testdata/python_syntax @@ -0,0 +1,63 @@ +--- Syntax items --- +cCustomFunc xxx match /\w\+\s*\((\)\@=/ + links to Function +cCustomClass xxx match /\w\+\s*\(::\)\@=/ + links to Function +pythonStatement xxx return True lambda + nextgroup=pythonFunction skipwhite def + del + nextgroup=pythonFunction skipwhite class + global nonlocal as None, False, yield with print continue break pass assert exec + links to Statement +pythonFunction xxx match /\%(\%(def\s\|class\s\|@\)\s*\)\@<=\h\%(\w\|\.\)*/ contained + links to Function +pythonConditional xxx if else elif + links to Conditional +pythonRepeat xxx for while + links to Repeat +pythonOperator xxx or is and in not + links to Operator +pythonException xxx finally raise except try + links to Exception +pythonInclude xxx from import + links to Include +pythonDecorator xxx match /@/ display nextgroup=pythonFunction skipwhite + links to Define +pythonTodo xxx contained NOTE XXX TODO NOTES FIXME + links to Todo +pythonComment xxx match /#.*$/ contains=pythonTodo,@Spell + links to Comment +pythonEscape xxx match /\\[abfnrtv'"\\]/ contained + match /\\\o\{1,3}/ contained + match /\\x\x\{2}/ contained + match /\%(\\u\x\{4}\|\\U\x\{8}\)/ contained + match /\\N{\a\+\%(\s\a\+\)*}/ contained + match /\\$/ + links to Special +pythonString xxx start=/[uU]\=\z(['"]\)/ skip=/\\\\\|\\\z1/ end=/\z1/ contains=pythonEscape,@Spell + start=/[uU]\=\z('''\|"""\)/ end=/\z1/ keepend contains=pythonEscape,pythonSpaceError,pythonDoctest,@Spell + links to String +pythonDoctest xxx start=/^\s*>>>\s/ end=/^\s*$/ contained contains=ALLBUT,pythonDoctest,@Spell + links to Special +pythonRawString xxx start=/[uU]\=[rR]\z(['"]\)/ skip=/\\\\\|\\\z1/ end=/\z1/ contains=@Spell + start=/[uU]\=[rR]\z('''\|"""\)/ end=/\z1/ keepend contains=pythonSpaceError,pythonDoctest,@Spell + links to String +pythonNumber xxx match /\<0[oO]\=\o\+[Ll]\=\>/ + match /\<0[xX]\x\+[Ll]\=\>/ + match /\<0[bB][01]\+[Ll]\=\>/ + match /\<\%([1-9]\d*\|0\)[Ll]\=\>/ + match /\<\d\+[jJ]\>/ + match /\<\d\+[eE][+-]\=\d\+[jJ]\=\>/ + match /\<\d\+\.\%([eE][+-]\=\d\+\)\=[jJ]\=\%(\W\|$\)\@=/ + match /\%(^\|\W\)\@<=\d*\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>/ + links to Number +pythonBuiltin xxx list locals all classmethod None abs cmp reduce ord hex object memoryview enumerate __debug__ compile str False True issubclass input hasattr frozenset slice callable sum filter range any long execfile min type sorted reload super complex xrange file ascii setattr unicode staticmethod basestring unichr float iter map globals max isinstance dict chr reversed buffer delattr __import__ oct dir eval raw_input hash getattr tuple id bin vars apply bytes repr pow print zip open NotImplemented intern round format bool help property coerce Ellipsis len int next exec set bytearray divmod + links to Function +pythonExceptions xxx OSError EnvironmentError UserWarning NameError ArithmeticError NotImplementedError ReferenceError BaseException LookupError ImportWarning OverflowError SystemExit IndentationError GeneratorExit Warning RuntimeError MemoryError WindowsError AssertionError UnicodeWarning KeyError TypeError TabError ImportError SyntaxWarning SyntaxError UnboundLocalError KeyboardInterrupt UnicodeDecodeError IOError Exception FutureWarning AttributeError UnicodeTranslateError VMSError EOFError FloatingPointError ValueError IndexError RuntimeWarning DeprecationWarning PendingDeprecationWarning UnicodeEncodeError StopIteration UnicodeError BytesWarning StandardError SystemError ZeroDivisionError BufferError + links to Structure +pythonDoctestValue xxx start=/^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\+/ end=/$/ contained + links to Define +OperatorChars xxx match #?\|+\|-\|\*\|;\|:\|,\|<\|>\|&\||\|!\|\~\|%\|=\|)\|(\|{\|}\|\.\|\[\|\]\|/\(/\|*\)\@!# +Spell cluster=NONE +NoSpell cluster=NONE + diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/vimsupport_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/vimsupport_test.py new file mode 100644 index 0000000..6840235 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/vimsupport_test.py @@ -0,0 +1,1434 @@ +# coding: utf-8 +# +# Copyright (C) 2015 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import ExtendedMock, MockVimModule, MockVimCommand +MockVimModule() + +from ycm import vimsupport +from nose.tools import eq_ +from hamcrest import assert_that, calling, raises, none, has_entry +from mock import MagicMock, call, patch +from ycmd.utils import ToBytes, ToUnicode +import os +import json + + +def ReplaceChunk_SingleLine_Repl_1_test(): + # Replace with longer range + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 1, 1, 5 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'How long', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "How long is a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 4 ) + + # and replace again, using delta + start, end = _BuildLocations( 1, 10, 1, 11 ) + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + ' piece of ', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( 'How long is a piece of string' ) ], result_buffer ) + eq_( new_line_offset, 0 ) + eq_( new_char_offset, 9 ) + eq_( line_offset, 0 ) + eq_( char_offset, 13 ) + + # and once more, for luck + start, end = _BuildLocations( 1, 11, 1, 17 ) + + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + 'pie', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( 'How long is a piece of pie' ) ], result_buffer ) + eq_( new_line_offset, 0 ) + eq_( new_char_offset, -3 ) + eq_( line_offset, 0 ) + eq_( char_offset, 10 ) + + +def ReplaceChunk_SingleLine_Repl_2_test(): + # Replace with shorter range + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 11, 1, 17 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'test', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is a test" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -2 ) + + +def ReplaceChunk_SingleLine_Repl_3_test(): + # Replace with equal range + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 6, 1, 8 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'be', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This be a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 0 ) + + +def ReplaceChunk_SingleLine_Add_1_test(): + # Insert at start + result_buffer = [ ToBytes( "is a string" ) ] + start, end = _BuildLocations( 1, 1, 1, 1 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'This ', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 5 ) + + +def ReplaceChunk_SingleLine_Add_2_test(): + # Insert at end + result_buffer = [ ToBytes( "This is a " ) ] + start, end = _BuildLocations( 1, 11, 1, 11 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'string', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 6 ) + + +def ReplaceChunk_SingleLine_Add_3_test(): + # Insert in the middle + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 8, 1, 8 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + ' not', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is not a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 4 ) + + +def ReplaceChunk_SingleLine_Del_1_test(): + # Delete from start + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 1, 1, 6 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + '', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "is a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -5 ) + + +def ReplaceChunk_SingleLine_Del_2_test(): + # Delete from end + result_buffer = [ ToBytes( "This is a string" ) ] + start, end = _BuildLocations( 1, 10, 1, 18 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + '', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is a" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -8 ) + + +def ReplaceChunk_SingleLine_Del_3_test(): + # Delete from middle + result_buffer = [ ToBytes( "This is not a string" ) ] + start, end = _BuildLocations( 1, 9, 1, 13 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + '', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This is a string" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -4 ) + + +def ReplaceChunk_SingleLine_Unicode_ReplaceUnicodeChars_test(): + # Replace Unicode characters. + result_buffer = [ ToBytes( "This Uniçø∂‰ string is in the middle" ) ] + start, end = _BuildLocations( 1, 6, 1, 20 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Unicode ', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This Unicode string is in the middle" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -6 ) + + +def ReplaceChunk_SingleLine_Unicode_ReplaceAfterUnicode_test(): + # Replace ASCII characters after Unicode characters in the line. + result_buffer = [ ToBytes( "This Uniçø∂‰ string is in the middle" ) ] + start, end = _BuildLocations( 1, 30, 1, 43 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'fåke', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "This Uniçø∂‰ string is fåke" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -8 ) + + +def ReplaceChunk_SingleLine_Unicode_Grown_test(): + # Replace ASCII characters after Unicode characters in the line. + result_buffer = [ ToBytes( "a" ) ] + start, end = _BuildLocations( 1, 1, 1, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'å', + 0, + 0, + result_buffer ) + + eq_( [ ToBytes( "å" ) ], result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 1 ) # Note: byte difference (a = 1 byte, å = 2 bytes) + + +def ReplaceChunk_RemoveSingleLine_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 1, 3, 1 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, -1 ) + eq_( char_offset, 0 ) + + +def ReplaceChunk_SingleToMultipleLines_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 1 ) + eq_( char_offset, 1 ) + + # now make another change to the "2nd" line + start, end = _BuildLocations( 2, 3, 2, 4 ) + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + 'cccc', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFBcccc" ), + ToBytes( "aCa" ) ], result_buffer ) + eq_( line_offset, 1 ) + eq_( char_offset, 4 ) + + +def ReplaceChunk_SingleToMultipleLines2_test(): + result_buffer = [ ToBytes( "aAa" ), ToBytes( "aBa" ), ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Eb\nbFb\nG', + 0, + 0, + result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "GBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 2 ) + eq_( char_offset, 0 ) + + +def ReplaceChunk_SingleToMultipleLines3_test(): + result_buffer = [ ToBytes( "aAa" ), ToBytes( "aBa" ), ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Eb\nbFb\nbGb', + 0, + 0, + result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "bGbBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 2 ) + eq_( char_offset, 2 ) + + +def ReplaceChunk_SingleToMultipleLinesReplace_test(): + result_buffer = [ ToBytes( "aAa" ), ToBytes( "aBa" ), ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 2, 1, 4 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Eb\nbFb\nbGb', + 0, + 0, + result_buffer ) + expected_buffer = [ ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "bGb" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 2 ) + eq_( char_offset, 0 ) + + +def ReplaceChunk_SingleToMultipleLinesReplace_2_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 2, 1, 4 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Eb\nbFb\nbGb', + 0, + 0, + result_buffer ) + expected_buffer = [ ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "bGb" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 2 ) + eq_( char_offset, 0 ) + + # now do a subsequent change (insert at end of line "1") + start, end = _BuildLocations( 1, 4, 1, 4 ) + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + 'cccc', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "bGbcccc" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ], result_buffer ) + + eq_( line_offset, 2 ) + eq_( char_offset, 4 ) + + +def ReplaceChunk_MultipleLinesToSingleLine_test(): + result_buffer = [ ToBytes( "aAa" ), ToBytes( "aBa" ), ToBytes( "aCaaaa" ) ] + start, end = _BuildLocations( 2, 2, 3, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'E', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), ToBytes( "aECaaaa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, -1 ) + eq_( char_offset, 1 ) + + # make another modification applying offsets + start, end = _BuildLocations( 3, 3, 3, 4 ) + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + 'cccc', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( "aAa" ), + ToBytes( "aECccccaaa" ) ], result_buffer ) + eq_( line_offset, -1 ) + eq_( char_offset, 4 ) + + # and another, for luck + start, end = _BuildLocations( 3, 4, 3, 5 ) + ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( + start, + end, + 'dd\ndd', + line_offset, + char_offset, + result_buffer ) + + line_offset += new_line_offset + char_offset += new_char_offset + + eq_( [ ToBytes( "aAa" ), + ToBytes( "aECccccdd" ), + ToBytes( "ddaa" ) ], + result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -2 ) + + +def ReplaceChunk_MultipleLinesToSameMultipleLines_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ), + ToBytes( "aDe" ) ] + start, end = _BuildLocations( 2, 2, 3, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFCa" ), + ToBytes( "aDe" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 1 ) + + +def ReplaceChunk_MultipleLinesToMoreMultipleLines_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ), + ToBytes( "aDe" ) ] + start, end = _BuildLocations( 2, 2, 3, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'Eb\nbFb\nbG', + 0, + 0, + result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aEb" ), + ToBytes( "bFb" ), + ToBytes( "bGCa" ), + ToBytes( "aDe" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 1 ) + eq_( char_offset, 1 ) + + +def ReplaceChunk_MultipleLinesToLessMultipleLines_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ), + ToBytes( "aDe" ) ] + start, end = _BuildLocations( 1, 2, 3, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aEb" ), ToBytes( "bFCa" ), ToBytes( "aDe" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, -1 ) + eq_( char_offset, 1 ) + + +def ReplaceChunk_MultipleLinesToEvenLessMultipleLines_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ), + ToBytes( "aDe" ) ] + start, end = _BuildLocations( 1, 2, 4, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aEb" ), ToBytes( "bFDe" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, -2 ) + eq_( char_offset, 1 ) + + +def ReplaceChunk_SpanBufferEdge_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 1, 1, 3 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "bDba" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 1 ) + + +def ReplaceChunk_DeleteTextInLine_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 3 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, -1 ) + + +def ReplaceChunk_AddTextInLine_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "abDbBa" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 3 ) + + +def ReplaceChunk_ReplaceTextInLine_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 2, 2, 2, 3 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', + 0, 0, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "abDba" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 2 ) + + +def ReplaceChunk_SingleLineOffsetWorks_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 1, 1, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', + 1, 1, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "abDba" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 0 ) + eq_( char_offset, 2 ) + + +def ReplaceChunk_SingleLineToMultipleLinesOffsetWorks_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 1, 1, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Db\nE', + 1, 1, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "aDb" ), + ToBytes( "Ea" ), + ToBytes( "aCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 1 ) + eq_( char_offset, -1 ) + + +def ReplaceChunk_MultipleLinesToSingleLineOffsetWorks_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 1, 1, 2, 2 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', + 1, 1, result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "abDbCa" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, -1 ) + eq_( char_offset, 3 ) + + +def ReplaceChunk_MultipleLineOffsetWorks_test(): + result_buffer = [ ToBytes( "aAa" ), + ToBytes( "aBa" ), + ToBytes( "aCa" ) ] + start, end = _BuildLocations( 3, 1, 4, 3 ) + ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, + end, + 'bDb\nbEb\nbFb', + -1, + 1, + result_buffer ) + expected_buffer = [ ToBytes( "aAa" ), + ToBytes( "abDb" ), + ToBytes( "bEb" ), + ToBytes( "bFba" ) ] + eq_( expected_buffer, result_buffer ) + eq_( line_offset, 1 ) + eq_( char_offset, 1 ) + + +def _BuildLocations( start_line, start_column, end_line, end_column ): + return { + 'line_num' : start_line, + 'column_num': start_column, + }, { + 'line_num' : end_line, + 'column_num': end_column, + } + + +def ReplaceChunksInBuffer_SortedChunks_test(): + chunks = [ + _BuildChunk( 1, 4, 1, 4, '('), + _BuildChunk( 1, 11, 1, 11, ')' ) + ] + + result_buffer = [ ToBytes( "CT<10 >> 2> ct" ) ] + vimsupport.ReplaceChunksInBuffer( chunks, result_buffer, None ) + + expected_buffer = [ ToBytes( "CT<(10 >> 2)> ct" ) ] + eq_( expected_buffer, result_buffer ) + + +def ReplaceChunksInBuffer_UnsortedChunks_test(): + chunks = [ + _BuildChunk( 1, 11, 1, 11, ')'), + _BuildChunk( 1, 4, 1, 4, '(' ) + ] + + result_buffer = [ ToBytes( "CT<10 >> 2> ct" ) ] + vimsupport.ReplaceChunksInBuffer( chunks, result_buffer, None ) + + expected_buffer = [ ToBytes( "CT<(10 >> 2)> ct" ) ] + eq_( expected_buffer, result_buffer ) + + +class MockBuffer( object ): + """An object that looks like a vim.buffer object, enough for ReplaceChunk to + generate a location list""" + + def __init__( self, lines, name, number ): + self.lines = [ ToBytes( x ) for x in lines ] + self.name = name + self.number = number + + + def __getitem__( self, index ): + """ Return the bytes for a given line at index |index| """ + return self.lines[ index ] + + + def __len__( self ): + return len( self.lines ) + + + def __setitem__( self, key, value ): + return self.lines.__setitem__( key, value ) + + + def GetLines( self ): + """ Return the contents of the buffer as a list of unicode strings""" + return [ ToUnicode( x ) for x in self.lines ] + + +@patch( 'ycm.vimsupport.VariableExists', return_value = False ) +@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' ) +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', + return_value=1, + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.BufferIsVisible', + return_value=True, + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.OpenFilename' ) +@patch( 'ycm.vimsupport.EchoTextVimWidth', new_callable=ExtendedMock ) +@patch( 'vim.eval', new_callable=ExtendedMock ) +@patch( 'vim.command', new_callable=ExtendedMock ) +def ReplaceChunks_SingleFile_Open_test( vim_command, + vim_eval, + echo_text_vim_width, + open_filename, + buffer_is_visible, + get_buffer_number_for_filename, + set_fitting_height, + variable_exists ): + + chunks = [ + _BuildChunk( 1, 1, 2, 1, 'replacement', 'single_file' ) + ] + + result_buffer = MockBuffer( [ + 'line1', + 'line2', + 'line3', + ], 'single_file', 1 ) + + with patch( 'vim.buffers', [ None, result_buffer, None ] ): + vimsupport.ReplaceChunks( chunks ) + + # Ensure that we applied the replacement correctly + eq_( result_buffer.GetLines(), [ + 'replacementline2', + 'line3', + ] ) + + # GetBufferNumberForFilename is called twice: + # - once to the check if we would require opening the file (so that we can + # raise a warning) + # - once whilst applying the changes + get_buffer_number_for_filename.assert_has_exact_calls( [ + call( 'single_file', False ), + call( 'single_file', False ), + ] ) + + # BufferIsVisible is called twice for the same reasons as above + buffer_is_visible.assert_has_exact_calls( [ + call( 1 ), + call( 1 ), + ] ) + + # we don't attempt to open any files + open_filename.assert_not_called() + + # But we do set the quickfix list + vim_eval.assert_has_exact_calls( [ + call( 'setqflist( {0} )'.format( json.dumps( [ { + 'bufnr': 1, + 'filename': 'single_file', + 'lnum': 1, + 'col': 1, + 'text': 'replacement', + 'type': 'F' + } ] ) ) ), + ] ) + vim_command.assert_has_exact_calls( [ + call( 'botright copen' ), + call( 'silent! wincmd p' ) + ] ) + set_fitting_height.assert_called_once_with() + + # And it is ReplaceChunks that prints the message showing the number of + # changes + echo_text_vim_width.assert_has_exact_calls( [ + call( 'Applied 1 changes' ), + ] ) + + +@patch( 'ycm.vimsupport.VariableExists', return_value = False ) +@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' ) +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', + side_effect=[ -1, -1, 1 ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.BufferIsVisible', + side_effect=[ False, False, True ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.OpenFilename', + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.EchoTextVimWidth', new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.Confirm', + return_value=True, + new_callable=ExtendedMock ) +@patch( 'vim.eval', return_value=10, new_callable=ExtendedMock ) +@patch( 'vim.command', new_callable=ExtendedMock ) +def ReplaceChunks_SingleFile_NotOpen_test( vim_command, + vim_eval, + confirm, + echo_text_vim_width, + open_filename, + buffer_is_visible, + get_buffer_number_for_filename, + set_fitting_height, + variable_exists ): + + chunks = [ + _BuildChunk( 1, 1, 2, 1, 'replacement', 'single_file' ) + ] + + result_buffer = MockBuffer( [ + 'line1', + 'line2', + 'line3', + ], 'single_file', 1 ) + + with patch( 'vim.buffers', [ None, result_buffer, None ] ): + vimsupport.ReplaceChunks( chunks ) + + # We checked if it was OK to open the file + confirm.assert_has_exact_calls( [ + call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) ) + ] ) + + # Ensure that we applied the replacement correctly + eq_( result_buffer.GetLines(), [ + 'replacementline2', + 'line3', + ] ) + + # GetBufferNumberForFilename is called 3 times. The return values are set in + # the @patch call above: + # - once to the check if we would require opening the file (so that we can + # raise a warning) (-1 return) + # - once whilst applying the changes (-1 return) + # - finally after calling OpenFilename (1 return) + get_buffer_number_for_filename.assert_has_exact_calls( [ + call( 'single_file', False ), + call( 'single_file', False ), + call( 'single_file', False ), + ] ) + + # BufferIsVisible is called 3 times for the same reasons as above, with the + # return of each one + buffer_is_visible.assert_has_exact_calls( [ + call( -1 ), + call( -1 ), + call( 1 ), + ] ) + + # We open 'single_file' as expected. + open_filename.assert_called_with( 'single_file', { + 'focus': True, + 'fix': True, + 'size': 10 + } ) + + # And close it again, then show the quickfix window. + vim_command.assert_has_exact_calls( [ + call( 'lclose' ), + call( 'hide' ), + call( 'botright copen' ), + call( 'silent! wincmd p' ) + ] ) + set_fitting_height.assert_called_once_with() + + # And update the quickfix list + vim_eval.assert_has_exact_calls( [ + call( '&previewheight' ), + call( 'setqflist( {0} )'.format( json.dumps( [ { + 'bufnr': 1, + 'filename': 'single_file', + 'lnum': 1, + 'col': 1, + 'text': 'replacement', + 'type': 'F' + } ] ) ) ), + ] ) + + # And it is ReplaceChunks that prints the message showing the number of + # changes + echo_text_vim_width.assert_has_exact_calls( [ + call( 'Applied 1 changes' ), + ] ) + + +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', + side_effect=[ -1, -1, 1 ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.BufferIsVisible', + side_effect=[ False, False, True ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.OpenFilename', + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.EchoTextVimWidth', + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.Confirm', + return_value=False, + new_callable=ExtendedMock ) +@patch( 'vim.eval', + return_value=10, + new_callable=ExtendedMock ) +@patch( 'vim.command', new_callable=ExtendedMock ) +def ReplaceChunks_User_Declines_To_Open_File_test( + vim_command, + vim_eval, + confirm, + echo_text_vim_width, + open_filename, + buffer_is_visible, + get_buffer_number_for_filename ): + + # Same as above, except the user selects Cancel when asked if they should + # allow us to open lots of (ahem, 1) file. + + chunks = [ + _BuildChunk( 1, 1, 2, 1, 'replacement', 'single_file' ) + ] + + result_buffer = MockBuffer( [ + 'line1', + 'line2', + 'line3', + ], 'single_file', 1 ) + + with patch( 'vim.buffers', [ None, result_buffer, None ] ): + vimsupport.ReplaceChunks( chunks ) + + # We checked if it was OK to open the file + confirm.assert_has_exact_calls( [ + call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) ) + ] ) + + # Ensure that buffer is not changed + eq_( result_buffer.GetLines(), [ + 'line1', + 'line2', + 'line3', + ] ) + + # GetBufferNumberForFilename is called once. The return values are set in + # the @patch call above: + # - once to the check if we would require opening the file (so that we can + # raise a warning) (-1 return) + get_buffer_number_for_filename.assert_has_exact_calls( [ + call( 'single_file', False ), + ] ) + + # BufferIsVisible is called once for the above file, which wasn't visible. + buffer_is_visible.assert_has_exact_calls( [ + call( -1 ), + ] ) + + # We don't attempt to open any files or update any quickfix list or anything + # like that + open_filename.assert_not_called() + vim_eval.assert_not_called() + vim_command.assert_not_called() + echo_text_vim_width.assert_not_called() + + +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', + side_effect=[ -1, -1, 1 ], + new_callable=ExtendedMock ) +# Key difference is here: In the final check, BufferIsVisible returns False +@patch( 'ycm.vimsupport.BufferIsVisible', + side_effect=[ False, False, False ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.OpenFilename', + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.EchoTextVimWidth', + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.Confirm', + return_value=True, + new_callable=ExtendedMock ) +@patch( 'vim.eval', + return_value=10, + new_callable=ExtendedMock ) +@patch( 'vim.command', + new_callable=ExtendedMock ) +def ReplaceChunks_User_Aborts_Opening_File_test( + vim_command, + vim_eval, + confirm, + echo_text_vim_width, + open_filename, + buffer_is_visible, + get_buffer_number_for_filename ): + + # Same as above, except the user selects Abort or Quick during the + # "swap-file-found" dialog + + chunks = [ + _BuildChunk( 1, 1, 2, 1, 'replacement', 'single_file' ) + ] + + result_buffer = MockBuffer( [ + 'line1', + 'line2', + 'line3', + ], 'single_file', 1 ) + + with patch( 'vim.buffers', [ None, result_buffer, None ] ): + assert_that( calling( vimsupport.ReplaceChunks ).with_args( chunks ), + raises( RuntimeError, + 'Unable to open file: single_file\nFixIt/Refactor operation ' + 'aborted prior to completion. Your files have not been ' + 'fully updated. Please use undo commands to revert the ' + 'applied changes.' ) ) + + # We checked if it was OK to open the file + confirm.assert_has_exact_calls( [ + call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) ) + ] ) + + # Ensure that buffer is not changed + eq_( result_buffer.GetLines(), [ + 'line1', + 'line2', + 'line3', + ] ) + + # We tried to open this file + open_filename.assert_called_with( "single_file", { + 'focus': True, + 'fix': True, + 'size': 10 + } ) + vim_eval.assert_called_with( "&previewheight" ) + + # But raised an exception before issuing the message at the end + echo_text_vim_width.assert_not_called() + + +@patch( 'ycm.vimsupport.VariableExists', return_value = False ) +@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' ) +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', side_effect=[ + 22, # first_file (check) + -1, # another_file (check) + 22, # first_file (apply) + -1, # another_file (apply) + 19, # another_file (check after open) + ], + new_callable=ExtendedMock ) +@patch( 'ycm.vimsupport.BufferIsVisible', side_effect=[ + True, # first_file (check) + False, # second_file (check) + True, # first_file (apply) + False, # second_file (apply) + True, # side_effect (check after open) + ], + new_callable=ExtendedMock) +@patch( 'ycm.vimsupport.OpenFilename', + new_callable=ExtendedMock) +@patch( 'ycm.vimsupport.EchoTextVimWidth', + new_callable=ExtendedMock) +@patch( 'ycm.vimsupport.Confirm', return_value=True, + new_callable=ExtendedMock) +@patch( 'vim.eval', return_value=10, + new_callable=ExtendedMock) +@patch( 'vim.command', + new_callable=ExtendedMock) +def ReplaceChunks_MultiFile_Open_test( vim_command, + vim_eval, + confirm, + echo_text_vim_width, + open_filename, + buffer_is_visible, + get_buffer_number_for_filename, + set_fitting_height, + variable_exists ): + + # Chunks are split across 2 files, one is already open, one isn't + + chunks = [ + _BuildChunk( 1, 1, 2, 1, 'first_file_replacement ', '1_first_file' ), + _BuildChunk( 2, 1, 2, 1, 'second_file_replacement ', '2_another_file' ), + ] + + first_file = MockBuffer( [ + 'line1', + 'line2', + 'line3', + ], '1_first_file', 22 ) + another_file = MockBuffer( [ + 'another line1', + 'ACME line2', + ], '2_another_file', 19 ) + + vim_buffers = [ None ] * 23 + vim_buffers[ 22 ] = first_file + vim_buffers[ 19 ] = another_file + + with patch( 'vim.buffers', vim_buffers ): + vimsupport.ReplaceChunks( chunks ) + + # We checked for the right file names + get_buffer_number_for_filename.assert_has_exact_calls( [ + call( '1_first_file', False ), + call( '2_another_file', False ), + call( '1_first_file', False ), + call( '2_another_file', False ), + call( '2_another_file', False ), + ] ) + + # We checked if it was OK to open the file + confirm.assert_has_exact_calls( [ + call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) ) + ] ) + + # Ensure that buffers are updated + eq_( another_file.GetLines(), [ + 'another line1', + 'second_file_replacement ACME line2', + ] ) + eq_( first_file.GetLines(), [ + 'first_file_replacement line2', + 'line3', + ] ) + + # We open '2_another_file' as expected. + open_filename.assert_called_with( '2_another_file', { + 'focus': True, + 'fix': True, + 'size': 10 + } ) + + # And close it again, then show the quickfix window. + vim_command.assert_has_exact_calls( [ + call( 'lclose' ), + call( 'hide' ), + call( 'botright copen' ), + call( 'silent! wincmd p' ) + ] ) + set_fitting_height.assert_called_once_with() + + # And update the quickfix list with each entry + vim_eval.assert_has_exact_calls( [ + call( '&previewheight' ), + call( 'setqflist( {0} )'.format( json.dumps( [ { + 'bufnr': 22, + 'filename': '1_first_file', + 'lnum': 1, + 'col': 1, + 'text': 'first_file_replacement ', + 'type': 'F' + }, { + 'bufnr': 19, + 'filename': '2_another_file', + 'lnum': 2, + 'col': 1, + 'text': 'second_file_replacement ', + 'type': 'F' + } ] ) ) ), + ] ) + + # And it is ReplaceChunks that prints the message showing the number of + # changes + echo_text_vim_width.assert_has_exact_calls( [ + call( 'Applied 2 changes' ), + ] ) + + +def _BuildChunk( start_line, + start_column, + end_line, + end_column, + replacement_text, filepath='test_file_name' ): + return { + 'range': { + 'start': { + 'filepath': filepath, + 'line_num': start_line, + 'column_num': start_column, + }, + 'end': { + 'filepath': filepath, + 'line_num': end_line, + 'column_num': end_column, + }, + }, + 'replacement_text': replacement_text + } + + +@patch( 'vim.command', new_callable=ExtendedMock ) +@patch( 'vim.current', new_callable=ExtendedMock) +def WriteToPreviewWindow_test( vim_current, vim_command ): + vim_current.window.options.__getitem__ = MagicMock( return_value = True ) + + vimsupport.WriteToPreviewWindow( "test" ) + + vim_command.assert_has_exact_calls( [ + call( 'silent! pclose!' ), + call( 'silent! pedit! _TEMP_FILE_' ), + call( 'silent! wincmd P' ), + call( 'silent! wincmd p' ) ] ) + + vim_current.buffer.__setitem__.assert_called_with( + slice( None, None, None ), [ 'test' ] ) + + vim_current.buffer.options.__setitem__.assert_has_exact_calls( [ + call( 'modifiable', True ), + call( 'readonly', False ), + call( 'buftype', 'nofile' ), + call( 'swapfile', False ), + call( 'modifiable', False ), + call( 'modified', False ), + call( 'readonly', True ), + ], any_order = True ) + + +@patch( 'vim.current' ) +def WriteToPreviewWindow_MultiLine_test( vim_current ): + vim_current.window.options.__getitem__ = MagicMock( return_value = True ) + vimsupport.WriteToPreviewWindow( "test\ntest2" ) + + vim_current.buffer.__setitem__.assert_called_with( + slice( None, None, None ), [ 'test', 'test2' ] ) + + +@patch( 'vim.command', new_callable=ExtendedMock ) +@patch( 'vim.current', new_callable=ExtendedMock ) +def WriteToPreviewWindow_JumpFail_test( vim_current, vim_command ): + vim_current.window.options.__getitem__ = MagicMock( return_value = False ) + + vimsupport.WriteToPreviewWindow( "test" ) + + vim_command.assert_has_exact_calls( [ + call( 'silent! pclose!' ), + call( 'silent! pedit! _TEMP_FILE_' ), + call( 'silent! wincmd P' ), + call( "echom 'test'" ), + ] ) + + vim_current.buffer.__setitem__.assert_not_called() + vim_current.buffer.options.__setitem__.assert_not_called() + + +@patch( 'vim.command', new_callable=ExtendedMock ) +@patch( 'vim.current', new_callable=ExtendedMock ) +def WriteToPreviewWindow_JumpFail_MultiLine_test( vim_current, vim_command ): + + vim_current.window.options.__getitem__ = MagicMock( return_value = False ) + + vimsupport.WriteToPreviewWindow( "test\ntest2" ) + + vim_command.assert_has_exact_calls( [ + call( 'silent! pclose!' ), + call( 'silent! pedit! _TEMP_FILE_' ), + call( 'silent! wincmd P' ), + call( "echom 'test'" ), + call( "echom 'test2'" ), + ] ) + + vim_current.buffer.__setitem__.assert_not_called() + vim_current.buffer.options.__setitem__.assert_not_called() + + +def CheckFilename_test(): + assert_that( + calling( vimsupport.CheckFilename ).with_args( None ), + raises( RuntimeError, "'None' is not a valid filename" ) + ) + + assert_that( + calling( vimsupport.CheckFilename ).with_args( 'nonexistent_file' ), + raises( RuntimeError, + "filename 'nonexistent_file' cannot be opened. " + "No such file or directory." ) + ) + + assert_that( vimsupport.CheckFilename( __file__ ), none() ) + + +def BufferIsVisibleForFilename_test(): + buffers = [ + { + 'number': 1, + 'filename': os.path.realpath( 'visible_filename' ), + 'window': 1 + }, + { + 'number': 2, + 'filename': os.path.realpath( 'hidden_filename' ), + } + ] + + with patch( 'vim.buffers', buffers ): + eq_( vimsupport.BufferIsVisibleForFilename( 'visible_filename' ), True ) + eq_( vimsupport.BufferIsVisibleForFilename( 'hidden_filename' ), False ) + eq_( vimsupport.BufferIsVisibleForFilename( 'another_filename' ), False ) + + +@patch( 'ycm.vimsupport.GetBufferNumberForFilename', + side_effect = [ 2, 5, -1 ] ) +@patch( 'vim.command', + side_effect = MockVimCommand, + new_callable = ExtendedMock ) +def CloseBuffersForFilename_test( vim_command, *args ): + vimsupport.CloseBuffersForFilename( 'some_filename' ) + + vim_command.assert_has_exact_calls( [ + call( 'silent! bwipeout! 2' ), + call( 'silent! bwipeout! 5' ) + ], any_order = True ) + + +@patch( 'vim.command', new_callable = ExtendedMock ) +@patch( 'vim.current', new_callable = ExtendedMock ) +def OpenFilename_test( vim_current, vim_command ): + # Options used to open a logfile + options = { + 'size': vimsupport.GetIntValue( '&previewheight' ), + 'fix': True, + 'watch': True, + 'position': 'end' + } + + vimsupport.OpenFilename( __file__, options ) + + vim_command.assert_has_exact_calls( [ + call( '12split {0}'.format( __file__ ) ), + call( "exec " + "'au BufEnter <buffer> :silent! checktime {0}'".format( __file__ ) ), + call( 'silent! normal G zz' ), + call( 'silent! wincmd p' ) + ] ) + + vim_current.buffer.options.__setitem__.assert_has_exact_calls( [ + call( 'autoread', True ), + ] ) + + vim_current.window.options.__setitem__.assert_has_exact_calls( [ + call( 'winfixheight', True ) + ] ) + + +@patch( 'ycm.vimsupport.BufferModified', side_effect = [ True ] ) +@patch( 'ycm.vimsupport.FiletypesForBuffer', side_effect = [ [ 'cpp' ] ] ) +def GetUnsavedAndCurrentBufferData_EncodedUnicodeCharsInBuffers_test( *args ): + mock_buffer = MagicMock() + mock_buffer.name = os.path.realpath( 'filename' ) + mock_buffer.number = 1 + mock_buffer.__iter__.return_value = [ u'abc', ToBytes( u'fДa' ) ] + + with patch( 'vim.buffers', [ mock_buffer ] ): + assert_that( vimsupport.GetUnsavedAndCurrentBufferData(), + has_entry( mock_buffer.name, + has_entry( u'contents', u'abc\nfДa\n' ) ) ) + + +# NOTE: Vim returns byte offsets for columns, not actual character columns. This +# makes 'ДД' have 4 columns: column 0, column 2 and column 4. +@patch( 'vim.current.line', ToBytes( 'ДДaa' ) ) +@patch( 'ycm.vimsupport.CurrentColumn', side_effect = [ 4 ] ) +def TextBeforeCursor_EncodedUnicode_test( *args ): + eq_( vimsupport.TextBeforeCursor(), u'ДД' ) + + +# NOTE: Vim returns byte offsets for columns, not actual character columns. This +# makes 'ДД' have 4 columns: column 0, column 2 and column 4. +@patch( 'vim.current.line', ToBytes( 'aaДД' ) ) +@patch( 'ycm.vimsupport.CurrentColumn', side_effect = [ 2 ] ) +def TextAfterCursor_EncodedUnicode_test( *args ): + eq_( vimsupport.TextAfterCursor(), u'ДД' ) + + +@patch( 'vim.current.line', ToBytes( 'fДa' ) ) +def CurrentLineContents_EncodedUnicode_test( *args ): + eq_( vimsupport.CurrentLineContents(), u'fДa' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_IntAsUnicode_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( '123' ), 123 ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_IntAsBytes_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( ToBytes( '123' ) ), 123 ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_StringAsUnicode_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( 'foo' ), 'foo' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_StringAsBytes_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( ToBytes( 'foo' ) ), 'foo' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_ListPassthrough_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( [ 1, 2 ] ), [ 1, 2 ] ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_ObjectPassthrough_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( { 1: 2 } ), { 1: 2 } ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_GeneratorPassthrough_test( *args ): + gen = ( x**2 for x in [ 1, 2, 3 ] ) + eq_( vimsupport.VimExpressionToPythonType( gen ), gen ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/tests/youcompleteme_test.py b/vim/bundle/YouCompleteMe/python/ycm/tests/youcompleteme_test.py new file mode 100644 index 0000000..eb04b80 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/tests/youcompleteme_test.py @@ -0,0 +1,47 @@ +# Copyright (C) 2016 YouCompleteMe contributors +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from ycm.test_utils import MockVimModule +MockVimModule() + +import sys +from mock import MagicMock +from hamcrest import assert_that, is_in, is_not + +from ycm.youcompleteme import YouCompleteMe + + +class YouCompleteMe_test(): + + def setUp( self ): + self.ycm = YouCompleteMe( MagicMock( spec_set = dict ) ) + + + def tearDown( self ): + self.ycm.OnVimLeave() + + + def YcmCoreNotImported_test( self ): + assert_that( 'ycm_core', is_not( is_in( sys.modules ) ) ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/unsafe_thread_pool_executor.py b/vim/bundle/YouCompleteMe/python/ycm/unsafe_thread_pool_executor.py new file mode 100644 index 0000000..666aebc --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/unsafe_thread_pool_executor.py @@ -0,0 +1,120 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. +# +# Copyright (C) 2013 Google Inc. +# Changes to this file are licensed under the same terms as the original file +# (the Python Software Foundation License). + + +from __future__ import with_statement +import threading +import weakref +import sys + +from concurrent.futures import _base + +try: + import queue +except ImportError: + import Queue as queue + + +# This file provides an UnsafeThreadPoolExecutor, which operates exactly like +# the upstream Python version of ThreadPoolExecutor with one exception: it +# doesn't wait for worker threads to finish before shutting down the Python +# interpreter. +# +# This is dangerous for many workloads, but fine for some (like when threads +# only send network requests). The YCM workload is one of those workloads where +# it's safe (the aforementioned network requests case). + +class _WorkItem(object): + def __init__(self, future, fn, args, kwargs): + self.future = future + self.fn = fn + self.args = args + self.kwargs = kwargs + + def run(self): + if not self.future.set_running_or_notify_cancel(): + return + + try: + result = self.fn(*self.args, **self.kwargs) + except BaseException: + e = sys.exc_info()[1] + self.future.set_exception(e) + else: + self.future.set_result(result) + + +def _worker(executor_reference, work_queue): + try: + while True: + work_item = work_queue.get(block=True) + if work_item is not None: + work_item.run() + continue + executor = executor_reference() + # Exit if: + # - The executor that owns the worker has been collected OR + # - The executor that owns the worker has been shutdown. + if executor is None or executor._shutdown: + # Notice other workers + work_queue.put(None) + return + del executor + except BaseException: + _base.LOGGER.critical('Exception in worker', exc_info=True) + + +class UnsafeThreadPoolExecutor(_base.Executor): + def __init__(self, max_workers): + """Initializes a new ThreadPoolExecutor instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + """ + self._max_workers = max_workers + self._work_queue = queue.Queue() + self._threads = set() + self._shutdown = False + self._shutdown_lock = threading.Lock() + + def submit(self, fn, *args, **kwargs): + with self._shutdown_lock: + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + + f = _base.Future() + w = _WorkItem(f, fn, args, kwargs) + + self._work_queue.put(w) + self._adjust_thread_count() + return f + submit.__doc__ = _base.Executor.submit.__doc__ + + def _adjust_thread_count(self): + # When the executor gets lost, the weakref callback will wake up + # the worker threads. + def weakref_cb(_, q=self._work_queue): + q.put(None) + # TODO(bquinlan): Should avoid creating new threads if there are more + # idle threads than items in the work queue. + if len(self._threads) < self._max_workers: + t = threading.Thread(target=_worker, + args=(weakref.ref(self, weakref_cb), + self._work_queue)) + t.daemon = True + t.start() + self._threads.add(t) + + def shutdown(self, wait=True): + with self._shutdown_lock: + self._shutdown = True + self._work_queue.put(None) + if wait: + for t in self._threads: + t.join() + shutdown.__doc__ = _base.Executor.shutdown.__doc__ diff --git a/vim/bundle/YouCompleteMe/python/ycm/vimsupport.py b/vim/bundle/YouCompleteMe/python/ycm/vimsupport.py new file mode 100644 index 0000000..c4a600c --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/vimsupport.py @@ -0,0 +1,978 @@ +# Copyright (C) 2011, 2012 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from future.utils import iterkeys +import vim +import os +import tempfile +import json +import re +from collections import defaultdict +from ycmd.utils import ToUnicode, ToBytes +from ycmd import user_options_store + +BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit', + 'horizontal-split' : 'split', + 'vertical-split' : 'vsplit', + 'new-tab' : 'tabedit' } + +FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = ( + 'The requested operation will apply changes to {0} files which are not ' + 'currently open. This will therefore open {0} new files in the hidden ' + 'buffers. The quickfix list can then be used to review the changes. No ' + 'files will be written to disk. Do you wish to continue?' ) + + +def CurrentLineAndColumn(): + """Returns the 0-based current line and 0-based current column.""" + # See the comment in CurrentColumn about the calculation for the line and + # column number + line, column = vim.current.window.cursor + line -= 1 + return line, column + + +def CurrentColumn(): + """Returns the 0-based current column. Do NOT access the CurrentColumn in + vim.current.line. It doesn't exist yet when the cursor is at the end of the + line. Only the chars before the current column exist in vim.current.line.""" + + # vim's columns are 1-based while vim.current.line columns are 0-based + # ... but vim.current.window.cursor (which returns a (line, column) tuple) + # columns are 0-based, while the line from that same tuple is 1-based. + # vim.buffers buffer objects OTOH have 0-based lines and columns. + # Pigs have wings and I'm a loopy purple duck. Everything makes sense now. + return vim.current.window.cursor[ 1 ] + + +def CurrentLineContents(): + return ToUnicode( vim.current.line ) + + +def TextAfterCursor(): + """Returns the text after CurrentColumn.""" + return ToUnicode( vim.current.line[ CurrentColumn(): ] ) + + +def TextBeforeCursor(): + """Returns the text before CurrentColumn.""" + return ToUnicode( vim.current.line[ :CurrentColumn() ] ) + + +# Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '7.4.301' +def VimVersionAtLeast( version_string ): + major, minor, patch = [ int( x ) for x in version_string.split( '.' ) ] + + # For Vim 7.4.301, v:version is '704' + actual_major_and_minor = GetIntValue( 'v:version' ) + matching_major_and_minor = major * 100 + minor + if actual_major_and_minor != matching_major_and_minor: + return actual_major_and_minor > matching_major_and_minor + + return GetBoolValue( 'has("patch{0}")'.format( patch ) ) + + +# Note the difference between buffer OPTIONS and VARIABLES; the two are not +# the same. +def GetBufferOption( buffer_object, option ): + # NOTE: We used to check for the 'options' property on the buffer_object which + # is available in recent versions of Vim and would then use: + # + # buffer_object.options[ option ] + # + # to read the value, BUT this caused annoying flickering when the + # buffer_object was a hidden buffer (with option = 'ft'). This was all due to + # a Vim bug. Until this is fixed, we won't use it. + + to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option ) + return GetVariableValue( to_eval ) + + +def BufferModified( buffer_object ): + return bool( int( GetBufferOption( buffer_object, 'mod' ) ) ) + + +def GetUnsavedAndCurrentBufferData(): + buffers_data = {} + for buffer_object in vim.buffers: + if not ( BufferModified( buffer_object ) or + buffer_object == vim.current.buffer ): + continue + + buffers_data[ GetBufferFilepath( buffer_object ) ] = { + # Add a newline to match what gets saved to disk. See #1455 for details. + 'contents': '\n'.join( ToUnicode( x ) for x in buffer_object ) + '\n', + 'filetypes': FiletypesForBuffer( buffer_object ) + } + + return buffers_data + + +def GetBufferNumberForFilename( filename, open_file_if_needed = True ): + return GetIntValue( u"bufnr('{0}', {1})".format( + EscapeForVim( os.path.realpath( filename ) ), + int( open_file_if_needed ) ) ) + + +def GetCurrentBufferFilepath(): + return GetBufferFilepath( vim.current.buffer ) + + +def BufferIsVisible( buffer_number ): + if buffer_number < 0: + return False + window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) ) + return window_number != -1 + + +def GetBufferFilepath( buffer_object ): + if buffer_object.name: + return buffer_object.name + # Buffers that have just been created by a command like :enew don't have any + # buffer name so we use the buffer number for that. Also, os.getcwd() throws + # an exception when the CWD has been deleted so we handle that. + try: + folder_path = os.getcwd() + except OSError: + folder_path = tempfile.gettempdir() + return os.path.join( folder_path, str( buffer_object.number ) ) + + +def UnplaceSignInBuffer( buffer_number, sign_id ): + if buffer_number < 0: + return + vim.command( + 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format( + sign_id, buffer_number ) ) + + +def PlaceSign( sign_id, line_num, buffer_num, is_error = True ): + # libclang can give us diagnostics that point "outside" the file; Vim borks + # on these. + if line_num < 1: + line_num = 1 + + sign_name = 'YcmError' if is_error else 'YcmWarning' + vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format( + sign_id, line_num, sign_name, buffer_num ) ) + + +def PlaceDummySign( sign_id, buffer_num, line_num ): + if buffer_num < 0 or line_num < 0: + return + vim.command( 'sign define ycm_dummy_sign' ) + vim.command( + 'sign place {0} name=ycm_dummy_sign line={1} buffer={2}'.format( + sign_id, + line_num, + buffer_num, + ) + ) + + +def UnPlaceDummySign( sign_id, buffer_num ): + if buffer_num < 0: + return + vim.command( 'sign undefine ycm_dummy_sign' ) + vim.command( 'sign unplace {0} buffer={1}'.format( sign_id, buffer_num ) ) + + +def ClearYcmSyntaxMatches(): + matches = VimExpressionToPythonType( 'getmatches()' ) + for match in matches: + if match[ 'group' ].startswith( 'Ycm' ): + vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) ) + + +# Returns the ID of the newly added match +# Both line and column numbers are 1-based +def AddDiagnosticSyntaxMatch( line_num, + column_num, + line_end_num = None, + column_end_num = None, + is_error = True ): + group = 'YcmErrorSection' if is_error else 'YcmWarningSection' + + if not line_end_num: + line_end_num = line_num + + line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num ) + line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num, + column_end_num ) + + if not column_end_num: + return GetIntValue( + "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) ) + else: + return GetIntValue( + "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format( + group, line_num, column_num, line_end_num, column_end_num ) ) + + +# Clamps the line and column numbers so that they are not past the contents of +# the buffer. Numbers are 1-based byte offsets. +def LineAndColumnNumbersClamped( line_num, column_num ): + new_line_num = line_num + new_column_num = column_num + + max_line = len( vim.current.buffer ) + if line_num and line_num > max_line: + new_line_num = max_line + + max_column = len( vim.current.buffer[ new_line_num - 1 ] ) + if column_num and column_num > max_column: + new_column_num = max_column + + return new_line_num, new_column_num + + +def SetLocationList( diagnostics ): + """Diagnostics should be in qflist format; see ":h setqflist" for details.""" + vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) ) + + +def SetQuickFixList( quickfix_list, focus = False, autoclose = False ): + """Populate the quickfix list and open it. List should be in qflist format: + see ":h setqflist" for details. When focus is set to True, the quickfix + window becomes the active window. When autoclose is set to True, the quickfix + window is automatically closed after an entry is selected.""" + vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) ) + OpenQuickFixList( focus, autoclose ) + + +def OpenQuickFixList( focus = False, autoclose = False ): + """Open the quickfix list to full width at the bottom of the screen with its + height automatically set to fit all entries. This behavior can be overridden + by using the YcmQuickFixOpened autocommand. + See the SetQuickFixList function for the focus and autoclose options.""" + vim.command( 'botright copen' ) + + SetFittingHeightForCurrentWindow() + + if autoclose: + # This autocommand is automatically removed when the quickfix window is + # closed. + vim.command( 'au WinLeave <buffer> q' ) + + if VariableExists( '#User#YcmQuickFixOpened' ): + vim.command( 'doautocmd User YcmQuickFixOpened' ) + + if not focus: + JumpToPreviousWindow() + + +def SetFittingHeightForCurrentWindow(): + window_width = GetIntValue( 'winwidth( 0 )' ) + fitting_height = 0 + for line in vim.current.buffer: + fitting_height += len( line ) // window_width + 1 + vim.command( '{0}wincmd _'.format( fitting_height ) ) + + +def ConvertDiagnosticsToQfList( diagnostics ): + def ConvertDiagnosticToQfFormat( diagnostic ): + # See :h getqflist for a description of the dictionary fields. + # Note that, as usual, Vim is completely inconsistent about whether + # line/column numbers are 1 or 0 based in its various APIs. Here, it wants + # them to be 1-based. The documentation states quite clearly that it + # expects a byte offset, by which it means "1-based column number" as + # described in :h getqflist ("the first column is 1"). + location = diagnostic[ 'location' ] + line_num = location[ 'line_num' ] + + # libclang can give us diagnostics that point "outside" the file; Vim borks + # on these. + if line_num < 1: + line_num = 1 + + text = diagnostic[ 'text' ] + if diagnostic.get( 'fixit_available', False ): + text += ' (FixIt available)' + + return { + 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ), + 'lnum' : line_num, + 'col' : location[ 'column_num' ], + 'text' : text, + 'type' : diagnostic[ 'kind' ][ 0 ], + 'valid' : 1 + } + + return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ] + + +def GetVimGlobalsKeys(): + return vim.eval( 'keys( g: )' ) + + +def VimExpressionToPythonType( vim_expression ): + """Returns a Python type from the return value of the supplied Vim expression. + If the expression returns a list, dict or other non-string type, then it is + returned unmodified. If the string return can be converted to an + integer, returns an integer, otherwise returns the result converted to a + Unicode string.""" + + result = vim.eval( vim_expression ) + if not ( isinstance( result, str ) or isinstance( result, bytes ) ): + return result + + try: + return int( result ) + except ValueError: + return ToUnicode( result ) + + +def HiddenEnabled( buffer_object ): + return bool( int( GetBufferOption( buffer_object, 'hid' ) ) ) + + +def BufferIsUsable( buffer_object ): + return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object ) + + +def EscapedFilepath( filepath ): + return filepath.replace( ' ' , r'\ ' ) + + +# Both |line| and |column| need to be 1-based +def TryJumpLocationInOpenedTab( filename, line, column ): + filepath = os.path.realpath( filename ) + + for tab in vim.tabpages: + for win in tab.windows: + if win.buffer.name == filepath: + vim.current.tabpage = tab + vim.current.window = win + vim.current.window.cursor = ( line, column - 1 ) + + # Center the screen on the jumped-to location + vim.command( 'normal! zz' ) + return True + # 'filename' is not opened in any tab pages + return False + + +# Maps User command to vim command +def GetVimCommand( user_command, default = 'edit' ): + vim_command = BUFFER_COMMAND_MAP.get( user_command, default ) + if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ): + vim_command = 'split' + return vim_command + + +# Both |line| and |column| need to be 1-based +def JumpToLocation( filename, line, column ): + # Add an entry to the jumplist + vim.command( "normal! m'" ) + + if filename != GetCurrentBufferFilepath(): + # We prefix the command with 'keepjumps' so that opening the file is not + # recorded in the jumplist. So when we open the file and move the cursor to + # a location in it, the user can use CTRL-O to jump back to the original + # location, not to the start of the newly opened file. + # Sadly this fails on random occasions and the undesired jump remains in the + # jumplist. + user_command = user_options_store.Value( 'goto_buffer_command' ) + + if user_command == 'new-or-existing-tab': + if TryJumpLocationInOpenedTab( filename, line, column ): + return + user_command = 'new-tab' + + vim_command = GetVimCommand( user_command ) + try: + vim.command( 'keepjumps {0} {1}'.format( vim_command, + EscapedFilepath( filename ) ) ) + # When the file we are trying to jump to has a swap file + # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, + # or KeyboardInterrupt after user selects one of the options. + except vim.error as e: + if 'E325' not in str( e ): + raise + # Do nothing if the target file is still not opened (user chose (Q)uit) + if filename != GetCurrentBufferFilepath(): + return + # Thrown when user chooses (A)bort in .swp message box + except KeyboardInterrupt: + return + vim.current.window.cursor = ( line, column - 1 ) + + # Center the screen on the jumped-to location + vim.command( 'normal! zz' ) + + +def NumLinesInBuffer( buffer_object ): + # This is actually less than obvious, that's why it's wrapped in a function + return len( buffer_object ) + + +# Calling this function from the non-GUI thread will sometimes crash Vim. At +# the time of writing, YCM only uses the GUI thread inside Vim (this used to +# not be the case). +# We redraw the screen before displaying the message to avoid the "Press ENTER +# or type command to continue" prompt when editing a new C-family file. +def PostVimMessage( message ): + vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None" + .format( EscapeForVim( ToUnicode( message ) ) ) ) + + +# Unlike PostVimMesasge, this supports messages with newlines in them because it +# uses 'echo' instead of 'echomsg'. This also means that the message will NOT +# appear in Vim's message log. +def PostMultiLineNotice( message ): + vim.command( "echohl WarningMsg | echo '{0}' | echohl None" + .format( EscapeForVim( ToUnicode( message ) ) ) ) + + +def PresentDialog( message, choices, default_choice_index = 0 ): + """Presents the user with a dialog where a choice can be made. + This will be a dialog for gvim users or a question in the message buffer + for vim users or if `set guioptions+=c` was used. + + choices is list of alternatives. + default_choice_index is the 0-based index of the default element + that will get choosen if the user hits <CR>. Use -1 for no default. + + PresentDialog will return a 0-based index into the list + or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc. + + See also: + :help confirm() in vim (Note that vim uses 1-based indexes) + + Example call: + PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"]) + Is this a nice example? + [Y]es, (N)o, May(b)e:""" + to_eval = "confirm('{0}', '{1}', {2})".format( + EscapeForVim( ToUnicode( message ) ), + EscapeForVim( ToUnicode( "\n" .join( choices ) ) ), + default_choice_index + 1 ) + return int( vim.eval( to_eval ) ) - 1 + + +def Confirm( message ): + """Display |message| with Ok/Cancel operations. Returns True if the user + selects Ok""" + return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 ) + + +def EchoText( text, log_as_message = True ): + def EchoLine( text ): + command = 'echom' if log_as_message else 'echo' + vim.command( "{0} '{1}'".format( command, + EscapeForVim( text ) ) ) + + for line in ToUnicode( text ).split( '\n' ): + EchoLine( line ) + + +# Echos text but truncates it so that it all fits on one line +def EchoTextVimWidth( text ): + vim_width = GetIntValue( '&columns' ) + truncated_text = ToUnicode( text )[ : int( vim_width * 0.9 ) ] + truncated_text.replace( '\n', ' ' ) + + old_ruler = GetIntValue( '&ruler' ) + old_showcmd = GetIntValue( '&showcmd' ) + vim.command( 'set noruler noshowcmd' ) + vim.command( 'redraw' ) + + EchoText( truncated_text, False ) + + SetVariableValue( '&ruler', old_ruler ) + SetVariableValue( '&showcmd', old_showcmd ) + + +def EscapeForVim( text ): + return ToUnicode( text.replace( "'", "''" ) ) + + +def CurrentFiletypes(): + return VimExpressionToPythonType( "&filetype" ).split( '.' ) + + +def FiletypesForBuffer( buffer_object ): + # NOTE: Getting &ft for other buffers only works when the buffer has been + # visited by the user at least once, which is true for modified buffers + return GetBufferOption( buffer_object, 'ft' ).split( '.' ) + + +def VariableExists( variable ): + return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) ) + + +def SetVariableValue( variable, value ): + vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) ) + + +def GetVariableValue( variable ): + return vim.eval( variable ) + + +def GetBoolValue( variable ): + return bool( int( vim.eval( variable ) ) ) + + +def GetIntValue( variable ): + return int( vim.eval( variable ) ) + + +def _SortChunksByFile( chunks ): + """Sort the members of the list |chunks| (which must be a list of dictionaries + conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new + list in arbitrary order.""" + + chunks_by_file = defaultdict( list ) + + for chunk in chunks: + filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ] + chunks_by_file[ filepath ].append( chunk ) + + return chunks_by_file + + +def _GetNumNonVisibleFiles( file_list ): + """Returns the number of file in the iterable list of files |file_list| which + are not curerntly open in visible windows""" + return len( + [ f for f in file_list + if not BufferIsVisible( GetBufferNumberForFilename( f, False ) ) ] ) + + +def _OpenFileInSplitIfNeeded( filepath ): + """Ensure that the supplied filepath is open in a visible window, opening a + new split if required. Returns the buffer number of the file and an indication + of whether or not a new split was opened. + + If the supplied filename is already open in a visible window, return just + return its buffer number. If the supplied file is not visible in a window + in the current tab, opens it in a new vertical split. + + Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer + number and whether or not this method created a new split. If the user opts + not to open a file, or if opening fails, this method raises RuntimeError, + otherwise, guarantees to return a visible buffer number in buffer_num.""" + + buffer_num = GetBufferNumberForFilename( filepath, False ) + + # We only apply changes in the current tab page (i.e. "visible" windows). + # Applying changes in tabs does not lead to a better user experience, as the + # quickfix list no longer works as you might expect (doesn't jump into other + # tabs), and the complexity of choosing where to apply edits is significant. + if BufferIsVisible( buffer_num ): + # file is already open and visible, just return that buffer number (and an + # idicator that we *didn't* open a split) + return ( buffer_num, False ) + + # The file is not open in a visible window, so we open it in a split. + # We open the file with a small, fixed height. This means that we don't + # make the current buffer the smallest after a series of splits. + OpenFilename( filepath, { + 'focus': True, + 'fix': True, + 'size': GetIntValue( '&previewheight' ), + } ) + + # OpenFilename returns us to the original cursor location. This is what we + # want, because we don't want to disorientate the user, but we do need to + # know the (now open) buffer number for the filename + buffer_num = GetBufferNumberForFilename( filepath, False ) + if not BufferIsVisible( buffer_num ): + # This happens, for example, if there is a swap file and the user + # selects the "Quit" or "Abort" options. We just raise an exception to + # make it clear to the user that the abort has left potentially + # partially-applied changes. + raise RuntimeError( + 'Unable to open file: {0}\nFixIt/Refactor operation ' + 'aborted prior to completion. Your files have not been ' + 'fully updated. Please use undo commands to revert the ' + 'applied changes.'.format( filepath ) ) + + # We opened this file in a split + return ( buffer_num, True ) + + +def ReplaceChunks( chunks ): + """Apply the source file deltas supplied in |chunks| to arbitrary files. + |chunks| is a list of changes defined by ycmd.responses.FixItChunk, + which may apply arbitrary modifications to arbitrary files. + + If a file specified in a particular chunk is not currently open in a visible + buffer (i.e., one in a window visible in the current tab), we: + - issue a warning to the user that we're going to open new files (and offer + her the option to abort cleanly) + - open the file in a new split, make the changes, then hide the buffer. + + If for some reason a file could not be opened or changed, raises RuntimeError. + Otherwise, returns no meaningful value.""" + + # We apply the edits file-wise for efficiency, and because we must track the + # file-wise offset deltas (caused by the modifications to the text). + chunks_by_file = _SortChunksByFile( chunks ) + + # We sort the file list simply to enable repeatable testing + sorted_file_list = sorted( iterkeys( chunks_by_file ) ) + + # Make sure the user is prepared to have her screen mutilated by the new + # buffers + num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list ) + + if num_files_to_open > 0: + if not Confirm( + FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ): + return + + # Store the list of locations where we applied changes. We use this to display + # the quickfix window showing the user where we applied changes. + locations = [] + + for filepath in sorted_file_list: + ( buffer_num, close_window ) = _OpenFileInSplitIfNeeded( filepath ) + + ReplaceChunksInBuffer( chunks_by_file[ filepath ], + vim.buffers[ buffer_num ], + locations ) + + # When opening tons of files, we don't want to have a split for each new + # file, as this simply does not scale, so we open the window, make the + # edits, then hide the window. + if close_window: + # Some plugins (I'm looking at you, syntastic) might open a location list + # for the window we just opened. We don't want that location list hanging + # around, so we close it. lclose is a no-op if there is no location list. + vim.command( 'lclose' ) + + # Note that this doesn't lose our changes. It simply "hides" the buffer, + # which can later be re-accessed via the quickfix list or `:ls` + vim.command( 'hide' ) + + # Open the quickfix list, populated with entries for each location we changed. + if locations: + SetQuickFixList( locations ) + + EchoTextVimWidth( "Applied " + str( len( chunks ) ) + " changes" ) + + +def ReplaceChunksInBuffer( chunks, vim_buffer, locations ): + """Apply changes in |chunks| to the buffer-like object |buffer|. Append each + chunk's start to the list |locations|""" + + # We need to track the difference in length, but ensuring we apply fixes + # in ascending order of insertion point. + chunks.sort( key = lambda chunk: ( + chunk[ 'range' ][ 'start' ][ 'line_num' ], + chunk[ 'range' ][ 'start' ][ 'column_num' ] + ) ) + + # Remember the line number we're processing. Negative line number means we + # haven't processed any lines yet (by nature of being not equal to any + # real line number). + last_line = -1 + + line_delta = 0 + for chunk in chunks: + if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line: + # If this chunk is on a different line than the previous chunk, + # then ignore previous deltas (as offsets won't have changed). + last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ] + char_delta = 0 + + ( new_line_delta, new_char_delta ) = ReplaceChunk( + chunk[ 'range' ][ 'start' ], + chunk[ 'range' ][ 'end' ], + chunk[ 'replacement_text' ], + line_delta, char_delta, + vim_buffer, + locations ) + line_delta += new_line_delta + char_delta += new_char_delta + + +# Replace the chunk of text specified by a contiguous range with the supplied +# text. +# * start and end are objects with line_num and column_num properties +# * the range is inclusive +# * indices are all 1-based +# * the returned character delta is the delta for the last line +# +# returns the delta (in lines and characters) that any position after the end +# needs to be adjusted by. +# +# NOTE: Works exclusively with bytes() instances and byte offsets as returned +# by ycmd and used within the Vim buffers +def ReplaceChunk( start, end, replacement_text, line_delta, char_delta, + vim_buffer, locations = None ): + # ycmd's results are all 1-based, but vim's/python's are all 0-based + # (so we do -1 on all of the values) + start_line = start[ 'line_num' ] - 1 + line_delta + end_line = end[ 'line_num' ] - 1 + line_delta + + source_lines_count = end_line - start_line + 1 + start_column = start[ 'column_num' ] - 1 + char_delta + end_column = end[ 'column_num' ] - 1 + if source_lines_count == 1: + end_column += char_delta + + # NOTE: replacement_text is unicode, but all our offsets are byte offsets, + # so we convert to bytes + replacement_lines = ToBytes( replacement_text ).splitlines( False ) + if not replacement_lines: + replacement_lines = [ bytes( b'' ) ] + replacement_lines_count = len( replacement_lines ) + + end_existing_text = vim_buffer[ end_line ][ end_column : ] + start_existing_text = vim_buffer[ start_line ][ : start_column ] + + new_char_delta = ( len( replacement_lines[ -1 ] ) + - ( end_column - start_column ) ) + if replacement_lines_count > 1: + new_char_delta -= start_column + + replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ] + replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text + + vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:] + + if locations is not None: + locations.append( { + 'bufnr': vim_buffer.number, + 'filename': vim_buffer.name, + # line and column numbers are 1-based in qflist + 'lnum': start_line + 1, + 'col': start_column + 1, + 'text': replacement_text, + 'type': 'F', + } ) + + new_line_delta = replacement_lines_count - source_lines_count + return ( new_line_delta, new_char_delta ) + + +def InsertNamespace( namespace ): + if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ): + expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' ) + if expr: + SetVariableValue( "g:ycm_namespace_to_insert", namespace ) + vim.eval( expr ) + return + + pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*' + line = SearchInCurrentBuffer( pattern ) + existing_line = LineTextInCurrentBuffer( line ) + existing_indent = re.sub( r"\S.*", "", existing_line ) + new_line = "{0}using {1};\n\n".format( existing_indent, namespace ) + replace_pos = { 'line_num': line + 1, 'column_num': 1 } + ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0 ) + PostVimMessage( "Add namespace: {0}".format( namespace ) ) + + +def SearchInCurrentBuffer( pattern ): + return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern ))) + + +def LineTextInCurrentBuffer( line ): + return vim.current.buffer[ line ] + + +def ClosePreviewWindow(): + """ Close the preview window if it is present, otherwise do nothing """ + vim.command( 'silent! pclose!' ) + + +def JumpToPreviewWindow(): + """ Jump the vim cursor to the preview window, which must be active. Returns + boolean indicating if the cursor ended up in the preview window """ + vim.command( 'silent! wincmd P' ) + return vim.current.window.options[ 'previewwindow' ] + + +def JumpToPreviousWindow(): + """ Jump the vim cursor to its previous window position """ + vim.command( 'silent! wincmd p' ) + + +def JumpToTab( tab_number ): + """Jump to Vim tab with corresponding number """ + vim.command( 'silent! tabn {0}'.format( tab_number ) ) + + +def OpenFileInPreviewWindow( filename ): + """ Open the supplied filename in the preview window """ + vim.command( 'silent! pedit! ' + filename ) + + +def WriteToPreviewWindow( message ): + """ Display the supplied message in the preview window """ + + # This isn't something that comes naturally to Vim. Vim only wants to show + # tags and/or actual files in the preview window, so we have to hack it a + # little bit. We generate a temporary file name and "open" that, then write + # the data to it. We make sure the buffer can't be edited or saved. Other + # approaches include simply opening a split, but we want to take advantage of + # the existing Vim options for preview window height, etc. + + ClosePreviewWindow() + + OpenFileInPreviewWindow( vim.eval( 'tempname()' ) ) + + if JumpToPreviewWindow(): + # We actually got to the preview window. By default the preview window can't + # be changed, so we make it writable, write to it, then make it read only + # again. + vim.current.buffer.options[ 'modifiable' ] = True + vim.current.buffer.options[ 'readonly' ] = False + + vim.current.buffer[:] = message.splitlines() + + vim.current.buffer.options[ 'buftype' ] = 'nofile' + vim.current.buffer.options[ 'swapfile' ] = False + vim.current.buffer.options[ 'modifiable' ] = False + vim.current.buffer.options[ 'readonly' ] = True + + # We need to prevent closing the window causing a warning about unsaved + # file, so we pretend to Vim that the buffer has not been changed. + vim.current.buffer.options[ 'modified' ] = False + + JumpToPreviousWindow() + else: + # We couldn't get to the preview window, but we still want to give the user + # the information we have. The only remaining option is to echo to the + # status area. + EchoText( message ) + + +def CheckFilename( filename ): + """Check if filename is openable.""" + try: + # We don't want to check for encoding issues when trying to open the file + # so we open it in binary mode. + open( filename, mode = 'rb' ).close() + except TypeError: + raise RuntimeError( "'{0}' is not a valid filename".format( filename ) ) + except IOError as error: + raise RuntimeError( + "filename '{0}' cannot be opened. {1}.".format( filename, + error.strerror ) ) + + +def BufferIsVisibleForFilename( filename ): + """Check if a buffer exists for a specific file.""" + buffer_number = GetBufferNumberForFilename( filename, False ) + return BufferIsVisible( buffer_number ) + + +def CloseBuffersForFilename( filename ): + """Close all buffers for a specific file.""" + buffer_number = GetBufferNumberForFilename( filename, False ) + while buffer_number != -1: + vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) ) + new_buffer_number = GetBufferNumberForFilename( filename, False ) + if buffer_number == new_buffer_number: + raise RuntimeError( "Buffer {0} for filename '{1}' should already be " + "wiped out.".format( buffer_number, filename ) ) + buffer_number = new_buffer_number + + +def OpenFilename( filename, options = {} ): + """Open a file in Vim. Following options are available: + - command: specify which Vim command is used to open the file. Choices + are same-buffer, horizontal-split, vertical-split, and new-tab (default: + horizontal-split); + - size: set the height of the window for a horizontal split or the width for + a vertical one (default: ''); + - fix: set the winfixheight option for a horizontal split or winfixwidth for + a vertical one (default: False). See :h winfix for details; + - focus: focus the opened file (default: False); + - watch: automatically watch for changes (default: False). This is useful + for logs; + - position: set the position where the file is opened (default: start). + Choices are start and end.""" + + # Set the options. + command = GetVimCommand( options.get( 'command', 'horizontal-split' ), + 'horizontal-split' ) + size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else + '' ) + focus = options.get( 'focus', False ) + + # There is no command in Vim to return to the previous tab so we need to + # remember the current tab if needed. + if not focus and command == 'tabedit': + previous_tab = GetIntValue( 'tabpagenr()' ) + else: + previous_tab = None + + # Open the file + CheckFilename( filename ) + try: + vim.command( '{0}{1} {2}'.format( size, command, filename ) ) + # When the file we are trying to jump to has a swap file, + # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, + # or KeyboardInterrupt after user selects one of the options which actually + # opens the file (Open read-only/Edit anyway). + except vim.error as e: + if 'E325' not in str( e ): + raise + + # Otherwise, the user might have chosen Quit. This is detectable by the + # current file not being the target file + if filename != GetCurrentBufferFilepath(): + return + except KeyboardInterrupt: + # Raised when the user selects "Abort" after swap-exists-choices + return + + _SetUpLoadedBuffer( command, + filename, + options.get( 'fix', False ), + options.get( 'position', 'start' ), + options.get( 'watch', False ) ) + + # Vim automatically set the focus to the opened file so we need to get the + # focus back (if the focus option is disabled) when opening a new tab or + # window. + if not focus: + if command == 'tabedit': + JumpToTab( previous_tab ) + if command in [ 'split', 'vsplit' ]: + JumpToPreviousWindow() + + +def _SetUpLoadedBuffer( command, filename, fix, position, watch ): + """After opening a buffer, configure it according to the supplied options, + which are as defined by the OpenFilename method.""" + + if command == 'split': + vim.current.window.options[ 'winfixheight' ] = fix + if command == 'vsplit': + vim.current.window.options[ 'winfixwidth' ] = fix + + if watch: + vim.current.buffer.options[ 'autoread' ] = True + vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'" + .format( filename ) ) + + if position == 'end': + vim.command( 'silent! normal G zz' ) diff --git a/vim/bundle/YouCompleteMe/python/ycm/youcompleteme.py b/vim/bundle/YouCompleteMe/python/ycm/youcompleteme.py new file mode 100644 index 0000000..fa4bcf1 --- /dev/null +++ b/vim/bundle/YouCompleteMe/python/ycm/youcompleteme.py @@ -0,0 +1,711 @@ +# Copyright (C) 2011, 2012 Google Inc. +# +# This file is part of YouCompleteMe. +# +# YouCompleteMe 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. +# +# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. + +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import * # noqa + +from future.utils import iteritems +import os +import vim +import json +import re +import signal +import base64 +from subprocess import PIPE +from tempfile import NamedTemporaryFile +from ycm import paths, vimsupport +from ycmd import utils +from ycmd import server_utils +from ycmd.request_wrap import RequestWrap +from ycmd.responses import ServerError +from ycm.diagnostic_interface import DiagnosticInterface +from ycm.omni_completer import OmniCompleter +from ycm import syntax_parse +from ycm.client.ycmd_keepalive import YcmdKeepalive +from ycm.client.base_request import BaseRequest, BuildRequestData +from ycm.client.completer_available_request import SendCompleterAvailableRequest +from ycm.client.command_request import SendCommandRequest +from ycm.client.completion_request import ( CompletionRequest, + ConvertCompletionDataToVimData ) +from ycm.client.omni_completion_request import OmniCompletionRequest +from ycm.client.event_notification import ( SendEventNotificationAsync, + EventNotification ) + +try: + from UltiSnips import UltiSnips_Manager + USE_ULTISNIPS_DATA = True +except ImportError: + USE_ULTISNIPS_DATA = False + + +def PatchNoProxy(): + current_value = os.environ.get('no_proxy', '') + additions = '127.0.0.1,localhost' + os.environ['no_proxy'] = ( additions if not current_value + else current_value + ',' + additions ) + +# We need this so that Requests doesn't end up using the local HTTP proxy when +# talking to ycmd. Users should actually be setting this themselves when +# configuring a proxy server on their machine, but most don't know they need to +# or how to do it, so we do it for them. +# Relevant issues: +# https://github.com/Valloric/YouCompleteMe/issues/641 +# https://github.com/kennethreitz/requests/issues/879 +PatchNoProxy() + +# Force the Python interpreter embedded in Vim (in which we are running) to +# ignore the SIGINT signal. This helps reduce the fallout of a user pressing +# Ctrl-C in Vim. +signal.signal( signal.SIGINT, signal.SIG_IGN ) + +HMAC_SECRET_LENGTH = 16 +SERVER_SHUTDOWN_MESSAGE = ( + "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." ) +STDERR_FILE_MESSAGE = ( + "Run ':YcmToggleLogs stderr' to check the logs." ) +STDERR_FILE_DELETED_MESSAGE = ( + "Logfile was deleted; set 'g:ycm_server_keep_logfiles' to see errors " + "in the future." ) +CORE_UNEXPECTED_MESSAGE = ( + 'Unexpected error while loading the YCM core library.' ) +CORE_MISSING_MESSAGE = ( + 'YCM core library not detected; you need to compile YCM before using it. ' + 'Follow the instructions in the documentation.' ) +CORE_PYTHON2_MESSAGE = ( + "YCM core library compiled for Python 2 but loaded in Python 3. " + "Set the 'g:ycm_server_python_interpreter' option to a Python 2 " + "interpreter path." ) +CORE_PYTHON3_MESSAGE = ( + "YCM core library compiled for Python 3 but loaded in Python 2. " + "Set the 'g:ycm_server_python_interpreter' option to a Python 3 " + "interpreter path." ) +CORE_OUTDATED_MESSAGE = ( + 'YCM core library too old; PLEASE RECOMPILE by running the install.py ' + 'script. See the documentation for more details.' ) +SERVER_IDLE_SUICIDE_SECONDS = 10800 # 3 hours +DIAGNOSTIC_UI_FILETYPES = set( [ 'cpp', 'cs', 'c', 'objc', 'objcpp' ] ) + + +class YouCompleteMe( object ): + def __init__( self, user_options ): + self._user_options = user_options + self._user_notified_about_crash = False + self._diag_interface = DiagnosticInterface( user_options ) + self._omnicomp = OmniCompleter( user_options ) + self._latest_file_parse_request = None + self._latest_completion_request = None + self._latest_diagnostics = [] + self._server_stdout = None + self._server_stderr = None + self._server_popen = None + self._filetypes_with_keywords_loaded = set() + self._ycmd_keepalive = YcmdKeepalive() + self._SetupServer() + self._ycmd_keepalive.Start() + self._complete_done_hooks = { + 'cs': lambda self: self._OnCompleteDone_Csharp() + } + + def _SetupServer( self ): + self._available_completers = {} + server_port = utils.GetUnusedLocalhostPort() + # The temp options file is deleted by ycmd during startup + with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file: + hmac_secret = os.urandom( HMAC_SECRET_LENGTH ) + options_dict = dict( self._user_options ) + options_dict[ 'hmac_secret' ] = utils.ToUnicode( + base64.b64encode( hmac_secret ) ) + json.dump( options_dict, options_file ) + options_file.flush() + + args = [ paths.PathToPythonInterpreter(), + paths.PathToServerScript(), + '--port={0}'.format( server_port ), + '--options_file={0}'.format( options_file.name ), + '--log={0}'.format( self._user_options[ 'server_log_level' ] ), + '--idle_suicide_seconds={0}'.format( + SERVER_IDLE_SUICIDE_SECONDS )] + + filename_format = os.path.join( utils.PathToCreatedTempDir(), + 'server_{port}_{std}.log' ) + + self._server_stdout = filename_format.format( port = server_port, + std = 'stdout' ) + self._server_stderr = filename_format.format( port = server_port, + std = 'stderr' ) + args.append( '--stdout={0}'.format( self._server_stdout ) ) + args.append( '--stderr={0}'.format( self._server_stderr ) ) + + if self._user_options[ 'server_keep_logfiles' ]: + args.append( '--keep_logfiles' ) + + self._server_popen = utils.SafePopen( args, stdin_windows = PIPE, + stdout = PIPE, stderr = PIPE ) + BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port ) + BaseRequest.hmac_secret = hmac_secret + + self._NotifyUserIfServerCrashed() + + + def IsServerAlive( self ): + returncode = self._server_popen.poll() + # When the process hasn't finished yet, poll() returns None. + return returncode is None + + + def _NotifyUserIfServerCrashed( self ): + if self._user_notified_about_crash or self.IsServerAlive(): + return + self._user_notified_about_crash = True + + try: + vimsupport.CheckFilename( self._server_stderr ) + stderr_message = STDERR_FILE_MESSAGE + except RuntimeError: + stderr_message = STDERR_FILE_DELETED_MESSAGE + + message = SERVER_SHUTDOWN_MESSAGE + return_code = self._server_popen.poll() + if return_code == server_utils.CORE_UNEXPECTED_STATUS: + message += ' ' + CORE_UNEXPECTED_MESSAGE + ' ' + stderr_message + elif return_code == server_utils.CORE_MISSING_STATUS: + message += ' ' + CORE_MISSING_MESSAGE + elif return_code == server_utils.CORE_PYTHON2_STATUS: + message += ' ' + CORE_PYTHON2_MESSAGE + elif return_code == server_utils.CORE_PYTHON3_STATUS: + message += ' ' + CORE_PYTHON3_MESSAGE + elif return_code == server_utils.CORE_OUTDATED_STATUS: + message += ' ' + CORE_OUTDATED_MESSAGE + else: + message += ' ' + stderr_message + vimsupport.PostVimMessage( message ) + + + def ServerPid( self ): + if not self._server_popen: + return -1 + return self._server_popen.pid + + + def _ServerCleanup( self ): + if self.IsServerAlive(): + self._server_popen.terminate() + + + def RestartServer( self ): + self._CloseLogs() + vimsupport.PostVimMessage( 'Restarting ycmd server...' ) + self._user_notified_about_crash = False + self._ServerCleanup() + self._SetupServer() + + + def CreateCompletionRequest( self, force_semantic = False ): + request_data = BuildRequestData() + if ( not self.NativeFiletypeCompletionAvailable() and + self.CurrentFiletypeCompletionEnabled() ): + wrapped_request_data = RequestWrap( request_data ) + if self._omnicomp.ShouldUseNow( wrapped_request_data ): + self._latest_completion_request = OmniCompletionRequest( + self._omnicomp, wrapped_request_data ) + return self._latest_completion_request + + request_data[ 'working_dir' ] = os.getcwd() + + self._AddExtraConfDataIfNeeded( request_data ) + if force_semantic: + request_data[ 'force_semantic' ] = True + self._latest_completion_request = CompletionRequest( request_data ) + return self._latest_completion_request + + + def SendCommandRequest( self, arguments, completer ): + if self.IsServerAlive(): + return SendCommandRequest( arguments, completer ) + + + def GetDefinedSubcommands( self ): + if self.IsServerAlive(): + try: + return BaseRequest.PostDataToHandler( BuildRequestData(), + 'defined_subcommands' ) + except ServerError: + return [] + else: + return [] + + + def GetCurrentCompletionRequest( self ): + return self._latest_completion_request + + + def GetOmniCompleter( self ): + return self._omnicomp + + + def FiletypeCompleterExistsForFiletype( self, filetype ): + try: + return self._available_completers[ filetype ] + except KeyError: + pass + + if not self.IsServerAlive(): + return False + + exists_completer = SendCompleterAvailableRequest( filetype ) + if exists_completer is None: + return False + + self._available_completers[ filetype ] = exists_completer + return exists_completer + + + def NativeFiletypeCompletionAvailable( self ): + return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in + vimsupport.CurrentFiletypes() ] ) + + + def NativeFiletypeCompletionUsable( self ): + return ( self.CurrentFiletypeCompletionEnabled() and + self.NativeFiletypeCompletionAvailable() ) + + + def OnFileReadyToParse( self ): + if not self.IsServerAlive(): + self._NotifyUserIfServerCrashed() + return + + self._omnicomp.OnFileReadyToParse( None ) + + extra_data = {} + self._AddTagsFilesIfNeeded( extra_data ) + self._AddSyntaxDataIfNeeded( extra_data ) + self._AddExtraConfDataIfNeeded( extra_data ) + + self._latest_file_parse_request = EventNotification( 'FileReadyToParse', + extra_data ) + self._latest_file_parse_request.Start() + + + def OnBufferUnload( self, deleted_buffer_file ): + if not self.IsServerAlive(): + return + SendEventNotificationAsync( 'BufferUnload', + { 'unloaded_buffer': deleted_buffer_file } ) + + + def OnBufferVisit( self ): + if not self.IsServerAlive(): + return + extra_data = {} + _AddUltiSnipsDataIfNeeded( extra_data ) + SendEventNotificationAsync( 'BufferVisit', extra_data ) + + + def OnInsertLeave( self ): + if not self.IsServerAlive(): + return + SendEventNotificationAsync( 'InsertLeave' ) + + + def OnCursorMoved( self ): + self._diag_interface.OnCursorMoved() + + + def OnVimLeave( self ): + self._ServerCleanup() + + + def OnCurrentIdentifierFinished( self ): + if not self.IsServerAlive(): + return + SendEventNotificationAsync( 'CurrentIdentifierFinished' ) + + + def OnCompleteDone( self ): + complete_done_actions = self.GetCompleteDoneHooks() + for action in complete_done_actions: + action(self) + + + def GetCompleteDoneHooks( self ): + filetypes = vimsupport.CurrentFiletypes() + for key, value in iteritems( self._complete_done_hooks ): + if key in filetypes: + yield value + + + def GetCompletionsUserMayHaveCompleted( self ): + latest_completion_request = self.GetCurrentCompletionRequest() + if not latest_completion_request or not latest_completion_request.Done(): + return [] + + completions = latest_completion_request.RawResponse() + + result = self._FilterToMatchingCompletions( completions, True ) + result = list( result ) + if result: + return result + + if self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ): + # Since the way that YCM works leads to CompleteDone called on every + # character, return blank if the completion might not be done. This won't + # match if the completion is ended with typing a non-keyword character. + return [] + + result = self._FilterToMatchingCompletions( completions, False ) + + return list( result ) + + + def _FilterToMatchingCompletions( self, completions, full_match_only ): + self._PatchBasedOnVimVersion() + return self._FilterToMatchingCompletions( completions, full_match_only) + + + def _HasCompletionsThatCouldBeCompletedWithMoreText( self, completions ): + self._PatchBasedOnVimVersion() + return self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ) + + + def _PatchBasedOnVimVersion( self ): + if vimsupport.VimVersionAtLeast( "7.4.774" ): + self._HasCompletionsThatCouldBeCompletedWithMoreText = \ + self._HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim + self._FilterToMatchingCompletions = \ + self._FilterToMatchingCompletions_NewerVim + else: + self._FilterToMatchingCompletions = \ + self._FilterToMatchingCompletions_OlderVim + self._HasCompletionsThatCouldBeCompletedWithMoreText = \ + self._HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim + + + def _FilterToMatchingCompletions_NewerVim( self, + completions, + full_match_only ): + """Filter to completions matching the item Vim said was completed""" + completed = vimsupport.GetVariableValue( 'v:completed_item' ) + for completion in completions: + item = ConvertCompletionDataToVimData( completion ) + match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only + else [ 'word' ] ) + + def matcher( key ): + return ( utils.ToUnicode( completed.get( key, "" ) ) == + utils.ToUnicode( item.get( key, "" ) ) ) + + if all( [ matcher( i ) for i in match_keys ] ): + yield completion + + + def _FilterToMatchingCompletions_OlderVim( self, completions, + full_match_only ): + """ Filter to completions matching the buffer text """ + if full_match_only: + return # Only supported in 7.4.774+ + # No support for multiple line completions + text = vimsupport.TextBeforeCursor() + for completion in completions: + word = completion[ "insertion_text" ] + # Trim complete-ending character if needed + text = re.sub( r"[^a-zA-Z0-9_]$", "", text ) + buffer_text = text[ -1 * len( word ) : ] + if buffer_text == word: + yield completion + + + def _HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim( self, + completions ): + completed_item = vimsupport.GetVariableValue( 'v:completed_item' ) + if not completed_item: + return False + + completed_word = utils.ToUnicode( completed_item[ 'word' ] ) + if not completed_word: + return False + + # Sometimes CompleteDone is called after the next character is inserted. + # If so, use inserted character to filter possible completions further. + text = vimsupport.TextBeforeCursor() + reject_exact_match = True + if text and text[ -1 ] != completed_word[ -1 ]: + reject_exact_match = False + completed_word += text[ -1 ] + + for completion in completions: + word = utils.ToUnicode( + ConvertCompletionDataToVimData( completion )[ 'word' ] ) + if reject_exact_match and word == completed_word: + continue + if word.startswith( completed_word ): + return True + return False + + + def _HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim( self, + completions ): + # No support for multiple line completions + text = vimsupport.TextBeforeCursor() + for completion in completions: + word = utils.ToUnicode( + ConvertCompletionDataToVimData( completion )[ 'word' ] ) + for i in range( 1, len( word ) - 1 ): # Excluding full word + if text[ -1 * i : ] == word[ : i ]: + return True + return False + + + def _OnCompleteDone_Csharp( self ): + completions = self.GetCompletionsUserMayHaveCompleted() + namespaces = [ self._GetRequiredNamespaceImport( c ) + for c in completions ] + namespaces = [ n for n in namespaces if n ] + if not namespaces: + return + + if len( namespaces ) > 1: + choices = [ "{0} {1}".format( i + 1, n ) + for i, n in enumerate( namespaces ) ] + choice = vimsupport.PresentDialog( "Insert which namespace:", choices ) + if choice < 0: + return + namespace = namespaces[ choice ] + else: + namespace = namespaces[ 0 ] + + vimsupport.InsertNamespace( namespace ) + + + def _GetRequiredNamespaceImport( self, completion ): + if ( "extra_data" not in completion + or "required_namespace_import" not in completion[ "extra_data" ] ): + return None + return completion[ "extra_data" ][ "required_namespace_import" ] + + + def GetErrorCount( self ): + return self._diag_interface.GetErrorCount() + + + def GetWarningCount( self ): + return self._diag_interface.GetWarningCount() + + + def DiagnosticUiSupportedForCurrentFiletype( self ): + return any( [ x in DIAGNOSTIC_UI_FILETYPES + for x in vimsupport.CurrentFiletypes() ] ) + + + def ShouldDisplayDiagnostics( self ): + return bool( self._user_options[ 'show_diagnostics_ui' ] and + self.DiagnosticUiSupportedForCurrentFiletype() ) + + + def PopulateLocationListWithLatestDiagnostics( self ): + # Do nothing if loc list is already populated by diag_interface + if not self._user_options[ 'always_populate_location_list' ]: + self._diag_interface.PopulateLocationList( self._latest_diagnostics ) + return bool( self._latest_diagnostics ) + + + def UpdateDiagnosticInterface( self ): + self._diag_interface.UpdateWithNewDiagnostics( self._latest_diagnostics ) + + + def FileParseRequestReady( self, block = False ): + return bool( self._latest_file_parse_request and + ( block or self._latest_file_parse_request.Done() ) ) + + + def HandleFileParseRequest( self, block = False ): + # Order is important here: + # FileParseRequestReady has a low cost, while + # NativeFiletypeCompletionUsable is a blocking server request + if ( self.FileParseRequestReady( block ) and + self.NativeFiletypeCompletionUsable() ): + + if self.ShouldDisplayDiagnostics(): + self._latest_diagnostics = self._latest_file_parse_request.Response() + self.UpdateDiagnosticInterface() + else: + # YCM client has a hard-coded list of filetypes which are known + # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype() + # + # For filetypes which don't support diagnostics, we just want to check + # the _latest_file_parse_request for any exception or UnknownExtraConf + # response, to allow the server to raise configuration warnings, etc. + # to the user. We ignore any other supplied data. + self._latest_file_parse_request.Response() + + # We set the file parse request to None because we want to prevent + # repeated issuing of the same warnings/errors/prompts. Setting this to + # None makes FileParseRequestReady return False until the next + # request is created. + # + # Note: it is the server's responsibility to determine the frequency of + # error/warning/prompts when receiving a FileReadyToParse event, but + # it our responsibility to ensure that we only apply the + # warning/error/prompt received once (for each event). + self._latest_file_parse_request = None + + + def ShowDetailedDiagnostic( self ): + if not self.IsServerAlive(): + return + try: + debug_info = BaseRequest.PostDataToHandler( BuildRequestData(), + 'detailed_diagnostic' ) + if 'message' in debug_info: + vimsupport.EchoText( debug_info[ 'message' ] ) + except ServerError as e: + vimsupport.PostVimMessage( str( e ) ) + + + def DebugInfo( self ): + if self.IsServerAlive(): + debug_info = BaseRequest.PostDataToHandler( BuildRequestData(), + 'debug_info' ) + else: + debug_info = 'Server crashed, no debug info from server' + debug_info += '\nServer running at: {0}'.format( + BaseRequest.server_location ) + debug_info += '\nServer process ID: {0}'.format( self._server_popen.pid ) + if self._server_stderr or self._server_stdout: + debug_info += '\nServer logfiles:\n {0}\n {1}'.format( + self._server_stdout, + self._server_stderr ) + + return debug_info + + + def _OpenLogs( self, stdout = True, stderr = True ): + # Open log files in a horizontal window with the same behavior as the + # preview window (same height and winfixheight enabled). Automatically + # watch for changes. Set the cursor position at the end of the file. + options = { + 'size': vimsupport.GetIntValue( '&previewheight' ), + 'fix': True, + 'watch': True, + 'position': 'end' + } + + if stdout: + vimsupport.OpenFilename( self._server_stdout, options ) + if stderr: + vimsupport.OpenFilename( self._server_stderr, options ) + + + def _CloseLogs( self, stdout = True, stderr = True ): + if stdout: + vimsupport.CloseBuffersForFilename( self._server_stdout ) + if stderr: + vimsupport.CloseBuffersForFilename( self._server_stderr ) + + + def ToggleLogs( self, stdout = True, stderr = True ): + if ( stdout and + vimsupport.BufferIsVisibleForFilename( self._server_stdout ) or + stderr and + vimsupport.BufferIsVisibleForFilename( self._server_stderr ) ): + return self._CloseLogs( stdout = stdout, stderr = stderr ) + + # Close hidden logfile buffers if any to keep a clean state + self._CloseLogs( stdout = stdout, stderr = stderr ) + + try: + self._OpenLogs( stdout = stdout, stderr = stderr ) + except RuntimeError as error: + vimsupport.PostVimMessage( 'YouCompleteMe encountered an error when ' + 'opening logs: {0}.'.format( error ) ) + + + def CurrentFiletypeCompletionEnabled( self ): + filetypes = vimsupport.CurrentFiletypes() + filetype_to_disable = self._user_options[ + 'filetype_specific_completion_to_disable' ] + if '*' in filetype_to_disable: + return False + else: + return not any([ x in filetype_to_disable for x in filetypes ]) + + + def _AddSyntaxDataIfNeeded( self, extra_data ): + if not self._user_options[ 'seed_identifiers_with_syntax' ]: + return + filetype = vimsupport.CurrentFiletypes()[ 0 ] + if filetype in self._filetypes_with_keywords_loaded: + return + + self._filetypes_with_keywords_loaded.add( filetype ) + extra_data[ 'syntax_keywords' ] = list( + syntax_parse.SyntaxKeywordsForCurrentBuffer() ) + + + def _AddTagsFilesIfNeeded( self, extra_data ): + def GetTagFiles(): + tag_files = vim.eval( 'tagfiles()' ) + # getcwd() throws an exception when the CWD has been deleted. + try: + current_working_directory = os.getcwd() + except OSError: + return [] + return [ os.path.join( current_working_directory, x ) for x in tag_files ] + + if not self._user_options[ 'collect_identifiers_from_tags_files' ]: + return + extra_data[ 'tag_files' ] = GetTagFiles() + + + def _AddExtraConfDataIfNeeded( self, extra_data ): + def BuildExtraConfData( extra_conf_vim_data ): + return dict( ( expr, vimsupport.VimExpressionToPythonType( expr ) ) + for expr in extra_conf_vim_data ) + + extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ] + if extra_conf_vim_data: + extra_data[ 'extra_conf_data' ] = BuildExtraConfData( + extra_conf_vim_data ) + + +def _AddUltiSnipsDataIfNeeded( extra_data ): + if not USE_ULTISNIPS_DATA: + return + + try: + # Since UltiSnips may run in a different python interpreter (python 3) than + # YCM, UltiSnips_Manager singleton is not necessary the same as the one + # used by YCM. In particular, it means that we cannot rely on UltiSnips to + # set the current filetypes to the singleton. We need to do it ourself. + UltiSnips_Manager.reset_buffer_filetypes() + UltiSnips_Manager.add_buffer_filetypes( + vimsupport.GetVariableValue( '&filetype' ) ) + rawsnips = UltiSnips_Manager._snips( '', True ) + except: + return + + # UltiSnips_Manager._snips() returns a class instance where: + # class.trigger - name of snippet trigger word ( e.g. defn or testcase ) + # class.description - description of the snippet + extra_data[ 'ultisnips_snippets' ] = [ + { 'trigger': x.trigger, 'description': x.description } for x in rawsnips + ] diff --git a/vim/bundle/YouCompleteMe/run_tests.py b/vim/bundle/YouCompleteMe/run_tests.py new file mode 100755 index 0000000..c837b9f --- /dev/null +++ b/vim/bundle/YouCompleteMe/run_tests.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +import os +import subprocess +import os.path as p +import sys + +DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) +DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) +DIR_OF_YCMD_THIRD_PARTY = p.join( DIR_OF_THIRD_PARTY, 'ycmd', 'third_party' ) + +python_path = [] +for folder in os.listdir( DIR_OF_THIRD_PARTY ): + python_path.append( p.abspath( p.join( DIR_OF_THIRD_PARTY, folder ) ) ) +for folder in os.listdir( DIR_OF_YCMD_THIRD_PARTY ): + # We skip python-future because it needs to be inserted in sys.path AFTER + # the standard library imports but we can't do that with PYTHONPATH because + # the std lib paths are always appended to PYTHONPATH. We do it correctly in + # prod in ycmd/utils.py because we have access to the right sys.path. + # So for dev, we rely on python-future being installed correctly with + # pip install -r test_requirements.txt + # + # Pip knows how to install this correctly so that it doesn't matter where in + # sys.path the path is. + if folder == 'python-future': + continue + python_path.append( p.abspath( p.join( DIR_OF_YCMD_THIRD_PARTY, folder ) ) ) +if os.environ.get( 'PYTHONPATH' ): + python_path.append( os.environ[ 'PYTHONPATH' ] ) +os.environ[ 'PYTHONPATH' ] = os.pathsep.join( python_path ) + +sys.path.insert( 1, p.abspath( p.join( DIR_OF_YCMD_THIRD_PARTY, + 'argparse' ) ) ) + +import argparse + + +def RunFlake8(): + print( 'Running flake8' ) + subprocess.check_call( [ + 'flake8', + p.join( DIR_OF_THIS_SCRIPT, 'python' ) + ] ) + + +def ParseArguments(): + parser = argparse.ArgumentParser() + parser.add_argument( '--skip-build', action = 'store_true', + help = 'Do not build ycmd before testing.' ) + parser.add_argument( '--no-flake8', action = 'store_true', + help = 'Do not run flake8' ) + + return parser.parse_known_args() + + +def BuildYcmdLibs( args ): + if not args.skip_build: + subprocess.check_call( [ + sys.executable, + p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ) + ] ) + + +def NoseTests( extra_args ): + subprocess.check_call( [ + 'nosetests', + '-v', + '-w', + p.join( DIR_OF_THIS_SCRIPT, 'python' ) + ] + extra_args ) + + +def Main(): + ( parsed_args, extra_args ) = ParseArguments() + if not parsed_args.no_flake8: + RunFlake8() + BuildYcmdLibs( parsed_args ) + NoseTests( extra_args ) + +if __name__ == "__main__": + Main() diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/CHANGES b/vim/bundle/YouCompleteMe/third_party/pythonfutures/CHANGES new file mode 100755 index 0000000..81df636 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/CHANGES @@ -0,0 +1,44 @@ +2.1.4 +===== + +- Ported the library again from Python 3.2.5 to get the latest bug fixes + + +2.1.3 +===== + +- Fixed race condition in wait(return_when=ALL_COMPLETED) + (http://bugs.python.org/issue14406) -- thanks Ralf Schmitt +- Added missing setUp() methods to several test classes + + +2.1.2 +===== + +- Fixed installation problem on Python 3.1 + + +2.1.1 +===== + +- Fixed missing 'concurrent' package declaration in setup.py + + +2.1 +=== + +- Moved the code from the 'futures' package to 'concurrent.futures' to provide + a drop in backport that matches the code in Python 3.2 standard library +- Deprecated the old 'futures' package + + +2.0 +=== + +- Changed implementation to match PEP 3148 + + +1.0 +=== + +Initial release. diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/LICENSE b/vim/bundle/YouCompleteMe/third_party/pythonfutures/LICENSE new file mode 100755 index 0000000..c430db0 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/LICENSE @@ -0,0 +1,21 @@ +Copyright 2009 Brian Quinlan. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY BRIAN QUINLAN "AS IS" AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +HALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/__init__.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/__init__.py new file mode 100755 index 0000000..b36383a --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/__init__.py @@ -0,0 +1,3 @@ +from pkgutil import extend_path + +__path__ = extend_path(__path__, __name__) diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/__init__.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/__init__.py new file mode 100755 index 0000000..b5231f8 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Execute computations asynchronously using threads or processes.""" + +__author__ = 'Brian Quinlan (brian@sweetapp.com)' + +from concurrent.futures._base import (FIRST_COMPLETED, + FIRST_EXCEPTION, + ALL_COMPLETED, + CancelledError, + TimeoutError, + Future, + Executor, + wait, + as_completed) +from concurrent.futures.process import ProcessPoolExecutor +from concurrent.futures.thread import ThreadPoolExecutor diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_base.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_base.py new file mode 100755 index 0000000..8ed69b7 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_base.py @@ -0,0 +1,574 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +from __future__ import with_statement +import logging +import threading +import time + +try: + from collections import namedtuple +except ImportError: + from concurrent.futures._compat import namedtuple + +__author__ = 'Brian Quinlan (brian@sweetapp.com)' + +FIRST_COMPLETED = 'FIRST_COMPLETED' +FIRST_EXCEPTION = 'FIRST_EXCEPTION' +ALL_COMPLETED = 'ALL_COMPLETED' +_AS_COMPLETED = '_AS_COMPLETED' + +# Possible future states (for internal use by the futures package). +PENDING = 'PENDING' +RUNNING = 'RUNNING' +# The future was cancelled by the user... +CANCELLED = 'CANCELLED' +# ...and _Waiter.add_cancelled() was called by a worker. +CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED' +FINISHED = 'FINISHED' + +_FUTURE_STATES = [ + PENDING, + RUNNING, + CANCELLED, + CANCELLED_AND_NOTIFIED, + FINISHED +] + +_STATE_TO_DESCRIPTION_MAP = { + PENDING: "pending", + RUNNING: "running", + CANCELLED: "cancelled", + CANCELLED_AND_NOTIFIED: "cancelled", + FINISHED: "finished" +} + +# Logger for internal use by the futures package. +LOGGER = logging.getLogger("concurrent.futures") + +class Error(Exception): + """Base class for all future-related exceptions.""" + pass + +class CancelledError(Error): + """The Future was cancelled.""" + pass + +class TimeoutError(Error): + """The operation exceeded the given deadline.""" + pass + +class _Waiter(object): + """Provides the event that wait() and as_completed() block on.""" + def __init__(self): + self.event = threading.Event() + self.finished_futures = [] + + def add_result(self, future): + self.finished_futures.append(future) + + def add_exception(self, future): + self.finished_futures.append(future) + + def add_cancelled(self, future): + self.finished_futures.append(future) + +class _AsCompletedWaiter(_Waiter): + """Used by as_completed().""" + + def __init__(self): + super(_AsCompletedWaiter, self).__init__() + self.lock = threading.Lock() + + def add_result(self, future): + with self.lock: + super(_AsCompletedWaiter, self).add_result(future) + self.event.set() + + def add_exception(self, future): + with self.lock: + super(_AsCompletedWaiter, self).add_exception(future) + self.event.set() + + def add_cancelled(self, future): + with self.lock: + super(_AsCompletedWaiter, self).add_cancelled(future) + self.event.set() + +class _FirstCompletedWaiter(_Waiter): + """Used by wait(return_when=FIRST_COMPLETED).""" + + def add_result(self, future): + super(_FirstCompletedWaiter, self).add_result(future) + self.event.set() + + def add_exception(self, future): + super(_FirstCompletedWaiter, self).add_exception(future) + self.event.set() + + def add_cancelled(self, future): + super(_FirstCompletedWaiter, self).add_cancelled(future) + self.event.set() + +class _AllCompletedWaiter(_Waiter): + """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).""" + + def __init__(self, num_pending_calls, stop_on_exception): + self.num_pending_calls = num_pending_calls + self.stop_on_exception = stop_on_exception + self.lock = threading.Lock() + super(_AllCompletedWaiter, self).__init__() + + def _decrement_pending_calls(self): + with self.lock: + self.num_pending_calls -= 1 + if not self.num_pending_calls: + self.event.set() + + def add_result(self, future): + super(_AllCompletedWaiter, self).add_result(future) + self._decrement_pending_calls() + + def add_exception(self, future): + super(_AllCompletedWaiter, self).add_exception(future) + if self.stop_on_exception: + self.event.set() + else: + self._decrement_pending_calls() + + def add_cancelled(self, future): + super(_AllCompletedWaiter, self).add_cancelled(future) + self._decrement_pending_calls() + +class _AcquireFutures(object): + """A context manager that does an ordered acquire of Future conditions.""" + + def __init__(self, futures): + self.futures = sorted(futures, key=id) + + def __enter__(self): + for future in self.futures: + future._condition.acquire() + + def __exit__(self, *args): + for future in self.futures: + future._condition.release() + +def _create_and_install_waiters(fs, return_when): + if return_when == _AS_COMPLETED: + waiter = _AsCompletedWaiter() + elif return_when == FIRST_COMPLETED: + waiter = _FirstCompletedWaiter() + else: + pending_count = sum( + f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs) + + if return_when == FIRST_EXCEPTION: + waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True) + elif return_when == ALL_COMPLETED: + waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False) + else: + raise ValueError("Invalid return condition: %r" % return_when) + + for f in fs: + f._waiters.append(waiter) + + return waiter + +def as_completed(fs, timeout=None): + """An iterator over the given futures that yields each as it completes. + + Args: + fs: The sequence of Futures (possibly created by different Executors) to + iterate over. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + + Returns: + An iterator that yields the given Futures as they complete (finished or + cancelled). + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + """ + if timeout is not None: + end_time = timeout + time.time() + + with _AcquireFutures(fs): + finished = set( + f for f in fs + if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) + pending = set(fs) - finished + waiter = _create_and_install_waiters(fs, _AS_COMPLETED) + + try: + for future in finished: + yield future + + while pending: + if timeout is None: + wait_timeout = None + else: + wait_timeout = end_time - time.time() + if wait_timeout < 0: + raise TimeoutError( + '%d (of %d) futures unfinished' % ( + len(pending), len(fs))) + + waiter.event.wait(wait_timeout) + + with waiter.lock: + finished = waiter.finished_futures + waiter.finished_futures = [] + waiter.event.clear() + + for future in finished: + yield future + pending.remove(future) + + finally: + for f in fs: + f._waiters.remove(waiter) + +DoneAndNotDoneFutures = namedtuple( + 'DoneAndNotDoneFutures', 'done not_done') +def wait(fs, timeout=None, return_when=ALL_COMPLETED): + """Wait for the futures in the given sequence to complete. + + Args: + fs: The sequence of Futures (possibly created by different Executors) to + wait upon. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + return_when: Indicates when this function should return. The options + are: + + FIRST_COMPLETED - Return when any future finishes or is + cancelled. + FIRST_EXCEPTION - Return when any future finishes by raising an + exception. If no future raises an exception + then it is equivalent to ALL_COMPLETED. + ALL_COMPLETED - Return when all futures finish or are cancelled. + + Returns: + A named 2-tuple of sets. The first set, named 'done', contains the + futures that completed (is finished or cancelled) before the wait + completed. The second set, named 'not_done', contains uncompleted + futures. + """ + with _AcquireFutures(fs): + done = set(f for f in fs + if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) + not_done = set(fs) - done + + if (return_when == FIRST_COMPLETED) and done: + return DoneAndNotDoneFutures(done, not_done) + elif (return_when == FIRST_EXCEPTION) and done: + if any(f for f in done + if not f.cancelled() and f.exception() is not None): + return DoneAndNotDoneFutures(done, not_done) + + if len(done) == len(fs): + return DoneAndNotDoneFutures(done, not_done) + + waiter = _create_and_install_waiters(fs, return_when) + + waiter.event.wait(timeout) + for f in fs: + f._waiters.remove(waiter) + + done.update(waiter.finished_futures) + return DoneAndNotDoneFutures(done, set(fs) - done) + +class Future(object): + """Represents the result of an asynchronous computation.""" + + def __init__(self): + """Initializes the future. Should not be called by clients.""" + self._condition = threading.Condition() + self._state = PENDING + self._result = None + self._exception = None + self._waiters = [] + self._done_callbacks = [] + + def _invoke_callbacks(self): + for callback in self._done_callbacks: + try: + callback(self) + except Exception: + LOGGER.exception('exception calling callback for %r', self) + + def __repr__(self): + with self._condition: + if self._state == FINISHED: + if self._exception: + return '<Future at %s state=%s raised %s>' % ( + hex(id(self)), + _STATE_TO_DESCRIPTION_MAP[self._state], + self._exception.__class__.__name__) + else: + return '<Future at %s state=%s returned %s>' % ( + hex(id(self)), + _STATE_TO_DESCRIPTION_MAP[self._state], + self._result.__class__.__name__) + return '<Future at %s state=%s>' % ( + hex(id(self)), + _STATE_TO_DESCRIPTION_MAP[self._state]) + + def cancel(self): + """Cancel the future if possible. + + Returns True if the future was cancelled, False otherwise. A future + cannot be cancelled if it is running or has already completed. + """ + with self._condition: + if self._state in [RUNNING, FINISHED]: + return False + + if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: + return True + + self._state = CANCELLED + self._condition.notify_all() + + self._invoke_callbacks() + return True + + def cancelled(self): + """Return True if the future has cancelled.""" + with self._condition: + return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED] + + def running(self): + """Return True if the future is currently executing.""" + with self._condition: + return self._state == RUNNING + + def done(self): + """Return True of the future was cancelled or finished executing.""" + with self._condition: + return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED] + + def __get_result(self): + if self._exception: + raise self._exception + else: + return self._result + + def add_done_callback(self, fn): + """Attaches a callable that will be called when the future finishes. + + Args: + fn: A callable that will be called with this future as its only + argument when the future completes or is cancelled. The callable + will always be called by a thread in the same process in which + it was added. If the future has already completed or been + cancelled then the callable will be called immediately. These + callables are called in the order that they were added. + """ + with self._condition: + if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]: + self._done_callbacks.append(fn) + return + fn(self) + + def result(self, timeout=None): + """Return the result of the call that the future represents. + + Args: + timeout: The number of seconds to wait for the result if the future + isn't done. If None, then there is no limit on the wait time. + + Returns: + The result of the call that the future represents. + + Raises: + CancelledError: If the future was cancelled. + TimeoutError: If the future didn't finish executing before the given + timeout. + Exception: If the call raised then that exception will be raised. + """ + with self._condition: + if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: + raise CancelledError() + elif self._state == FINISHED: + return self.__get_result() + + self._condition.wait(timeout) + + if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: + raise CancelledError() + elif self._state == FINISHED: + return self.__get_result() + else: + raise TimeoutError() + + def exception(self, timeout=None): + """Return the exception raised by the call that the future represents. + + Args: + timeout: The number of seconds to wait for the exception if the + future isn't done. If None, then there is no limit on the wait + time. + + Returns: + The exception raised by the call that the future represents or None + if the call completed without raising. + + Raises: + CancelledError: If the future was cancelled. + TimeoutError: If the future didn't finish executing before the given + timeout. + """ + + with self._condition: + if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: + raise CancelledError() + elif self._state == FINISHED: + return self._exception + + self._condition.wait(timeout) + + if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: + raise CancelledError() + elif self._state == FINISHED: + return self._exception + else: + raise TimeoutError() + + # The following methods should only be used by Executors and in tests. + def set_running_or_notify_cancel(self): + """Mark the future as running or process any cancel notifications. + + Should only be used by Executor implementations and unit tests. + + If the future has been cancelled (cancel() was called and returned + True) then any threads waiting on the future completing (though calls + to as_completed() or wait()) are notified and False is returned. + + If the future was not cancelled then it is put in the running state + (future calls to running() will return True) and True is returned. + + This method should be called by Executor implementations before + executing the work associated with this future. If this method returns + False then the work should not be executed. + + Returns: + False if the Future was cancelled, True otherwise. + + Raises: + RuntimeError: if this method was already called or if set_result() + or set_exception() was called. + """ + with self._condition: + if self._state == CANCELLED: + self._state = CANCELLED_AND_NOTIFIED + for waiter in self._waiters: + waiter.add_cancelled(self) + # self._condition.notify_all() is not necessary because + # self.cancel() triggers a notification. + return False + elif self._state == PENDING: + self._state = RUNNING + return True + else: + LOGGER.critical('Future %s in unexpected state: %s', + id(self.future), + self.future._state) + raise RuntimeError('Future in unexpected state') + + def set_result(self, result): + """Sets the return value of work associated with the future. + + Should only be used by Executor implementations and unit tests. + """ + with self._condition: + self._result = result + self._state = FINISHED + for waiter in self._waiters: + waiter.add_result(self) + self._condition.notify_all() + self._invoke_callbacks() + + def set_exception(self, exception): + """Sets the result of the future as being the given exception. + + Should only be used by Executor implementations and unit tests. + """ + with self._condition: + self._exception = exception + self._state = FINISHED + for waiter in self._waiters: + waiter.add_exception(self) + self._condition.notify_all() + self._invoke_callbacks() + +class Executor(object): + """This is an abstract base class for concrete asynchronous executors.""" + + def submit(self, fn, *args, **kwargs): + """Submits a callable to be executed with the given arguments. + + Schedules the callable to be executed as fn(*args, **kwargs) and returns + a Future instance representing the execution of the callable. + + Returns: + A Future representing the given call. + """ + raise NotImplementedError() + + def map(self, fn, *iterables, **kwargs): + """Returns a iterator equivalent to map(fn, iter). + + Args: + fn: A callable that will take as many arguments as there are + passed iterables. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + + Returns: + An iterator equivalent to: map(func, *iterables) but the calls may + be evaluated out-of-order. + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + Exception: If fn(*args) raises for any values. + """ + timeout = kwargs.get('timeout') + if timeout is not None: + end_time = timeout + time.time() + + fs = [self.submit(fn, *args) for args in zip(*iterables)] + + try: + for future in fs: + if timeout is None: + yield future.result() + else: + yield future.result(end_time - time.time()) + finally: + for future in fs: + future.cancel() + + def shutdown(self, wait=True): + """Clean-up the resources associated with the Executor. + + It is safe to call this method several times. Otherwise, no other + methods can be called after this one. + + Args: + wait: If True then shutdown will not return until all running + futures have finished executing and the resources used by the + executor have been reclaimed. + """ + pass + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.shutdown(wait=True) + return False diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_compat.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_compat.py new file mode 100755 index 0000000..1146232 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_compat.py @@ -0,0 +1,101 @@ +from keyword import iskeyword as _iskeyword +from operator import itemgetter as _itemgetter +import sys as _sys + + +def namedtuple(typename, field_names): + """Returns a new subclass of tuple with named fields. + + >>> Point = namedtuple('Point', 'x y') + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with positional args or keywords + >>> p[0] + p[1] # indexable like a plain tuple + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessable by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + + """ + + # Parse and validate the field names. Validation serves two purposes, + # generating informative error messages and preventing template injection attacks. + if isinstance(field_names, basestring): + field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas + field_names = tuple(map(str, field_names)) + for name in (typename,) + field_names: + if not all(c.isalnum() or c=='_' for c in name): + raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) + if _iskeyword(name): + raise ValueError('Type names and field names cannot be a keyword: %r' % name) + if name[0].isdigit(): + raise ValueError('Type names and field names cannot start with a number: %r' % name) + seen_names = set() + for name in field_names: + if name.startswith('_'): + raise ValueError('Field names cannot start with an underscore: %r' % name) + if name in seen_names: + raise ValueError('Encountered duplicate field name: %r' % name) + seen_names.add(name) + + # Create and fill-in the class template + numfields = len(field_names) + argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes + reprtxt = ', '.join('%s=%%r' % name for name in field_names) + dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names)) + template = '''class %(typename)s(tuple): + '%(typename)s(%(argtxt)s)' \n + __slots__ = () \n + _fields = %(field_names)r \n + def __new__(_cls, %(argtxt)s): + return _tuple.__new__(_cls, (%(argtxt)s)) \n + @classmethod + def _make(cls, iterable, new=tuple.__new__, len=len): + 'Make a new %(typename)s object from a sequence or iterable' + result = new(cls, iterable) + if len(result) != %(numfields)d: + raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) + return result \n + def __repr__(self): + return '%(typename)s(%(reprtxt)s)' %% self \n + def _asdict(t): + 'Return a new dict which maps field names to their values' + return {%(dicttxt)s} \n + def _replace(_self, **kwds): + 'Return a new %(typename)s object replacing specified fields with new values' + result = _self._make(map(kwds.pop, %(field_names)r, _self)) + if kwds: + raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) + return result \n + def __getnewargs__(self): + return tuple(self) \n\n''' % locals() + for i, name in enumerate(field_names): + template += ' %s = _property(_itemgetter(%d))\n' % (name, i) + + # Execute the template string in a temporary namespace and + # support tracing utilities by setting a value for frame.f_globals['__name__'] + namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, + _property=property, _tuple=tuple) + try: + exec(template, namespace) + except SyntaxError: + e = _sys.exc_info()[1] + raise SyntaxError(e.message + ':\n' + template) + result = namespace[typename] + + # For pickling to work, the __module__ variable needs to be set to the frame + # where the named tuple is created. Bypass this step in enviroments where + # sys._getframe is not defined (Jython for example). + if hasattr(_sys, '_getframe'): + result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') + + return result diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/process.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/process.py new file mode 100755 index 0000000..98684f8 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/process.py @@ -0,0 +1,363 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Implements ProcessPoolExecutor. + +The follow diagram and text describe the data-flow through the system: + +|======================= In-process =====================|== Out-of-process ==| + ++----------+ +----------+ +--------+ +-----------+ +---------+ +| | => | Work Ids | => | | => | Call Q | => | | +| | +----------+ | | +-----------+ | | +| | | ... | | | | ... | | | +| | | 6 | | | | 5, call() | | | +| | | 7 | | | | ... | | | +| Process | | ... | | Local | +-----------+ | Process | +| Pool | +----------+ | Worker | | #1..n | +| Executor | | Thread | | | +| | +----------- + | | +-----------+ | | +| | <=> | Work Items | <=> | | <= | Result Q | <= | | +| | +------------+ | | +-----------+ | | +| | | 6: call() | | | | ... | | | +| | | future | | | | 4, result | | | +| | | ... | | | | 3, except | | | ++----------+ +------------+ +--------+ +-----------+ +---------+ + +Executor.submit() called: +- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict +- adds the id of the _WorkItem to the "Work Ids" queue + +Local worker thread: +- reads work ids from the "Work Ids" queue and looks up the corresponding + WorkItem from the "Work Items" dict: if the work item has been cancelled then + it is simply removed from the dict, otherwise it is repackaged as a + _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" + until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because + calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). +- reads _ResultItems from "Result Q", updates the future stored in the + "Work Items" dict and deletes the dict entry + +Process #1..n: +- reads _CallItems from "Call Q", executes the calls, and puts the resulting + _ResultItems in "Request Q" +""" + +from __future__ import with_statement +import atexit +import multiprocessing +import threading +import weakref +import sys + +from concurrent.futures import _base + +try: + import queue +except ImportError: + import Queue as queue + +__author__ = 'Brian Quinlan (brian@sweetapp.com)' + +# Workers are created as daemon threads and processes. This is done to allow the +# interpreter to exit when there are still idle processes in a +# ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However, +# allowing workers to die with the interpreter has two undesirable properties: +# - The workers would still be running during interpretor shutdown, +# meaning that they would fail in unpredictable ways. +# - The workers could be killed while evaluating a work item, which could +# be bad if the callable being evaluated has external side-effects e.g. +# writing to a file. +# +# To work around this problem, an exit handler is installed which tells the +# workers to exit when their work queues are empty and then waits until the +# threads/processes finish. + +_threads_queues = weakref.WeakKeyDictionary() +_shutdown = False + +def _python_exit(): + global _shutdown + _shutdown = True + items = list(_threads_queues.items()) + for t, q in items: + q.put(None) + for t, q in items: + t.join() + +# Controls how many more calls than processes will be queued in the call queue. +# A smaller number will mean that processes spend more time idle waiting for +# work while a larger number will make Future.cancel() succeed less frequently +# (Futures in the call queue cannot be cancelled). +EXTRA_QUEUED_CALLS = 1 + +class _WorkItem(object): + def __init__(self, future, fn, args, kwargs): + self.future = future + self.fn = fn + self.args = args + self.kwargs = kwargs + +class _ResultItem(object): + def __init__(self, work_id, exception=None, result=None): + self.work_id = work_id + self.exception = exception + self.result = result + +class _CallItem(object): + def __init__(self, work_id, fn, args, kwargs): + self.work_id = work_id + self.fn = fn + self.args = args + self.kwargs = kwargs + +def _process_worker(call_queue, result_queue): + """Evaluates calls from call_queue and places the results in result_queue. + + This worker is run in a separate process. + + Args: + call_queue: A multiprocessing.Queue of _CallItems that will be read and + evaluated by the worker. + result_queue: A multiprocessing.Queue of _ResultItems that will written + to by the worker. + shutdown: A multiprocessing.Event that will be set as a signal to the + worker that it should exit when call_queue is empty. + """ + while True: + call_item = call_queue.get(block=True) + if call_item is None: + # Wake up queue management thread + result_queue.put(None) + return + try: + r = call_item.fn(*call_item.args, **call_item.kwargs) + except BaseException: + e = sys.exc_info()[1] + result_queue.put(_ResultItem(call_item.work_id, + exception=e)) + else: + result_queue.put(_ResultItem(call_item.work_id, + result=r)) + +def _add_call_item_to_queue(pending_work_items, + work_ids, + call_queue): + """Fills call_queue with _WorkItems from pending_work_items. + + This function never blocks. + + Args: + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids + are consumed and the corresponding _WorkItems from + pending_work_items are transformed into _CallItems and put in + call_queue. + call_queue: A multiprocessing.Queue that will be filled with _CallItems + derived from _WorkItems. + """ + while True: + if call_queue.full(): + return + try: + work_id = work_ids.get(block=False) + except queue.Empty: + return + else: + work_item = pending_work_items[work_id] + + if work_item.future.set_running_or_notify_cancel(): + call_queue.put(_CallItem(work_id, + work_item.fn, + work_item.args, + work_item.kwargs), + block=True) + else: + del pending_work_items[work_id] + continue + +def _queue_management_worker(executor_reference, + processes, + pending_work_items, + work_ids_queue, + call_queue, + result_queue): + """Manages the communication between this process and the worker processes. + + This function is run in a local thread. + + Args: + executor_reference: A weakref.ref to the ProcessPoolExecutor that owns + this thread. Used to determine if the ProcessPoolExecutor has been + garbage collected and that this function can exit. + process: A list of the multiprocessing.Process instances used as + workers. + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). + call_queue: A multiprocessing.Queue that will be filled with _CallItems + derived from _WorkItems for processing by the process workers. + result_queue: A multiprocessing.Queue of _ResultItems generated by the + process workers. + """ + nb_shutdown_processes = [0] + def shutdown_one_process(): + """Tell a worker to terminate, which will in turn wake us again""" + call_queue.put(None) + nb_shutdown_processes[0] += 1 + while True: + _add_call_item_to_queue(pending_work_items, + work_ids_queue, + call_queue) + + result_item = result_queue.get(block=True) + if result_item is not None: + work_item = pending_work_items[result_item.work_id] + del pending_work_items[result_item.work_id] + + if result_item.exception: + work_item.future.set_exception(result_item.exception) + else: + work_item.future.set_result(result_item.result) + # Check whether we should start shutting down. + executor = executor_reference() + # No more work items can be added if: + # - The interpreter is shutting down OR + # - The executor that owns this worker has been collected OR + # - The executor that owns this worker has been shutdown. + if _shutdown or executor is None or executor._shutdown_thread: + # Since no new work items can be added, it is safe to shutdown + # this thread if there are no pending work items. + if not pending_work_items: + while nb_shutdown_processes[0] < len(processes): + shutdown_one_process() + # If .join() is not called on the created processes then + # some multiprocessing.Queue methods may deadlock on Mac OS + # X. + for p in processes: + p.join() + call_queue.close() + return + del executor + +_system_limits_checked = False +_system_limited = None +def _check_system_limits(): + global _system_limits_checked, _system_limited + if _system_limits_checked: + if _system_limited: + raise NotImplementedError(_system_limited) + _system_limits_checked = True + try: + import os + nsems_max = os.sysconf("SC_SEM_NSEMS_MAX") + except (AttributeError, ValueError): + # sysconf not available or setting not available + return + if nsems_max == -1: + # indetermine limit, assume that limit is determined + # by available memory only + return + if nsems_max >= 256: + # minimum number of semaphores available + # according to POSIX + return + _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max + raise NotImplementedError(_system_limited) + +class ProcessPoolExecutor(_base.Executor): + def __init__(self, max_workers=None): + """Initializes a new ProcessPoolExecutor instance. + + Args: + max_workers: The maximum number of processes that can be used to + execute the given calls. If None or not given then as many + worker processes will be created as the machine has processors. + """ + _check_system_limits() + + if max_workers is None: + self._max_workers = multiprocessing.cpu_count() + else: + self._max_workers = max_workers + + # Make the call queue slightly larger than the number of processes to + # prevent the worker processes from idling. But don't make it too big + # because futures in the call queue cannot be cancelled. + self._call_queue = multiprocessing.Queue(self._max_workers + + EXTRA_QUEUED_CALLS) + self._result_queue = multiprocessing.Queue() + self._work_ids = queue.Queue() + self._queue_management_thread = None + self._processes = set() + + # Shutdown is a two-step process. + self._shutdown_thread = False + self._shutdown_lock = threading.Lock() + self._queue_count = 0 + self._pending_work_items = {} + + def _start_queue_management_thread(self): + # When the executor gets lost, the weakref callback will wake up + # the queue management thread. + def weakref_cb(_, q=self._result_queue): + q.put(None) + if self._queue_management_thread is None: + self._queue_management_thread = threading.Thread( + target=_queue_management_worker, + args=(weakref.ref(self, weakref_cb), + self._processes, + self._pending_work_items, + self._work_ids, + self._call_queue, + self._result_queue)) + self._queue_management_thread.daemon = True + self._queue_management_thread.start() + _threads_queues[self._queue_management_thread] = self._result_queue + + def _adjust_process_count(self): + for _ in range(len(self._processes), self._max_workers): + p = multiprocessing.Process( + target=_process_worker, + args=(self._call_queue, + self._result_queue)) + p.start() + self._processes.add(p) + + def submit(self, fn, *args, **kwargs): + with self._shutdown_lock: + if self._shutdown_thread: + raise RuntimeError('cannot schedule new futures after shutdown') + + f = _base.Future() + w = _WorkItem(f, fn, args, kwargs) + + self._pending_work_items[self._queue_count] = w + self._work_ids.put(self._queue_count) + self._queue_count += 1 + # Wake up queue management thread + self._result_queue.put(None) + + self._start_queue_management_thread() + self._adjust_process_count() + return f + submit.__doc__ = _base.Executor.submit.__doc__ + + def shutdown(self, wait=True): + with self._shutdown_lock: + self._shutdown_thread = True + if self._queue_management_thread: + # Wake up queue management thread + self._result_queue.put(None) + if wait: + self._queue_management_thread.join() + # To reduce the risk of openning too many files, remove references to + # objects that use file descriptors. + self._queue_management_thread = None + self._call_queue = None + self._result_queue = None + self._processes = None + shutdown.__doc__ = _base.Executor.shutdown.__doc__ + +atexit.register(_python_exit) diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/thread.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/thread.py new file mode 100755 index 0000000..a45959d --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/concurrent/futures/thread.py @@ -0,0 +1,138 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Implements ThreadPoolExecutor.""" + +from __future__ import with_statement +import atexit +import threading +import weakref +import sys + +from concurrent.futures import _base + +try: + import queue +except ImportError: + import Queue as queue + +__author__ = 'Brian Quinlan (brian@sweetapp.com)' + +# Workers are created as daemon threads. This is done to allow the interpreter +# to exit when there are still idle threads in a ThreadPoolExecutor's thread +# pool (i.e. shutdown() was not called). However, allowing workers to die with +# the interpreter has two undesirable properties: +# - The workers would still be running during interpretor shutdown, +# meaning that they would fail in unpredictable ways. +# - The workers could be killed while evaluating a work item, which could +# be bad if the callable being evaluated has external side-effects e.g. +# writing to a file. +# +# To work around this problem, an exit handler is installed which tells the +# workers to exit when their work queues are empty and then waits until the +# threads finish. + +_threads_queues = weakref.WeakKeyDictionary() +_shutdown = False + +def _python_exit(): + global _shutdown + _shutdown = True + items = list(_threads_queues.items()) + for t, q in items: + q.put(None) + for t, q in items: + t.join() + +atexit.register(_python_exit) + +class _WorkItem(object): + def __init__(self, future, fn, args, kwargs): + self.future = future + self.fn = fn + self.args = args + self.kwargs = kwargs + + def run(self): + if not self.future.set_running_or_notify_cancel(): + return + + try: + result = self.fn(*self.args, **self.kwargs) + except BaseException: + e = sys.exc_info()[1] + self.future.set_exception(e) + else: + self.future.set_result(result) + +def _worker(executor_reference, work_queue): + try: + while True: + work_item = work_queue.get(block=True) + if work_item is not None: + work_item.run() + continue + executor = executor_reference() + # Exit if: + # - The interpreter is shutting down OR + # - The executor that owns the worker has been collected OR + # - The executor that owns the worker has been shutdown. + if _shutdown or executor is None or executor._shutdown: + # Notice other workers + work_queue.put(None) + return + del executor + except BaseException: + _base.LOGGER.critical('Exception in worker', exc_info=True) + +class ThreadPoolExecutor(_base.Executor): + def __init__(self, max_workers): + """Initializes a new ThreadPoolExecutor instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + """ + self._max_workers = max_workers + self._work_queue = queue.Queue() + self._threads = set() + self._shutdown = False + self._shutdown_lock = threading.Lock() + + def submit(self, fn, *args, **kwargs): + with self._shutdown_lock: + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + + f = _base.Future() + w = _WorkItem(f, fn, args, kwargs) + + self._work_queue.put(w) + self._adjust_thread_count() + return f + submit.__doc__ = _base.Executor.submit.__doc__ + + def _adjust_thread_count(self): + # When the executor gets lost, the weakref callback will wake up + # the worker threads. + def weakref_cb(_, q=self._work_queue): + q.put(None) + # TODO(bquinlan): Should avoid creating new threads if there are more + # idle threads than items in the work queue. + if len(self._threads) < self._max_workers: + t = threading.Thread(target=_worker, + args=(weakref.ref(self, weakref_cb), + self._work_queue)) + t.daemon = True + t.start() + self._threads.add(t) + _threads_queues[t] = self._work_queue + + def shutdown(self, wait=True): + with self._shutdown_lock: + self._shutdown = True + self._work_queue.put(None) + if wait: + for t in self._threads: + t.join() + shutdown.__doc__ = _base.Executor.shutdown.__doc__ diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/crawl.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/crawl.py new file mode 100755 index 0000000..86e0af7 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/crawl.py @@ -0,0 +1,74 @@ +"""Compare the speed of downloading URLs sequentially vs. using futures.""" + +import functools +import time +import timeit +import sys + +try: + from urllib2 import urlopen +except ImportError: + from urllib.request import urlopen + +from concurrent.futures import (as_completed, ThreadPoolExecutor, + ProcessPoolExecutor) + +URLS = ['http://www.google.com/', + 'http://www.apple.com/', + 'http://www.ibm.com', + 'http://www.thisurlprobablydoesnotexist.com', + 'http://www.slashdot.org/', + 'http://www.python.org/', + 'http://www.bing.com/', + 'http://www.facebook.com/', + 'http://www.yahoo.com/', + 'http://www.youtube.com/', + 'http://www.blogger.com/'] + +def load_url(url, timeout): + kwargs = {'timeout': timeout} if sys.version_info >= (2, 6) else {} + return urlopen(url, **kwargs).read() + +def download_urls_sequential(urls, timeout=60): + url_to_content = {} + for url in urls: + try: + url_to_content[url] = load_url(url, timeout=timeout) + except: + pass + return url_to_content + +def download_urls_with_executor(urls, executor, timeout=60): + try: + url_to_content = {} + future_to_url = dict((executor.submit(load_url, url, timeout), url) + for url in urls) + + for future in as_completed(future_to_url): + try: + url_to_content[future_to_url[future]] = future.result() + except: + pass + return url_to_content + finally: + executor.shutdown() + +def main(): + for name, fn in [('sequential', + functools.partial(download_urls_sequential, URLS)), + ('processes', + functools.partial(download_urls_with_executor, + URLS, + ProcessPoolExecutor(10))), + ('threads', + functools.partial(download_urls_with_executor, + URLS, + ThreadPoolExecutor(10)))]: + sys.stdout.write('%s: ' % name.ljust(12)) + start = time.time() + url_map = fn() + sys.stdout.write('%.2f seconds (%d of %d downloaded)\n' % + (time.time() - start, len(url_map), len(URLS))) + +if __name__ == '__main__': + main() diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/conf.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/conf.py new file mode 100755 index 0000000..124cd51 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/conf.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# +# futures documentation build configuration file, created by +# sphinx-quickstart on Wed Jun 3 19:35:34 2009. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.append(os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'futures' +copyright = u'2009-2011, Brian Quinlan' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '2.1.3' +# The full version, including alpha/beta/rc tags. +release = '2.1.3' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of documents that shouldn't be included in the build. +#unused_docs = [] + +# List of directories, relative to source directory, that shouldn't be searched +# for source files. +exclude_trees = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. Major themes that come with +# Sphinx are currently 'default' and 'sphinxdoc'. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# "<project> v<release> documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_use_modindex = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a <link> tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = '' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'futuresdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'futures.tex', u'futures Documentation', + u'Brian Quinlan', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_use_modindex = True diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/index.rst b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/index.rst new file mode 100755 index 0000000..525ce6a --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/index.rst @@ -0,0 +1,345 @@ +:mod:`concurrent.futures` --- Asynchronous computation +====================================================== + +.. module:: concurrent.futures + :synopsis: Execute computations asynchronously using threads or processes. + +The :mod:`concurrent.futures` module provides a high-level interface for +asynchronously executing callables. + +The asynchronous execution can be be performed by threads using +:class:`ThreadPoolExecutor` or seperate processes using +:class:`ProcessPoolExecutor`. Both implement the same interface, which is +defined by the abstract :class:`Executor` class. + +Executor Objects +---------------- + +:class:`Executor` is an abstract class that provides methods to execute calls +asynchronously. It should not be used directly, but through its two +subclasses: :class:`ThreadPoolExecutor` and :class:`ProcessPoolExecutor`. + +.. method:: Executor.submit(fn, *args, **kwargs) + + Schedules the callable to be executed as *fn*(*\*args*, *\*\*kwargs*) and + returns a :class:`Future` representing the execution of the callable. + +:: + + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(pow, 323, 1235) + print(future.result()) + +.. method:: Executor.map(func, *iterables, timeout=None) + + Equivalent to map(*func*, *\*iterables*) but func is executed asynchronously + and several calls to *func* may be made concurrently. The returned iterator + raises a :exc:`TimeoutError` if :meth:`__next__()` is called and the result + isn't available after *timeout* seconds from the original call to + :meth:`map()`. *timeout* can be an int or float. If *timeout* is not + specified or ``None`` then there is no limit to the wait time. If a call + raises an exception then that exception will be raised when its value is + retrieved from the iterator. + +.. method:: Executor.shutdown(wait=True) + + Signal the executor that it should free any resources that it is using when + the currently pending futures are done executing. Calls to + :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will + raise :exc:`RuntimeError`. + + If *wait* is `True` then this method will not return until all the pending + futures are done executing and the resources associated with the executor + have been freed. If *wait* is `False` then this method will return + immediately and the resources associated with the executor will be freed + when all pending futures are done executing. Regardless of the value of + *wait*, the entire Python program will not exit until all pending futures + are done executing. + + You can avoid having to call this method explicitly if you use the `with` + statement, which will shutdown the `Executor` (waiting as if + `Executor.shutdown` were called with *wait* set to `True`): + +:: + + import shutil + with ThreadPoolExecutor(max_workers=4) as e: + e.submit(shutil.copy, 'src1.txt', 'dest1.txt') + e.submit(shutil.copy, 'src2.txt', 'dest2.txt') + e.submit(shutil.copy, 'src3.txt', 'dest3.txt') + e.submit(shutil.copy, 'src3.txt', 'dest4.txt') + + +ThreadPoolExecutor Objects +-------------------------- + +The :class:`ThreadPoolExecutor` class is an :class:`Executor` subclass that uses +a pool of threads to execute calls asynchronously. + +Deadlock can occur when the callable associated with a :class:`Future` waits on +the results of another :class:`Future`. For example: + +:: + + import time + def wait_on_b(): + time.sleep(5) + print(b.result()) # b will never complete because it is waiting on a. + return 5 + + def wait_on_a(): + time.sleep(5) + print(a.result()) # a will never complete because it is waiting on b. + return 6 + + + executor = ThreadPoolExecutor(max_workers=2) + a = executor.submit(wait_on_b) + b = executor.submit(wait_on_a) + +And: + +:: + + def wait_on_future(): + f = executor.submit(pow, 5, 2) + # This will never complete because there is only one worker thread and + # it is executing this function. + print(f.result()) + + executor = ThreadPoolExecutor(max_workers=1) + executor.submit(wait_on_future) + +.. class:: ThreadPoolExecutor(max_workers) + + Executes calls asynchronously using at pool of at most *max_workers* threads. + +.. _threadpoolexecutor-example: + +ThreadPoolExecutor Example +^^^^^^^^^^^^^^^^^^^^^^^^^^ +:: + + from concurrent import futures + import urllib.request + + URLS = ['http://www.foxnews.com/', + 'http://www.cnn.com/', + 'http://europe.wsj.com/', + 'http://www.bbc.co.uk/', + 'http://some-made-up-domain.com/'] + + def load_url(url, timeout): + return urllib.request.urlopen(url, timeout=timeout).read() + + with futures.ThreadPoolExecutor(max_workers=5) as executor: + future_to_url = dict((executor.submit(load_url, url, 60), url) + for url in URLS) + + for future in futures.as_completed(future_to_url): + url = future_to_url[future] + if future.exception() is not None: + print('%r generated an exception: %s' % (url, + future.exception())) + else: + print('%r page is %d bytes' % (url, len(future.result()))) + +ProcessPoolExecutor Objects +--------------------------- + +The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that +uses a pool of processes to execute calls asynchronously. +:class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which +allows it to side-step the :term:`Global Interpreter Lock` but also means that +only picklable objects can be executed and returned. + +Calling :class:`Executor` or :class:`Future` methods from a callable submitted +to a :class:`ProcessPoolExecutor` will result in deadlock. + +.. class:: ProcessPoolExecutor(max_workers=None) + + Executes calls asynchronously using a pool of at most *max_workers* + processes. If *max_workers* is ``None`` or not given then as many worker + processes will be created as the machine has processors. + +.. _processpoolexecutor-example: + +ProcessPoolExecutor Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +:: + + import math + + PRIMES = [ + 112272535095293, + 112582705942171, + 112272535095293, + 115280095190773, + 115797848077099, + 1099726899285419] + + def is_prime(n): + if n % 2 == 0: + return False + + sqrt_n = int(math.floor(math.sqrt(n))) + for i in range(3, sqrt_n + 1, 2): + if n % i == 0: + return False + return True + + def main(): + with futures.ProcessPoolExecutor() as executor: + for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)): + print('%d is prime: %s' % (number, prime)) + + if __name__ == '__main__': + main() + +Future Objects +-------------- + +The :class:`Future` class encapulates the asynchronous execution of a callable. +:class:`Future` instances are created by :meth:`Executor.submit`. + +.. method:: Future.cancel() + + Attempt to cancel the call. If the call is currently being executed then + it cannot be cancelled and the method will return `False`, otherwise the call + will be cancelled and the method will return `True`. + +.. method:: Future.cancelled() + + Return `True` if the call was successfully cancelled. + +.. method:: Future.running() + + Return `True` if the call is currently being executed and cannot be + cancelled. + +.. method:: Future.done() + + Return `True` if the call was successfully cancelled or finished running. + +.. method:: Future.result(timeout=None) + + Return the value returned by the call. If the call hasn't yet completed then + this method will wait up to *timeout* seconds. If the call hasn't completed + in *timeout* seconds then a :exc:`TimeoutError` will be raised. *timeout* can + be an int or float.If *timeout* is not specified or ``None`` then there is no + limit to the wait time. + + If the future is cancelled before completing then :exc:`CancelledError` will + be raised. + + If the call raised then this method will raise the same exception. + +.. method:: Future.exception(timeout=None) + + Return the exception raised by the call. If the call hasn't yet completed + then this method will wait up to *timeout* seconds. If the call hasn't + completed in *timeout* seconds then a :exc:`TimeoutError` will be raised. + *timeout* can be an int or float. If *timeout* is not specified or ``None`` + then there is no limit to the wait time. + + If the future is cancelled before completing then :exc:`CancelledError` will + be raised. + + If the call completed without raising then ``None`` is returned. + +.. method:: Future.add_done_callback(fn) + + Attaches the callable *fn* to the future. *fn* will be called, with the + future as its only argument, when the future is cancelled or finishes + running. + + Added callables are called in the order that they were added and are always + called in a thread belonging to the process that added them. If the callable + raises an :exc:`Exception` then it will be logged and ignored. If the + callable raises another :exc:`BaseException` then the behavior is not + defined. + + If the future has already completed or been cancelled then *fn* will be + called immediately. + +Internal Future Methods +^^^^^^^^^^^^^^^^^^^^^^^ + +The following :class:`Future` methods are meant for use in unit tests and +:class:`Executor` implementations. + +.. method:: Future.set_running_or_notify_cancel() + + This method should only be called by :class:`Executor` implementations before + executing the work associated with the :class:`Future` and by unit tests. + + If the method returns `False` then the :class:`Future` was cancelled i.e. + :meth:`Future.cancel` was called and returned `True`. Any threads waiting + on the :class:`Future` completing (i.e. through :func:`as_completed` or + :func:`wait`) will be woken up. + + If the method returns `True` then the :class:`Future` was not cancelled + and has been put in the running state i.e. calls to + :meth:`Future.running` will return `True`. + + This method can only be called once and cannot be called after + :meth:`Future.set_result` or :meth:`Future.set_exception` have been + called. + +.. method:: Future.set_result(result) + + Sets the result of the work associated with the :class:`Future` to *result*. + + This method should only be used by Executor implementations and unit tests. + +.. method:: Future.set_exception(exception) + + Sets the result of the work associated with the :class:`Future` to the + :class:`Exception` *exception*. + + This method should only be used by Executor implementations and unit tests. + +Module Functions +---------------- + +.. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED) + + Wait for the :class:`Future` instances (possibly created by different + :class:`Executor` instances) given by *fs* to complete. Returns a named + 2-tuple of sets. The first set, named "done", contains the futures that + completed (finished or were cancelled) before the wait completed. The second + set, named "not_done", contains uncompleted futures. + + *timeout* can be used to control the maximum number of seconds to wait before + returning. *timeout* can be an int or float. If *timeout* is not specified or + ``None`` then there is no limit to the wait time. + + *return_when* indicates when this function should return. It must be one of + the following constants: + + +-----------------------------+----------------------------------------+ + | Constant | Description | + +=============================+========================================+ + | :const:`FIRST_COMPLETED` | The function will return when any | + | | future finishes or is cancelled. | + +-----------------------------+----------------------------------------+ + | :const:`FIRST_EXCEPTION` | The function will return when any | + | | future finishes by raising an | + | | exception. If no future raises an | + | | exception then it is equivalent to | + | | `ALL_COMPLETED`. | + +-----------------------------+----------------------------------------+ + | :const:`ALL_COMPLETED` | The function will return when all | + | | futures finish or are cancelled. | + +-----------------------------+----------------------------------------+ + +.. function:: as_completed(fs, timeout=None) + + Returns an iterator over the :class:`Future` instances (possibly created + by different :class:`Executor` instances) given by *fs* that yields futures + as they complete (finished or were cancelled). Any futures that completed + before :func:`as_completed()` was called will be yielded first. The returned + iterator raises a :exc:`TimeoutError` if :meth:`__next__()` is called and + the result isn't available after *timeout* seconds from the original call + to :func:`as_completed()`. *timeout* can be an int or float. If *timeout* + is not specified or ``None`` then there is no limit to the wait time. diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/make.bat b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/make.bat new file mode 100755 index 0000000..3e8021b --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/docs/make.bat @@ -0,0 +1,112 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +set SPHINXBUILD=sphinx-build +set ALLSPHINXOPTS=-d _build/doctrees %SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^<target^>` where ^<target^> is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (_build\*) do rmdir /q /s %%i + del /q /s _build\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% _build/html + echo. + echo.Build finished. The HTML pages are in _build/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% _build/dirhtml + echo. + echo.Build finished. The HTML pages are in _build/dirhtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% _build/pickle + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% _build/json + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% _build/htmlhelp + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in _build/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% _build/qthelp + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in _build/qthelp, like this: + echo.^> qcollectiongenerator _build\qthelp\futures.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile _build\qthelp\futures.ghc + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% _build/latex + echo. + echo.Build finished; the LaTeX files are in _build/latex. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% _build/changes + echo. + echo.The overview file is in _build/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% _build/linkcheck + echo. + echo.Link check complete; look for any errors in the above output ^ +or in _build/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% _build/doctest + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in _build/doctest/output.txt. + goto end +) + +:end diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/__init__.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/__init__.py new file mode 100755 index 0000000..8f8b234 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Execute computations asynchronously using threads or processes.""" + +import warnings + +from concurrent.futures import (FIRST_COMPLETED, + FIRST_EXCEPTION, + ALL_COMPLETED, + CancelledError, + TimeoutError, + Future, + Executor, + wait, + as_completed, + ProcessPoolExecutor, + ThreadPoolExecutor) + +__author__ = 'Brian Quinlan (brian@sweetapp.com)' + +warnings.warn('The futures package has been deprecated. ' + 'Use the concurrent.futures package instead.', + DeprecationWarning) diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/process.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/process.py new file mode 100755 index 0000000..e9d37b1 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/process.py @@ -0,0 +1 @@ +from concurrent.futures import ProcessPoolExecutor diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/thread.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/thread.py new file mode 100755 index 0000000..f6bd05d --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/futures/thread.py @@ -0,0 +1 @@ +from concurrent.futures import ThreadPoolExecutor diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/primes.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/primes.py new file mode 100755 index 0000000..0da2b3e --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/primes.py @@ -0,0 +1,50 @@ +from __future__ import with_statement +import math +import time +import sys + +from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor + +PRIMES = [ + 112272535095293, + 112582705942171, + 112272535095293, + 115280095190773, + 115797848077099, + 117450548693743, + 993960000099397] + +def is_prime(n): + if n % 2 == 0: + return False + + sqrt_n = int(math.floor(math.sqrt(n))) + for i in range(3, sqrt_n + 1, 2): + if n % i == 0: + return False + return True + +def sequential(): + return list(map(is_prime, PRIMES)) + +def with_process_pool_executor(): + with ProcessPoolExecutor(10) as executor: + return list(executor.map(is_prime, PRIMES)) + +def with_thread_pool_executor(): + with ThreadPoolExecutor(10) as executor: + return list(executor.map(is_prime, PRIMES)) + +def main(): + for name, fn in [('sequential', sequential), + ('processes', with_process_pool_executor), + ('threads', with_thread_pool_executor)]: + sys.stdout.write('%s: ' % name.ljust(12)) + start = time.time() + if fn() != [True] * len(PRIMES): + sys.stdout.write('failed\n') + else: + sys.stdout.write('%.2f seconds\n' % (time.time() - start)) + +if __name__ == '__main__': + main() diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.cfg b/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.cfg new file mode 100755 index 0000000..0a9f4f5 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.cfg @@ -0,0 +1,6 @@ +[build_sphinx] +source-dir = docs +build-dir = build/sphinx + +[upload_docs] +upload-dir = build/sphinx/html diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.py new file mode 100755 index 0000000..c08461e --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/setup.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +import sys + +extras = {} +try: + from setuptools import setup + extras['zip_safe'] = False + if sys.version_info < (2, 6): + extras['install_requires'] = ['multiprocessing'] +except ImportError: + from distutils.core import setup + +setup(name='futures', + version='2.1.4', + description='Backport of the concurrent.futures package from Python 3.2', + author='Brian Quinlan', + author_email='brian@sweetapp.com', + maintainer='Alex Gronholm', + maintainer_email='alex.gronholm+pypi@nextday.fi', + url='http://code.google.com/p/pythonfutures', + download_url='http://pypi.python.org/pypi/futures/', + packages=['futures', 'concurrent', 'concurrent.futures'], + license='BSD', + classifiers=['License :: OSI Approved :: BSD License', + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Programming Language :: Python :: 2.5', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.1'], + **extras + ) diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/test_futures.py b/vim/bundle/YouCompleteMe/third_party/pythonfutures/test_futures.py new file mode 100755 index 0000000..dd7fd3e --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/test_futures.py @@ -0,0 +1,723 @@ +from __future__ import with_statement +import os +import subprocess +import sys +import threading +import functools +import contextlib +import logging +import re +import time + +from concurrent import futures +from concurrent.futures._base import ( + PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED, Future) + +try: + import unittest2 as unittest +except ImportError: + import unittest + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + +try: + from test import test_support +except ImportError: + from test import support as test_support + +try: + next +except NameError: + next = lambda x: x.next() + + +def reap_threads(func): + """Use this function when threads are being used. This will + ensure that the threads are cleaned up even when the test fails. + If threading is unavailable this function does nothing. + """ + @functools.wraps(func) + def decorator(*args): + key = test_support.threading_setup() + try: + return func(*args) + finally: + test_support.threading_cleanup(*key) + return decorator + + +# Executing the interpreter in a subprocess +def _assert_python(expected_success, *args, **env_vars): + cmd_line = [sys.executable] + if not env_vars: + cmd_line.append('-E') + # Need to preserve the original environment, for in-place testing of + # shared library builds. + env = os.environ.copy() + # But a special flag that can be set to override -- in this case, the + # caller is responsible to pass the full environment. + if env_vars.pop('__cleanenv', None): + env = {} + env.update(env_vars) + cmd_line.extend(args) + p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=env) + try: + out, err = p.communicate() + finally: + subprocess._cleanup() + p.stdout.close() + p.stderr.close() + rc = p.returncode + err = strip_python_stderr(err) + if (rc and expected_success) or (not rc and not expected_success): + raise AssertionError( + "Process return code is %d, " + "stderr follows:\n%s" % (rc, err.decode('ascii', 'ignore'))) + return rc, out, err + + +def assert_python_ok(*args, **env_vars): + """ + Assert that running the interpreter with `args` and optional environment + variables `env_vars` is ok and return a (return code, stdout, stderr) tuple. + """ + return _assert_python(True, *args, **env_vars) + + +def strip_python_stderr(stderr): + """Strip the stderr of a Python process from potential debug output + emitted by the interpreter. + + This will typically be run on the result of the communicate() method + of a subprocess.Popen object. + """ + stderr = re.sub(r"\[\d+ refs\]\r?\n?$".encode(), "".encode(), stderr).strip() + return stderr + + +@contextlib.contextmanager +def captured_stderr(): + """Return a context manager used by captured_stdout/stdin/stderr + that temporarily replaces the sys stream *stream_name* with a StringIO.""" + logging_stream = StringIO() + handler = logging.StreamHandler(logging_stream) + logging.root.addHandler(handler) + + try: + yield logging_stream + finally: + logging.root.removeHandler(handler) + + +def create_future(state=PENDING, exception=None, result=None): + f = Future() + f._state = state + f._exception = exception + f._result = result + return f + + +PENDING_FUTURE = create_future(state=PENDING) +RUNNING_FUTURE = create_future(state=RUNNING) +CANCELLED_FUTURE = create_future(state=CANCELLED) +CANCELLED_AND_NOTIFIED_FUTURE = create_future(state=CANCELLED_AND_NOTIFIED) +EXCEPTION_FUTURE = create_future(state=FINISHED, exception=IOError()) +SUCCESSFUL_FUTURE = create_future(state=FINISHED, result=42) + + +def mul(x, y): + return x * y + + +def sleep_and_raise(t): + time.sleep(t) + raise Exception('this is an exception') + +def sleep_and_print(t, msg): + time.sleep(t) + print(msg) + sys.stdout.flush() + + +class ExecutorMixin: + worker_count = 5 + + def setUp(self): + self.t1 = time.time() + try: + self.executor = self.executor_type(max_workers=self.worker_count) + except NotImplementedError: + e = sys.exc_info()[1] + self.skipTest(str(e)) + self._prime_executor() + + def tearDown(self): + self.executor.shutdown(wait=True) + dt = time.time() - self.t1 + if test_support.verbose: + print("%.2fs" % dt) + self.assertLess(dt, 60, "synchronization issue: test lasted too long") + + def _prime_executor(self): + # Make sure that the executor is ready to do work before running the + # tests. This should reduce the probability of timeouts in the tests. + futures = [self.executor.submit(time.sleep, 0.1) + for _ in range(self.worker_count)] + + for f in futures: + f.result() + + +class ThreadPoolMixin(ExecutorMixin): + executor_type = futures.ThreadPoolExecutor + + +class ProcessPoolMixin(ExecutorMixin): + executor_type = futures.ProcessPoolExecutor + + +class ExecutorShutdownTest(unittest.TestCase): + def test_run_after_shutdown(self): + self.executor.shutdown() + self.assertRaises(RuntimeError, + self.executor.submit, + pow, 2, 5) + + def test_interpreter_shutdown(self): + # Test the atexit hook for shutdown of worker threads and processes + rc, out, err = assert_python_ok('-c', """if 1: + from concurrent.futures import %s + from time import sleep + from test_futures import sleep_and_print + t = %s(5) + t.submit(sleep_and_print, 1.0, "apple") + """ % (self.executor_type.__name__, self.executor_type.__name__)) + # Errors in atexit hooks don't change the process exit code, check + # stderr manually. + self.assertFalse(err) + self.assertEqual(out.strip(), "apple".encode()) + + def test_hang_issue12364(self): + fs = [self.executor.submit(time.sleep, 0.1) for _ in range(50)] + self.executor.shutdown() + for f in fs: + f.result() + + +class ThreadPoolShutdownTest(ThreadPoolMixin, ExecutorShutdownTest): + def _prime_executor(self): + pass + + def test_threads_terminate(self): + self.executor.submit(mul, 21, 2) + self.executor.submit(mul, 6, 7) + self.executor.submit(mul, 3, 14) + self.assertEqual(len(self.executor._threads), 3) + self.executor.shutdown() + for t in self.executor._threads: + t.join() + + def test_context_manager_shutdown(self): + with futures.ThreadPoolExecutor(max_workers=5) as e: + executor = e + self.assertEqual(list(e.map(abs, range(-5, 5))), + [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]) + + for t in executor._threads: + t.join() + + def test_del_shutdown(self): + executor = futures.ThreadPoolExecutor(max_workers=5) + executor.map(abs, range(-5, 5)) + threads = executor._threads + del executor + + for t in threads: + t.join() + + +class ProcessPoolShutdownTest(ProcessPoolMixin, ExecutorShutdownTest): + def _prime_executor(self): + pass + + def test_processes_terminate(self): + self.executor.submit(mul, 21, 2) + self.executor.submit(mul, 6, 7) + self.executor.submit(mul, 3, 14) + self.assertEqual(len(self.executor._processes), 5) + processes = self.executor._processes + self.executor.shutdown() + + for p in processes: + p.join() + + def test_context_manager_shutdown(self): + with futures.ProcessPoolExecutor(max_workers=5) as e: + processes = e._processes + self.assertEqual(list(e.map(abs, range(-5, 5))), + [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]) + + for p in processes: + p.join() + + def test_del_shutdown(self): + executor = futures.ProcessPoolExecutor(max_workers=5) + list(executor.map(abs, range(-5, 5))) + queue_management_thread = executor._queue_management_thread + processes = executor._processes + del executor + + queue_management_thread.join() + for p in processes: + p.join() + + +class WaitTests(unittest.TestCase): + + def test_first_completed(self): + future1 = self.executor.submit(mul, 21, 2) + future2 = self.executor.submit(time.sleep, 1.5) + + done, not_done = futures.wait( + [CANCELLED_FUTURE, future1, future2], + return_when=futures.FIRST_COMPLETED) + + self.assertEqual(set([future1]), done) + self.assertEqual(set([CANCELLED_FUTURE, future2]), not_done) + + def test_first_completed_some_already_completed(self): + future1 = self.executor.submit(time.sleep, 1.5) + + finished, pending = futures.wait( + [CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE, future1], + return_when=futures.FIRST_COMPLETED) + + self.assertEqual( + set([CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE]), + finished) + self.assertEqual(set([future1]), pending) + + def test_first_exception(self): + future1 = self.executor.submit(mul, 2, 21) + future2 = self.executor.submit(sleep_and_raise, 1.5) + future3 = self.executor.submit(time.sleep, 3) + + finished, pending = futures.wait( + [future1, future2, future3], + return_when=futures.FIRST_EXCEPTION) + + self.assertEqual(set([future1, future2]), finished) + self.assertEqual(set([future3]), pending) + + def test_first_exception_some_already_complete(self): + future1 = self.executor.submit(divmod, 21, 0) + future2 = self.executor.submit(time.sleep, 1.5) + + finished, pending = futures.wait( + [SUCCESSFUL_FUTURE, + CANCELLED_FUTURE, + CANCELLED_AND_NOTIFIED_FUTURE, + future1, future2], + return_when=futures.FIRST_EXCEPTION) + + self.assertEqual(set([SUCCESSFUL_FUTURE, + CANCELLED_AND_NOTIFIED_FUTURE, + future1]), finished) + self.assertEqual(set([CANCELLED_FUTURE, future2]), pending) + + def test_first_exception_one_already_failed(self): + future1 = self.executor.submit(time.sleep, 2) + + finished, pending = futures.wait( + [EXCEPTION_FUTURE, future1], + return_when=futures.FIRST_EXCEPTION) + + self.assertEqual(set([EXCEPTION_FUTURE]), finished) + self.assertEqual(set([future1]), pending) + + def test_all_completed(self): + future1 = self.executor.submit(divmod, 2, 0) + future2 = self.executor.submit(mul, 2, 21) + + finished, pending = futures.wait( + [SUCCESSFUL_FUTURE, + CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + future1, + future2], + return_when=futures.ALL_COMPLETED) + + self.assertEqual(set([SUCCESSFUL_FUTURE, + CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + future1, + future2]), finished) + self.assertEqual(set(), pending) + + def test_timeout(self): + future1 = self.executor.submit(mul, 6, 7) + future2 = self.executor.submit(time.sleep, 3) + + finished, pending = futures.wait( + [CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE, + future1, future2], + timeout=1.5, + return_when=futures.ALL_COMPLETED) + + self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE, + future1]), finished) + self.assertEqual(set([future2]), pending) + + +class ThreadPoolWaitTests(ThreadPoolMixin, WaitTests): + + def test_pending_calls_race(self): + # Issue #14406: multi-threaded race condition when waiting on all + # futures. + event = threading.Event() + def future_func(): + event.wait() + oldswitchinterval = sys.getcheckinterval() + sys.setcheckinterval(1) + try: + fs = set(self.executor.submit(future_func) for i in range(100)) + event.set() + futures.wait(fs, return_when=futures.ALL_COMPLETED) + finally: + sys.setcheckinterval(oldswitchinterval) + + +class ProcessPoolWaitTests(ProcessPoolMixin, WaitTests): + pass + + +class AsCompletedTests(unittest.TestCase): + # TODO(brian@sweetapp.com): Should have a test with a non-zero timeout. + def test_no_timeout(self): + future1 = self.executor.submit(mul, 2, 21) + future2 = self.executor.submit(mul, 7, 6) + + completed = set(futures.as_completed( + [CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE, + future1, future2])) + self.assertEqual(set( + [CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE, + future1, future2]), + completed) + + def test_zero_timeout(self): + future1 = self.executor.submit(time.sleep, 2) + completed_futures = set() + try: + for future in futures.as_completed( + [CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE, + future1], + timeout=0): + completed_futures.add(future) + except futures.TimeoutError: + pass + + self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE, + EXCEPTION_FUTURE, + SUCCESSFUL_FUTURE]), + completed_futures) + + +class ThreadPoolAsCompletedTests(ThreadPoolMixin, AsCompletedTests): + pass + + +class ProcessPoolAsCompletedTests(ProcessPoolMixin, AsCompletedTests): + pass + + +class ExecutorTest(unittest.TestCase): + # Executor.shutdown() and context manager usage is tested by + # ExecutorShutdownTest. + def test_submit(self): + future = self.executor.submit(pow, 2, 8) + self.assertEqual(256, future.result()) + + def test_submit_keyword(self): + future = self.executor.submit(mul, 2, y=8) + self.assertEqual(16, future.result()) + + def test_map(self): + self.assertEqual( + list(self.executor.map(pow, range(10), range(10))), + list(map(pow, range(10), range(10)))) + + def test_map_exception(self): + i = self.executor.map(divmod, [1, 1, 1, 1], [2, 3, 0, 5]) + self.assertEqual(next(i), (0, 1)) + self.assertEqual(next(i), (0, 1)) + self.assertRaises(ZeroDivisionError, next, i) + + def test_map_timeout(self): + results = [] + try: + for i in self.executor.map(time.sleep, + [0, 0, 3], + timeout=1.5): + results.append(i) + except futures.TimeoutError: + pass + else: + self.fail('expected TimeoutError') + + self.assertEqual([None, None], results) + + +class ThreadPoolExecutorTest(ThreadPoolMixin, ExecutorTest): + pass + + +class ProcessPoolExecutorTest(ProcessPoolMixin, ExecutorTest): + pass + + +class FutureTests(unittest.TestCase): + def test_done_callback_with_result(self): + callback_result = [None] + def fn(callback_future): + callback_result[0] = callback_future.result() + + f = Future() + f.add_done_callback(fn) + f.set_result(5) + self.assertEqual(5, callback_result[0]) + + def test_done_callback_with_exception(self): + callback_exception = [None] + def fn(callback_future): + callback_exception[0] = callback_future.exception() + + f = Future() + f.add_done_callback(fn) + f.set_exception(Exception('test')) + self.assertEqual(('test',), callback_exception[0].args) + + def test_done_callback_with_cancel(self): + was_cancelled = [None] + def fn(callback_future): + was_cancelled[0] = callback_future.cancelled() + + f = Future() + f.add_done_callback(fn) + self.assertTrue(f.cancel()) + self.assertTrue(was_cancelled[0]) + + def test_done_callback_raises(self): + with captured_stderr() as stderr: + raising_was_called = [False] + fn_was_called = [False] + + def raising_fn(callback_future): + raising_was_called[0] = True + raise Exception('doh!') + + def fn(callback_future): + fn_was_called[0] = True + + f = Future() + f.add_done_callback(raising_fn) + f.add_done_callback(fn) + f.set_result(5) + self.assertTrue(raising_was_called) + self.assertTrue(fn_was_called) + self.assertIn('Exception: doh!', stderr.getvalue()) + + def test_done_callback_already_successful(self): + callback_result = [None] + def fn(callback_future): + callback_result[0] = callback_future.result() + + f = Future() + f.set_result(5) + f.add_done_callback(fn) + self.assertEqual(5, callback_result[0]) + + def test_done_callback_already_failed(self): + callback_exception = [None] + def fn(callback_future): + callback_exception[0] = callback_future.exception() + + f = Future() + f.set_exception(Exception('test')) + f.add_done_callback(fn) + self.assertEqual(('test',), callback_exception[0].args) + + def test_done_callback_already_cancelled(self): + was_cancelled = [None] + def fn(callback_future): + was_cancelled[0] = callback_future.cancelled() + + f = Future() + self.assertTrue(f.cancel()) + f.add_done_callback(fn) + self.assertTrue(was_cancelled[0]) + + def test_repr(self): + self.assertRegexpMatches(repr(PENDING_FUTURE), + '<Future at 0x[0-9a-f]+ state=pending>') + self.assertRegexpMatches(repr(RUNNING_FUTURE), + '<Future at 0x[0-9a-f]+ state=running>') + self.assertRegexpMatches(repr(CANCELLED_FUTURE), + '<Future at 0x[0-9a-f]+ state=cancelled>') + self.assertRegexpMatches(repr(CANCELLED_AND_NOTIFIED_FUTURE), + '<Future at 0x[0-9a-f]+ state=cancelled>') + self.assertRegexpMatches( + repr(EXCEPTION_FUTURE), + '<Future at 0x[0-9a-f]+ state=finished raised IOError>') + self.assertRegexpMatches( + repr(SUCCESSFUL_FUTURE), + '<Future at 0x[0-9a-f]+ state=finished returned int>') + + def test_cancel(self): + f1 = create_future(state=PENDING) + f2 = create_future(state=RUNNING) + f3 = create_future(state=CANCELLED) + f4 = create_future(state=CANCELLED_AND_NOTIFIED) + f5 = create_future(state=FINISHED, exception=IOError()) + f6 = create_future(state=FINISHED, result=5) + + self.assertTrue(f1.cancel()) + self.assertEqual(f1._state, CANCELLED) + + self.assertFalse(f2.cancel()) + self.assertEqual(f2._state, RUNNING) + + self.assertTrue(f3.cancel()) + self.assertEqual(f3._state, CANCELLED) + + self.assertTrue(f4.cancel()) + self.assertEqual(f4._state, CANCELLED_AND_NOTIFIED) + + self.assertFalse(f5.cancel()) + self.assertEqual(f5._state, FINISHED) + + self.assertFalse(f6.cancel()) + self.assertEqual(f6._state, FINISHED) + + def test_cancelled(self): + self.assertFalse(PENDING_FUTURE.cancelled()) + self.assertFalse(RUNNING_FUTURE.cancelled()) + self.assertTrue(CANCELLED_FUTURE.cancelled()) + self.assertTrue(CANCELLED_AND_NOTIFIED_FUTURE.cancelled()) + self.assertFalse(EXCEPTION_FUTURE.cancelled()) + self.assertFalse(SUCCESSFUL_FUTURE.cancelled()) + + def test_done(self): + self.assertFalse(PENDING_FUTURE.done()) + self.assertFalse(RUNNING_FUTURE.done()) + self.assertTrue(CANCELLED_FUTURE.done()) + self.assertTrue(CANCELLED_AND_NOTIFIED_FUTURE.done()) + self.assertTrue(EXCEPTION_FUTURE.done()) + self.assertTrue(SUCCESSFUL_FUTURE.done()) + + def test_running(self): + self.assertFalse(PENDING_FUTURE.running()) + self.assertTrue(RUNNING_FUTURE.running()) + self.assertFalse(CANCELLED_FUTURE.running()) + self.assertFalse(CANCELLED_AND_NOTIFIED_FUTURE.running()) + self.assertFalse(EXCEPTION_FUTURE.running()) + self.assertFalse(SUCCESSFUL_FUTURE.running()) + + def test_result_with_timeout(self): + self.assertRaises(futures.TimeoutError, + PENDING_FUTURE.result, timeout=0) + self.assertRaises(futures.TimeoutError, + RUNNING_FUTURE.result, timeout=0) + self.assertRaises(futures.CancelledError, + CANCELLED_FUTURE.result, timeout=0) + self.assertRaises(futures.CancelledError, + CANCELLED_AND_NOTIFIED_FUTURE.result, timeout=0) + self.assertRaises(IOError, EXCEPTION_FUTURE.result, timeout=0) + self.assertEqual(SUCCESSFUL_FUTURE.result(timeout=0), 42) + + def test_result_with_success(self): + # TODO(brian@sweetapp.com): This test is timing dependant. + def notification(): + # Wait until the main thread is waiting for the result. + time.sleep(1) + f1.set_result(42) + + f1 = create_future(state=PENDING) + t = threading.Thread(target=notification) + t.start() + + self.assertEqual(f1.result(timeout=5), 42) + + def test_result_with_cancel(self): + # TODO(brian@sweetapp.com): This test is timing dependant. + def notification(): + # Wait until the main thread is waiting for the result. + time.sleep(1) + f1.cancel() + + f1 = create_future(state=PENDING) + t = threading.Thread(target=notification) + t.start() + + self.assertRaises(futures.CancelledError, f1.result, timeout=5) + + def test_exception_with_timeout(self): + self.assertRaises(futures.TimeoutError, + PENDING_FUTURE.exception, timeout=0) + self.assertRaises(futures.TimeoutError, + RUNNING_FUTURE.exception, timeout=0) + self.assertRaises(futures.CancelledError, + CANCELLED_FUTURE.exception, timeout=0) + self.assertRaises(futures.CancelledError, + CANCELLED_AND_NOTIFIED_FUTURE.exception, timeout=0) + self.assertTrue(isinstance(EXCEPTION_FUTURE.exception(timeout=0), + IOError)) + self.assertEqual(SUCCESSFUL_FUTURE.exception(timeout=0), None) + + def test_exception_with_success(self): + def notification(): + # Wait until the main thread is waiting for the exception. + time.sleep(1) + with f1._condition: + f1._state = FINISHED + f1._exception = IOError() + f1._condition.notify_all() + + f1 = create_future(state=PENDING) + t = threading.Thread(target=notification) + t.start() + + self.assertTrue(isinstance(f1.exception(timeout=5), IOError)) + +@reap_threads +def test_main(): + try: + test_support.run_unittest(ProcessPoolExecutorTest, + ThreadPoolExecutorTest, + ProcessPoolWaitTests, + ThreadPoolWaitTests, + ProcessPoolAsCompletedTests, + ThreadPoolAsCompletedTests, + FutureTests, + ProcessPoolShutdownTest, + ThreadPoolShutdownTest) + finally: + test_support.reap_children() + +if __name__ == "__main__": + test_main() diff --git a/vim/bundle/YouCompleteMe/third_party/pythonfutures/tox.ini b/vim/bundle/YouCompleteMe/third_party/pythonfutures/tox.ini new file mode 100755 index 0000000..c1ff2f1 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/pythonfutures/tox.ini @@ -0,0 +1,8 @@ +[tox] +envlist = py26,py27,py31 + +[testenv] +commands={envpython} test_futures.py [] + +[testenv:py26] +deps=unittest2 diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/.gitignore b/vim/bundle/YouCompleteMe/third_party/requests-futures/.gitignore new file mode 100644 index 0000000..0f0a128 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/.gitignore @@ -0,0 +1,4 @@ +build/ +dist/ +*.egg-info/ +*.pyc diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/.travis.yml b/vim/bundle/YouCompleteMe/third_party/requests-futures/.travis.yml new file mode 100644 index 0000000..ada4746 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/.travis.yml @@ -0,0 +1,11 @@ +language: python +python: + - 2.7 + - 3.2 + - 3.3 +env: HTTPBIN_URL=http://httpbin.org/ +script: python test_requests_futures.py +install: pip install -r requirements-python-2.7.txt +notifications: + email: + - rwmcfa1@neces.com diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/LICENSE b/vim/bundle/YouCompleteMe/third_party/requests-futures/LICENSE new file mode 100644 index 0000000..2a2a0c6 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/LICENSE @@ -0,0 +1,13 @@ +Copyright 2013 Ross McFarland + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/MANIFEST.in b/vim/bundle/YouCompleteMe/third_party/requests-futures/MANIFEST.in new file mode 100644 index 0000000..b9d5079 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/MANIFEST.in @@ -0,0 +1 @@ +include README.rst LICENSE test_requests_futures.py requirements-python-2.7.txt requirements-python-3.2.txt diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/README.rst b/vim/bundle/YouCompleteMe/third_party/requests-futures/README.rst new file mode 100644 index 0000000..5a25b22 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/README.rst @@ -0,0 +1,110 @@ +Asynchronous Python HTTP Requests for Humans +============================================ + +.. image:: https://travis-ci.org/ross/requests-futures.png?branch=master + :target: https://travis-ci.org/ross/requests-futures + +Small add-on for the python requests_ http library. Makes use of python 3.2's +`concurrent.futures`_ or the backport_ for prior versions of python. + +The additional API and changes are minimal and strives to avoid surprises. + +The following synchronous code: + +.. code-block:: python + + from requests import Session + + session = Session() + # first requests starts and blocks until finished + response_one = session.get('http://httpbin.org/get') + # second request starts once first is finished + response_two = session.get('http://httpbin.org/get?foo=bar') + # both requests are complete + print('response one status: {0}'.format(response_one.status_code)) + print(response_one.content) + print('response two status: {0}'.format(response_two.status_code)) + print(response_two.content) + +Can be translated to make use of futures, and thus be asynchronous by creating +a FuturesSession and catching the returned Future in place of Response. The +Response can be retrieved by calling the result method on the Future: + +.. code-block:: python + + from requests_futures.sessions import FuturesSession + + session = FuturesSession() + # first request is started in background + future_one = session.get('http://httpbin.org/get') + # second requests is started immediately + future_two = session.get('http://httpbin.org/get?foo=bar') + # wait for the first request to complete, if it hasn't already + response_one = future_one.result() + print('response one status: {0}'.format(response_one.status_code)) + print(response_one.content) + # wait for the second request to complete, if it hasn't already + response_two = future_two.result() + print('response two status: {0}'.format(response_two.status_code)) + print(response_two.content) + +By default a ThreadPoolExecutor is created with 2 workers. If you would like to +adjust that value or share a executor across multiple sessions you can provide +one to the FuturesSession constructor. + +.. code-block:: python + + from concurrent.futures import ThreadPoolExecutor + from requests_futures.sessions import FuturesSession + + session = FuturesSession(executor=ThreadPoolExecutor(max_workers=10)) + # ... + +As a shortcut in case of just increasing workers number you can pass +`max_workers` straight to the `FuturesSession` constructor: + +.. code-block:: python + + from requests_futures.sessions import FuturesSession + session = FuturesSession(max_workers=10) + +That's it. The api of requests.Session is preserved without any modifications +beyond returning a Future rather than Response. As with all futures exceptions +are shifted (thrown) to the future.result() call so try/except blocks should be +moved there. + +Working in the Background +========================= + +There is one additional parameter to the various request functions, +background_callback, which allows you to work with the Response objects in the +background thread. This can be useful for shifting work out of the foreground, +for a simple example take json parsing. + +.. code-block:: python + + from pprint import pprint + from requests_futures.sessions import FuturesSession + + session = FuturesSession() + + def bg_cb(sess, resp): + # parse the json storing the result on the response object + resp.data = resp.json() + + future = session.get('http://httpbin.org/get', background_callback=bg_cb) + # do some other stuff, send some more requests while this one works + response = future.result() + print('response status {0}'.format(response.status_code)) + # data will have been attached to the response object in the background + pprint(response.data) + + +Installation +============ + + pip install requests-futures + +.. _`requests`: https://github.com/kennethreitz/requests +.. _`concurrent.futures`: http://docs.python.org/dev/library/concurrent.futures.html +.. _backport: https://pypi.python.org/pypi/futures diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/__init__.py b/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/__init__.py new file mode 100644 index 0000000..af7acae --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/__init__.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +# Requests Futures + +""" +async requests HTTP library +~~~~~~~~~~~~~~~~~~~~~ + + +""" + +__title__ = 'requests-futures' +__version__ = '0.9.4' +__build__ = 0x000000 +__author__ = 'Ross McFarland' +__license__ = 'Apache 2.0' +__copyright__ = 'Copyright 2013 Ross McFarland' + +# Set default logging handler to avoid "No handler found" warnings. +import logging +try: # Python 2.7+ + from logging import NullHandler +except ImportError: + class NullHandler(logging.Handler): + def emit(self, record): + pass + +logging.getLogger(__name__).addHandler(NullHandler()) diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/sessions.py b/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/sessions.py new file mode 100644 index 0000000..ad2af1b --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/requests_futures/sessions.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +""" +requests_futures +~~~~~~~~~~~~~~~~ + +This module provides a small add-on for the requests http library. It makes use +of python 3.3's concurrent.futures or the futures backport for previous +releases of python. + + from requests_futures import FuturesSession + + session = FuturesSession() + # request is run in the background + future = session.get('http://httpbin.org/get') + # ... do other stuff ... + # wait for the request to complete, if it hasn't already + response = future.result() + print('response status: {0}'.format(response.status_code)) + print(response.content) + +""" + +from concurrent.futures import ThreadPoolExecutor +from requests import Session +from requests.adapters import DEFAULT_POOLSIZE, HTTPAdapter + +class FuturesSession(Session): + + def __init__(self, executor=None, max_workers=2, *args, **kwargs): + """Creates a FuturesSession + + Notes + ~~~~~ + + * ProcessPoolExecutor is not supported b/c Response objects are + not picklable. + + * If you provide both `executor` and `max_workers`, the latter is + ignored and provided executor is used as is. + """ + super(FuturesSession, self).__init__(*args, **kwargs) + if executor is None: + executor = ThreadPoolExecutor(max_workers=max_workers) + # set connection pool size equal to max_workers if needed + if max_workers > DEFAULT_POOLSIZE: + adapter_kwargs = dict(pool_connections=max_workers, + pool_maxsize=max_workers) + self.mount('https://', HTTPAdapter(**adapter_kwargs)) + self.mount('http://', HTTPAdapter(**adapter_kwargs)) + + self.executor = executor + + def request(self, *args, **kwargs): + """Maintains the existing api for Session.request. + + Used by all of the higher level methods, e.g. Session.get. + + The background_callback param allows you to do some processing on the + response in the background, e.g. call resp.json() so that json parsing + happens in the background thread. + """ + func = sup = super(FuturesSession, self).request + + background_callback = kwargs.pop('background_callback', None) + if background_callback: + def wrap(*args_, **kwargs_): + resp = sup(*args_, **kwargs_) + background_callback(self, resp) + return resp + + func = wrap + + return self.executor.submit(func, *args, **kwargs) diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-2.7.txt b/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-2.7.txt new file mode 100644 index 0000000..e70089a --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-2.7.txt @@ -0,0 +1,2 @@ +futures +requests>=1.2.0 diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-3.2.txt b/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-3.2.txt new file mode 100644 index 0000000..f250822 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/requirements-python-3.2.txt @@ -0,0 +1 @@ +requests>=1.2.0 diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/setup.py b/vim/bundle/YouCompleteMe/third_party/requests-futures/setup.py new file mode 100644 index 0000000..3f100d7 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/setup.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +import os +import sys + +import requests_futures + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +if sys.argv[-1] == 'publish': + os.system('python setup.py sdist upload') + sys.exit() + +packages = [ + 'requests_futures', +] + +requires = [ + 'requests>=1.2.0' +] + +if sys.version_info < (3, 2): + requires.append('futures>=2.1.3') + +setup( + name='requests-futures', + version=requests_futures.__version__, + description='Asynchronous Python HTTP for Humans.', + long_description=open('README.rst').read(), + author='Ross McFarland', + author_email='rwmcfa1@neces.com', + packages=packages, + package_dir={'requests_futures': 'requests_futures'}, + package_data={'requests_futures': ['LICENSE', 'README.rst']}, + include_package_data=True, + install_requires=requires, + license='Apache License v2', + url='https://github.com/ross/requests-futures', + zip_safe=False, + classifiers=( + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Natural Language :: English', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.1', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + ), +) diff --git a/vim/bundle/YouCompleteMe/third_party/requests-futures/test_requests_futures.py b/vim/bundle/YouCompleteMe/third_party/requests-futures/test_requests_futures.py new file mode 100644 index 0000000..b41836e --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/requests-futures/test_requests_futures.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""Tests for Requests.""" + +from concurrent.futures import Future +from requests import Response +from os import environ +from requests_futures.sessions import FuturesSession +from unittest import TestCase, main + +HTTPBIN = environ.get('HTTPBIN_URL', 'http://httpbin.org/') + +def httpbin(*suffix): + """Returns url for HTTPBIN resource.""" + return HTTPBIN + '/'.join(suffix) + + +class RequestsTestCase(TestCase): + + def test_futures_session(self): + # basic futures get + sess = FuturesSession() + future = sess.get(httpbin('get')) + self.assertIsInstance(future, Future) + resp = future.result() + self.assertIsInstance(resp, Response) + self.assertEqual(200, resp.status_code) + + # non-200, 404 + future = sess.get(httpbin('status/404')) + resp = future.result() + self.assertEqual(404, resp.status_code) + + def cb(s, r): + self.assertIsInstance(s, FuturesSession) + self.assertIsInstance(r, Response) + # add the parsed json data to the response + r.data = r.json() + + future = sess.get(httpbin('get'), background_callback=cb) + # this should block until complete + resp = future.result() + self.assertEqual(200, resp.status_code) + # make sure the callback was invoked + self.assertTrue(hasattr(resp, 'data')) + + def rasing_cb(s, r): + raise Exception('boom') + + future = sess.get(httpbin('get'), background_callback=rasing_cb) + with self.assertRaises(Exception) as cm: + resp = future.result() + self.assertEqual('boom', cm.exception.args[0]) + + def test_max_workers(self): + """ Tests the `max_workers` shortcut. """ + from concurrent.futures import ThreadPoolExecutor + session = FuturesSession() + self.assertEqual(session.executor._max_workers, 2) + session = FuturesSession(max_workers=5) + self.assertEqual(session.executor._max_workers, 5) + session = FuturesSession(executor=ThreadPoolExecutor(max_workers=10)) + self.assertEqual(session.executor._max_workers, 10) + session = FuturesSession(executor=ThreadPoolExecutor(max_workers=10), + max_workers=5) + self.assertEqual(session.executor._max_workers, 10) + + def test_redirect(self): + """ Tests for the ability to cleanly handle redirects. """ + sess = FuturesSession() + future = sess.get(httpbin('redirect-to?url=get')) + self.assertIsInstance(future, Future) + resp = future.result() + self.assertIsInstance(resp, Response) + self.assertEqual(200, resp.status_code) + + future = sess.get(httpbin('redirect-to?url=status/404')) + resp = future.result() + self.assertEqual(404, resp.status_code) + + +if __name__ == '__main__': + main() diff --git a/vim/bundle/YouCompleteMe/third_party/retries/retries.py b/vim/bundle/YouCompleteMe/third_party/retries/retries.py new file mode 100644 index 0000000..da7fa48 --- /dev/null +++ b/vim/bundle/YouCompleteMe/third_party/retries/retries.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2012 by Jeff Laughlin Consulting LLC +# +# 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. + + +import sys +from time import sleep + +# Source: https://gist.github.com/n1ywb/2570004 + +def example_exc_handler(tries_remaining, exception, delay): + """Example exception handler; prints a warning to stderr. + + tries_remaining: The number of tries remaining. + exception: The exception instance which was raised. + """ + print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s seconds" % (exception, tries_remaining, delay) + + +def retries(max_tries, delay=1, backoff=2, exceptions=(Exception,), hook=None): + """Function decorator implementing retrying logic. + + delay: Sleep this many seconds * backoff * try number after failure + backoff: Multiply delay by this factor after each failure + exceptions: A tuple of exception classes; default (Exception,) + hook: A function with the signature myhook(tries_remaining, exception); + default None + + The decorator will call the function up to max_tries times if it raises + an exception. + + By default it catches instances of the Exception class and subclasses. + This will recover after all but the most fatal errors. You may specify a + custom tuple of exception classes with the 'exceptions' argument; the + function will only be retried if it raises one of the specified + exceptions. + + Additionally you may specify a hook function which will be called prior + to retrying with the number of remaining tries and the exception instance; + see given example. This is primarily intended to give the opportunity to + log the failure. Hook is not called after failure if no retries remain. + """ + def dec(func): + def f2(*args, **kwargs): + mydelay = delay + tries = reversed(range(max_tries)) + for tries_remaining in tries: + try: + return func(*args, **kwargs) + except exceptions as e: + if tries_remaining > 0: + if hook is not None: + hook(tries_remaining, e, mydelay) + sleep(mydelay) + mydelay = mydelay * backoff + else: + raise + else: + break + return f2 + return dec diff --git a/vim/bundle/YouCompleteMe/tox.ini b/vim/bundle/YouCompleteMe/tox.ini new file mode 100644 index 0000000..70d6d70 --- /dev/null +++ b/vim/bundle/YouCompleteMe/tox.ini @@ -0,0 +1,4 @@ +[flake8] +ignore = E111,E114,E121,E125,E126,E127,E128,E129,E131,E133,E201,E202,E203,E211,E221,E222,E241,E251,E261,E303,E402,W503 +max-complexity = 10 +max-line-length = 80 |