pax_global_header00006660000000000000000000000064122756756540014535gustar00rootroot0000000000000052 comment=a662c816eeeb1c7dc104654ea2d2cc3815362fc0 vim-youcompleteme-0+20140207+git18be5c2/000077500000000000000000000000001227567565400173625ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/CONTRIBUTING.md000066400000000000000000000135171227567565400216220ustar00rootroot00000000000000Writing 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.sh` 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_use_vim_stdout = 1 let g:ycm_server_log_level = 'debug' ``` Then start gvim/macvim (not console vim) from the console. As you use Vim, you'll see the `ycmd` debug output stream in the console. Attach that to you issue. 3. **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. 4. **Include your OS and OS version.** 5. **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. **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. 4. **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?_ 5. **Sign the Google [Contributor License Agreement][cla]** (you can sign online at the bottom of that page). You _must_ sign this form, otherwise we cannot merge in your changes. **_Always_ mention in the pull request that you've signed it**, even if you signed it for a previous pull request (you only need to sign the CLA once). [build-bots]: https://travis-ci.org/Valloric/YouCompleteMe [ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users [cla]: https://developers.google.com/open-source/cla/individual vim-youcompleteme-0+20140207+git18be5c2/COPYING.txt000066400000000000000000001045131227567565400212370ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . vim-youcompleteme-0+20140207+git18be5c2/README.md000066400000000000000000002156041227567565400206510ustar00rootroot00000000000000YouCompleteMe: a code-completion engine for Vim =============================================== [![Build Status](https://travis-ci.org/Valloric/YouCompleteMe.png?branch=travis)](https://travis-ci.org/Valloric/YouCompleteMe) 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 semantic, [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, an [OmniSharp][]-based completion engine for C# 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 YCM also provides semantic go-to-definition/declaration commands for C-family languages & Python. Expect more IDE features powered by the various YCM semantic engines in the future. You'll also find that YCM has filepath completers (try typing `./` in a file) and a completer that integrates with [UltiSnips][]. Mac OS X super-quick installation --------------------------------- 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_support_libs library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. It's recommended that you have the latest Xcode installed along with the latest Command Line Tools (that you install from within Xcode). 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.sh --clang-completer Compiling YCM **without** semantic support for C-family languages: cd ~/.vim/bundle/YouCompleteMe ./install.sh If you want semantic C# support, you should add `--omnisharp-completer` to the install script as well. 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 super-quick installation ----------------------------------------- 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.584 with python2 support. At the time of writing, the version of Vim shipping with Ubuntu 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_support_libs 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`. Compiling YCM **with** semantic support for C-family languages: cd ~/.vim/bundle/YouCompleteMe ./install.sh --clang-completer Compiling YCM **without** semantic support for C-family languages: cd ~/.vim/bundle/YouCompleteMe ./install.sh If you want semantic C# support, you should add `--omnisharp-completer` to the install script as well. 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 Installation -------------------- YCM has **no official support for Windows**, but that doesn't mean you can't get it to work there. See the [Windows Installation Guide][win-wiki] wiki page. Feel free to add to it. Full Installation Guide ----------------------- These are the steps necessary to get YCM working on a Unix OS like Linux or Mac OS X. My apologies to Windows users, but I don't have a guide for them. The code is platform agnostic, so if everything is configured correctly, YCM _should_ work on Windows without issues (but as of writing, it's untested on that platform). 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_support_libs 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.584 _and_ that it has support for python2 scripting**. Inside Vim, type `:version`. Look at the first two to three lines of output; it should say `Vi IMproved 7.3` and then below that, `Included patches: 1-X`, where X will be some number. That number needs to be 584 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.584+, type the following in Vim: `:echo has('python')`. The output should be 1. If it's 0, then get a version of Vim with Python support. 2. **Install YCM** with [Vundle][] (or [Pathogen][], but Vundle is a better idea). With Vundle, this would mean adding a `Bundle '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 neccessary.] **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.4 or higher, but can in theory work with any 3.2+ version as well. You can use the system libclang _only if you are sure it is version 3.3 or higher_, otherwise don't. Even if it is, I 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. 4. **Compile the `ycm_support_libs` libraries** that YCM needs. These libs are the C++ engines 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`. You also need to make sure you have Python headers installed. On a Debian-like Linux distro, this would be `sudo apt-get install python-dev`. On Mac they should already be present. 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 "Unix Makefiles" . ~/.vim/bundle/YouCompleteMe/cpp 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). With that in mind, run the following command in the `ycm_build` directory: cmake -G "Unix Makefiles" -DPATH_TO_LLVM_ROOT=~/ycm_temp/llvm_root_dir . ~/.vim/bundle/YouCompleteMe/cpp Now that makefiles have been generated, simply run: make ycm_support_libs 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. 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. Running the `make` command will also place the `libclang.[so|dylib]` in the `YouCompleteMe/python` folder for you if you compiled with clang support (it needs to be there for YCM to work). 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. 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 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 Engine Usage - 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 Engine Usage 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. 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. ### Python semantic completion YCM uses [Jedi][] to power its semantic completion for Python. This should "just work" without any configuration from the user. You do NOT need to install Jedi yourself; YCM uses it as a git subrepo. If you're installing YCM with Vundle (which is the recommended way) then Vundle will make sure that the subrepo is checked out when you do `:BundleInstall`. If you're installing YCM by hand, then you need to run `git submodule update --init --recursive` when you're checking out the YCM repository. That's it. But again, installing YCM with Vundle takes care of all of this for you. In the future expect to see features like go-to-definition for Python as well. ### C# semantic completion YCM uses [OmniSharp][] to provide semantic completion for C#. It's used as a git subrepo. If you're installing YCM with Vundle (which is the recommended way) then Vundle will make sure that the subrepo is checked out when you do `:BundleInstall`. If you're installing YCM by hand, then you need to run `git submodule update --init --recursive` when you're checking out the YCM repository. OmniSharp is written in C# and has to be compiled. The `install.sh` script takes care of this if you pass `--omnisharp-completer` as an argument. ### Semantic completion for other languages 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 -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 if you compiled YCM with Clang support. 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 :YcmForceCompileAndDiagnostics` 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 `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. Here's how you'd change the style for a group: ``` highlight YcmErrorLine guibg=#3f0000 ``` Commands -------- ### The `:YcmRestartServer` command If the `ycmd` completion server 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 :YcmForceCompileAndDiagnostics` 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. 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 `:YcmCompleter` command This command can be used to invoke 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 information about the commands you can call for the selected completer. See the _YcmCompleter subcommands_ section for more information on the available subcommands. YcmCompleter subcommands ------------------------ [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 jd :YcmCompleter GoToDefinitionElseDeclaration` maps the `jd` sequence to the longer subcommand invocation. The various `GoTo*` 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). ### The `GoToDeclaration` subcommand Looks up the symbol under the cursor and jumps to its declaration. Supported in filetypes: `c, cpp, objc, objcpp, python, cs` ### 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, python, cs` ### The `GoToDefinitionElseDeclaration` subcommand Looks 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. Supported in filetypes: `c, cpp, objc, objcpp, python, cs` ### 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` ### 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` ### The `RestartServer` subcommand Restarts the semantic-engine-as-localhost-server for those semantic engines that work as separate servers that YCM talks to. Supported in filetypes: `cs` 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: 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` 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 `` 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 \} ### 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: `{}` let g:ycm_filetype_specific_completion_to_disable = {} ### 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. 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][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:` 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 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: `[]` let g:ycm_extra_conf_vim_data = [] ### The `g:ycm_path_to_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. The YCM client running inside Vim always uses the Python interpreter that's embedded inside Vim. Default: `''` let g:ycm_path_to_python_interpreter = '' ### The `g:ycm_server_use_vim_stdout` option By default, the `ycmd` completion server writes logs to logfiles. When this option is set to `1`, the server writes logs to Vim's stdout (so you'll see them in the console). Default: `0` let g:ycm_server_use_vim_stdout = 0 ### The `g:ycm_server_keep_logfiles` option When this option is set to `1`, the `ycmd` completion server 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 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_csharp_server_port` option The port number (on `localhost`) on which the OmniSharp server should be started. Default: `2000` let g:ycm_csharp_server_port = 2000 ### 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_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 `` to this list. Default: `['', '']` let g:ycm_key_list_select_completion = ['', ''] ### 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 `` 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: `['', '']` let g:ycm_key_list_previous_completion = ['', ''] ### 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 `` to Vim when the user types `` so YCM will make sure that `` is used in the map command when you're editing in console Vim, and `` in GUI Vim. This means that you can just press `` 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: `` let g:ycm_key_invoke_completion = '' ### 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: `d` let g:ycm_key_detailed_diagnostics = '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. 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->`. Default: `[see next line]` let g:ycm_semantic_triggers = { \ 'c' : ['->', '.'], \ 'objc' : ['->', '.'], \ 'ocaml' : ['.', '#'], \ 'cpp,objcpp' : ['->', '.', '::'], \ 'perl' : ['->'], \ 'php' : ['->', '::'], \ 'cs,java,javascript,d,vim,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 requeried 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 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. 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 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 compile flags for the file if the file is a C-family language file and you have compiled in Clang support. ### 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 ``, `` or `` (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 ` 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 `` 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 ""` part, where `` 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.2 libclang. Some distros ship with a system `libclang.so` that identifies itself as 3.2 but is not; it was cut from the upstream sources before the official 3.2 release and some API changes (like the addition of the CompileCommands API) were added after their cut. So just go through the installation guide and make sure you are using a correct `libclang.so`. I recommend downloading prebuilt binaries from llvm.org. ### 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:` field in the tags output. 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 `` 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: 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 fitering. ### 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 back at original` and similar, then sadly there's no fix for those. Vim will emit them no matter how hard I try to silence them. You'll have to learn to ignore them. It's a shitty "solution", I know. There's an [outstanding patch for Vim that fixes this issue][status-mes], but at the time of writing Vim upstream hasn't yet merged it in. ### 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. ### 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 `` is too annoying (agreed, it is), we suggest mapping it to something more convenient. On a QWERTY keyboard, a good pick for the `` map is `inoremap jk `. 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. Compiling from `clang` the binary uses the correct default header search paths but compiling from `libclang.so` does not. The issue seems to impact some OS's more than others. It appears that OS X Mavericks in particular has problems with this. The current 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. 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 . The author's homepage is . Project Management ------------------ This open-source project is run by me, Strahinja Val Markovic. I also happen to work for Google and the code I write here is under Google copyright (for the sake of simplicity and other reasons). This does **NOT** mean that this is an official Google product (it isn't) or that Google has (or wants to have) anything to do with it. License ------- This software is licensed under the [GPL v3 license][gpl]. © 2013 Google Inc. [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/Valloric/youcompleteme/trend.png)](https://bitdeli.com/free "Bitdeli Badge") [Clang]: http://clang.llvm.org/ [vundle]: https://github.com/gmarik/vundle#about [pathogen]: https://github.com/tpope/vim-pathogen#pathogenvim [clang-download]: http://llvm.org/releases/download.html#3.3 [brew]: http://mxcl.github.com/homebrew/ [cmake-download]: http://www.cmake.org/cmake/resources/software.html [macvim]: http://code.google.com/p/macvim/#Download [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 [flags_example]: https://github.com/Valloric/YouCompleteMe/blob/master/cpp/ycm/.ycm_extra_conf.py [compdb]: http://clang.llvm.org/docs/JSONCompilationDatabase.html [subsequence]: http://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/YouCompleteMe/blob/master/python/ycm/completers/completer.py [win-wiki]: https://github.com/Valloric/YouCompleteMe/wiki/Windows-Installation-Guide [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/gmarik/vundle/issues/48 [ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users [omnisharp]: https://github.com/nosami/OmniSharpServer [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 vim-youcompleteme-0+20140207+git18be5c2/autoload/000077500000000000000000000000001227567565400211725ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/autoload/youcompleteme.vim000066400000000000000000000572151227567565400246100ustar00rootroot00000000000000" 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 . " 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( ':p:h' ), '\' ) let s:searched_and_results_found = 0 let s:omnifunc_mode = 0 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 = -1 let s:diagnostic_ui_filetypes = { \ 'cpp': 1, \ 'c': 1, \ 'objc': 1, \ 'objcpp': 1, \ } function! youcompleteme#Enable() " When vim is in diff mode, don't run if &diff return endif call s:SetUpBackwardsCompatibility() py import sys py import vim exe 'python sys.path.insert( 0, "' . s:script_folder_path . '/../python" )' py from ycm import utils py utils.AddThirdPartyFoldersToSysPath() py from ycm import base py base.LoadJsonDefaultsIntoVim() py from ycm import vimsupport py from ycm import user_options_store py user_options_store.SetAll( base.BuildServerConf() ) if !pyeval( 'base.CompatibleWithYcmCore()') echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: YCM support libs too old, PLEASE RECOMPILE" | \ echohl None return endif py from ycm.youcompleteme import YouCompleteMe py ycm_state = YouCompleteMe( user_options_store.GetAll() ) 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 set ut=2000 endif augroup youcompleteme autocmd! autocmd CursorMovedI * call s:OnCursorMovedInsertMode() autocmd CursorMoved * call s:OnCursorMovedNormalMode() " 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 BufRead,BufEnter,FileType * call s:OnBufferVisit() autocmd BufUnload * call s:OnBufferUnload( expand( ':p' ) ) autocmd CursorHold,CursorHoldI * call s:OnCursorHold() autocmd InsertLeave * call s:OnInsertLeave() autocmd InsertEnter * call s:OnInsertEnter() autocmd VimLeave * call s:OnVimLeave() augroup END " Calling this once solves the problem of BufRead/BufEnter not triggering for " the first loaded file. This should be the last command executed in this " function! call s:OnBufferVisit() 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 ' . key . \ ' pumvisible() ? "\" : "\' . key .'"' endfor for key in g:ycm_key_list_previous_completion " This selects the previous candidate for shift-tab (default) exe 'inoremap ' . key . \ ' pumvisible() ? "\" : "\' . key .'"' endfor if !empty( g:ycm_key_invoke_completion ) let invoke_key = g:ycm_key_invoke_completion " Inside the console, is passed as to Vim if invoke_key ==# '' && !has('gui_running') let invoke_key = '' endif " trigger omni completion, deselects the first completion " candidate that vim selects by default silent! exe 'inoremap ' . invoke_key . ' ' endif if !empty( g:ycm_key_detailed_diagnostics ) silent! exe 'nnoremap ' . g:ycm_key_detailed_diagnostics . \ ' :YcmShowDetailedDiagnostic' 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:DiagnosticUiSupportedForCurrentFiletype() return get( s:diagnostic_ui_filetypes, &filetype, 0 ) endfunction function! s:AllowedToCompleteInCurrentFile() if empty( &filetype ) || \ getbufvar( winbufnr( winnr() ), "&buftype" ) ==# 'nofile' || \ &filetype ==# 'qf' 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: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. " Patch: https://groups.google.com/forum/#!topic/vim_dev/WeBBjkXE8H8 " At the time of writing, the patch hasn't been merged into Vim upstream, but " will at some point. " TODO: Check the Vim version (when patch lands) instead of doing try-catch " here. try set shortmess+=c catch endtry 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() py ycm_state.OnVimLeave() 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() py ycm_state.OnBufferVisit() call s:OnFileReadyToParse() endfunction function! s:OnBufferUnload( deleted_buffer_file ) if !s:AllowedToCompleteInCurrentFile() || empty( a:deleted_buffer_file ) return endif py 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 done diagnostics before " reparsing the file again. If we sent the new parse request first, then " the response would always be pending when we called " UpdateDiagnosticNotifications. call s:UpdateDiagnosticNotifications() let buffer_changed = b:changedtick != b:ycm_changedtick.file_ready_to_parse if buffer_changed py 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' if 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 py 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 && !pyeval( 'base.LastEnteredCharIsIdentifierChar()') let s:omnifunc_mode = 0 endif endfunction function! s:OnCursorMovedNormalMode() if !s:AllowedToCompleteInCurrentFile() return endif call s:OnFileReadyToParse() py ycm_state.OnCursorMoved() endfunction function! s:OnInsertLeave() if !s:AllowedToCompleteInCurrentFile() return endif let s:omnifunc_mode = 0 call s:OnFileReadyToParse() py 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() 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() if s:moved_vertically_in_insert_mode let s:previous_num_chars_on_current_line = -1 return 0 endif let num_chars_in_current_cursor_line = strlen( getline('.') ) if s:previous_num_chars_on_current_line == -1 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 if s:searched_and_results_found " This command does the actual closing of the preview window. If no preview " window is shown, nothing happens. pclose endif endfunction function! s:UpdateDiagnosticNotifications() let should_display_diagnostics = g:ycm_show_diagnostics_ui && \ s:DiagnosticUiSupportedForCurrentFiletype() && \ pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' ) if !should_display_diagnostics return endif py ycm_state.UpdateDiagnosticInterface() endfunction function! s:IdentifierFinishedOperations() if !pyeval( 'base.CurrentIdentifierFinished()' ) return endif py 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 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 " invokes the user's completion function (which we have set to " youcompleteme#Complete), and 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 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( "\\\", 'n' ) endfunction python << EOF def GetCompletions( query ): request = ycm_state.GetCurrentCompletionRequest() request.Start( query ) 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:CompletionsForQuery( query ) py results = GetCompletions( vim.eval( 'a:query' ) ) let results = pyeval( 'results' ) let s:searched_and_results_found = len( results.words ) != 0 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 py request = ycm_state.CreateCompletionRequest() if !pyeval( 'bool(request)' ) return -2 endif return pyeval( 'request.CompletionStartColumn()' ) else return s:CompletionsForQuery( a:base ) endif endfunction function! youcompleteme#OmniComplete( findstart, base ) if a:findstart let s:omnifunc_mode = 1 py request = ycm_state.CreateCompletionRequest( force_semantic = True ) return pyeval( 'request.CompletionStartColumn()' ) else return s:CompletionsForQuery( a:base ) endif endfunction function! youcompleteme#ServerPid() return pyeval( 'ycm_state.ServerPid()' ) endfunction function! s:RestartServer() py ycm_state.RestartServer() endfunction command! YcmRestartServer call s:RestartServer() function! s:ShowDetailedDiagnostic() py ycm_state.ShowDetailedDiagnostic() endfunction command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic() function! s:DebugInfo() echom "Printing YouCompleteMe debug information..." let debug_info = pyeval( 'ycm_state.DebugInfo()' ) for line in split( debug_info, "\n" ) echom '-- ' . line endfor endfunction command! YcmDebugInfo call s:DebugInfo() 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 py ycm_state.SendCommandRequest( vim.eval( 'l:arguments' ), \ vim.eval( 'l:completer' ) ) endfunction function! youcompleteme#OpenGoToList() set lazyredraw cclose execute 'belowright copen 3' set nolazyredraw au WinLeave q " automatically leave, if an option is chosen redraw! endfunction command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete \ YcmCompleter call s:CompleterCommand() function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos ) return join( pyeval( 'ycm_state.GetDefinedSubcommands()' ), \ "\n") endfunction function! s:ForceCompile() if !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." py ycm_state.OnFileReadyToParse() while 1 let diagnostics_ready = pyeval( \ 'ycm_state.DiagnosticsForCurrentFileReady()' ) if diagnostics_ready break endif sleep 100m endwhile return 1 endfunction function! s:ForceCompileAndDiagnostics() let compilation_succeeded = s:ForceCompile() if !compilation_succeeded return endif call s:UpdateDiagnosticNotifications() echom "Diagnostics refreshed." endfunction command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics() function! s:ShowDiagnostics() let compilation_succeeded = s:ForceCompile() if !compilation_succeeded return endif let diags = pyeval( \ 'ycm_state.GetDiagnosticsFromStoredRequest( qflist_format = True )' ) if !empty( diags ) call setloclist( 0, diags ) if g:ycm_open_loclist_on_ycm_diags lopen endif else echom "No warnings or errors detected" endif endfunction command! YcmDiags call s:ShowDiagnostics() " This is basic vim plugin boilerplate let &cpo = s:save_cpo unlet s:save_cpo vim-youcompleteme-0+20140207+git18be5c2/cpp/000077500000000000000000000000001227567565400201445ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/CMakeLists.txt000066400000000000000000000144531227567565400227130ustar00rootroot00000000000000# 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 . cmake_minimum_required( VERSION 2.8 ) project( YouCompleteMe ) option( UNIVERSAL "Build universal mac binary" OFF ) if ( CMAKE_GENERATOR STREQUAL Xcode ) set( CMAKE_GENERATOR_IS_XCODE true ) endif() if ( ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" ) set( SYSTEM_IS_FREEBSD true ) endif() if ( ${CMAKE_SYSTEM_NAME} MATCHES "SunOS" ) set( SYSTEM_IS_SUNOS true ) endif() # Check if platform is 64 bit if( CMAKE_SIZEOF_VOID_P EQUAL 4 ) set( 64_BIT_PLATFORM 0 ) else() set( 64_BIT_PLATFORM 1 ) endif() ############################################################################# # Turning on this flag tells cmake to emit a compile_commands.json file. # This file can be used to load compilation flags into YCM. See here for more # details: http://clang.llvm.org/docs/JSONCompilationDatabase.html set( CMAKE_EXPORT_COMPILE_COMMANDS 1 ) ############################################################################# # This is needed so that on macs, the library is built in both 32 bit and 64 bit # versions. Without this python might refuse to load the module, depending on # how python was built. # On Mac, boost needs to be compiled universal as well, if used instead of the # included BoostParts lib. For brew, that's # "brew install boost --universal" # If the user chose to use the system libclang.dylib (or the libclang.dylib # binary downloaded from llvm.org) on a mac, then we don't specify universal # binary building since the system libclang on macs is not universal (and thus # linking would fail with universal). if ( UNIVERSAL AND NOT USE_SYSTEM_LIBCLANG ) set( CMAKE_OSX_ARCHITECTURES "i386;x86_64" ) endif() ############################################################################# if ( CMAKE_CXX_COMPILER_ID STREQUAL "Clang" ) set( COMPILER_IS_CLANG true ) # Linux machines don't necessarily have libc++ installed alongside clang, # but HAS_LIBCXX11 doesn't always trigger for machines that DO have libc++. We # know that at least all the Mac OS versions we support that use Clang have # libc++, so we're safe there. On FreeBSD 9 libc++ is an optional build # toggle. On FreeBSD 10 it is the default. if ( HAS_LIBCXX11 OR APPLE OR SYSTEM_IS_FREEBSD ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++" ) endif() # Ninja will by default prevent Clang from outputting diagnostics in color, so # we force color output if ( CMAKE_GENERATOR STREQUAL "Ninja" ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcolor-diagnostics" ) endif() endif() ############################################################################# # Force release build by default, speed is of the essence if ( NOT CMAKE_BUILD_TYPE ) set( CMAKE_BUILD_TYPE Release ) endif() ############################################################################# # Determining the presence of C++11 support in the compiler set( CPP11_AVAILABLE false ) if ( CMAKE_COMPILER_IS_GNUCXX ) execute_process( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) if ( GCC_VERSION VERSION_GREATER 4.6 OR GCC_VERSION VERSION_EQUAL 4.6 ) set( CPP11_AVAILABLE true ) endif() elseif( COMPILER_IS_CLANG ) set( CPP11_AVAILABLE true ) set( CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11" ) set( CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++" ) endif() ############################################################################# # For MSVC enable UNICODE and compilation on multiple processors if ( MSVC ) add_definitions( /DUNICODE /D_UNICODE /Zc:wchar_t- ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP" ) endif() # Solves the conflict in names of hypot in python sources and boost::python if ( MINGW ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -include cmath") endif() # Due to a bug/misconfiguration/stupidity, boost 1.52 and libc++ don't like each # other much: a compilation error "Constexpr function never produces a constant # expression" pops up when trying to compile anything that uses # boost/chrono/duration.hpp (namely boost/thread for us). This is a workaround # that prevents this from happening. Also present in cpp/BoostParts/CMakeLists.txt. # See here for more details: https://svn.boost.org/trac/boost/ticket/7671 # TODO: remove this when it's fixed upstream (probably boost 1.53). add_definitions( -DBOOST_THREAD_DONT_USE_CHRONO ) if( MSVC OR CYGWIN ) # BOOST_ALL_NO_LIB turns off MSVC library autolinking add_definitions( -DBOOST_ALL_NO_LIB ) endif() if( WIN32 OR CYGWIN ) # BOOST_PYTHON_SOURCE makes boost use the correct __declspec add_definitions( -DBOOST_PYTHON_SOURCE -DBOOST_THREAD_USE_LIB ) if ( 64_BIT_PLATFORM ) # Enables python compilation for 64-bit Windows add_definitions( -DMS_WIN64 ) endif() endif() ############################################################################# # When used with Clang, adding the -std=c++0x flag to CMAKE_CXX_FLAGS will cause # the compiler to output a warning during linking: # clang: warning: argument unused during compilation: '-std=c++0x' # This is caused by cmake passing this flag to the linking stage which it # shouldn't do. It's ignored so it does no harm, but the warning is annoying. # # Putting the flag in add_definitions() works around the issue, even though it # shouldn't in theory go there. if ( CPP11_AVAILABLE ) message( "Your C++ compiler supports C++11, compiling in that mode." ) # Cygwin needs its hand held a bit; see issue #473 if ( CYGWIN AND CMAKE_COMPILER_IS_GNUCXX ) add_definitions( -std=gnu++0x ) else() add_definitions( -std=c++0x ) endif() else() message( "Your C++ compiler does NOT support C++11, compiling in C++03 mode." ) endif() add_subdirectory( BoostParts ) add_subdirectory( ycm ) vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/000077500000000000000000000000001227567565400207345ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/.ycm_extra_conf.py000066400000000000000000000145631227567565400243750ustar00rootroot00000000000000# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # 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 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. # # For more information, please refer to import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is not set). # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall', '-Wextra', '-Werror', '-Wc++98-compat', '-Wno-long-long', '-Wno-variadic-macros', '-fexceptions', '-DNDEBUG', # You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM # source code needs it. '-DUSE_CLANG_COMPLETER', # THIS IS IMPORTANT! Without a "-std=" flag, clang won't know which # language to use when compiling headers. So it will guess. Badly. So C++ # headers will be compiled as C headers. You don't want that so ALWAYS specify # a "-std=". # For a C project, you would set this to something like 'c99' instead of # 'c++11'. '-std=c++11', # ...and the same thing goes for the magic -x option which specifies the # language that the files to be compiled are written in. This is mostly # relevant for c++ headers. # For a C project, you would set this to 'c' instead of 'c++'. '-x', 'c++', '-isystem', '../BoostParts', '-isystem', # This path will only work on OS X, but extra paths that don't exist are not # harmful '/System/Library/Frameworks/Python.framework/Headers', '-isystem', '../llvm/include', '-isystem', '../llvm/tools/clang/include', '-I', '.', '-I', './ClangCompleter', '-isystem', './tests/gmock/gtest', '-isystem', './tests/gmock/gtest/include', '-isystem', './tests/gmock', '-isystem', './tests/gmock/include', '-isystem', '/usr/include', '-isystem', '/usr/local/include', '-isystem', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1', '-isystem', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include', ] # Set this to the absolute path to the folder (NOT the file!) containing the # compile_commands.json file to use that instead of 'flags'. See here for # more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html # # Most projects will NOT need to set this to anything; you can just change the # 'flags' list of compilation flags. Notice that YCM itself uses that approach. compilation_database_folder = '' if os.path.exists( compilation_database_folder ): database = ycm_core.CompilationDatabase( compilation_database_folder ) else: database = None SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ] def DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): if not working_directory: return list( flags ) new_flags = [] make_next_absolute = False path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] for flag in flags: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith( '/' ): new_flag = os.path.join( working_directory, flag ) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True break if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ] return extension in [ '.h', '.hxx', '.hpp', '.hh' ] def GetCompilationInfoForFile( filename ): # The compilation_commands.json file generated by CMake does not have entries # for header files. So we do our best by asking the db for flags for a # corresponding source file, if any. If one exists, the flags for that file # should be good enough. if IsHeaderFile( filename ): basename = os.path.splitext( filename )[ 0 ] for extension in SOURCE_EXTENSIONS: replacement_file = basename + extension if os.path.exists( replacement_file ): compilation_info = database.GetCompilationInfoForFile( replacement_file ) if compilation_info.compiler_flags_: return compilation_info return None return database.GetCompilationInfoForFile( filename ) def FlagsForFile( filename, **kwargs ): if database: # Bear in mind that compilation_info.compiler_flags_ does NOT return a # python list, but a "list-like" StringVec object compilation_info = GetCompilationInfoForFile( filename ) if not compilation_info: return None final_flags = MakeRelativePathsInFlagsAbsolute( compilation_info.compiler_flags_, compilation_info.compiler_working_dir_ ) # NOTE: This is just for YouCompleteMe; it's highly likely that your project # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT. try: final_flags.remove( '-stdlib=libc++' ) except ValueError: pass else: relative_to = DirectoryOfThisScript() final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) return { 'flags': final_flags, 'do_cache': True } vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/CMakeLists.txt000066400000000000000000000316241227567565400235020ustar00rootroot00000000000000# 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 . cmake_minimum_required( VERSION 2.8 ) project( ycm_support_libs ) set( CLIENT_LIB "ycm_client_support" ) set( SERVER_LIB "ycm_core" ) set( Python_ADDITIONAL_VERSIONS 2.7 2.6 ) find_package( PythonLibs 2.6 REQUIRED ) if ( NOT PYTHONLIBS_VERSION_STRING VERSION_LESS "3.0.0" ) message( FATAL_ERROR "CMake found python3 libs instead of python2 libs. YCM works only with " "python2.\n" ) endif() option( USE_DEV_FLAGS "Use compilation flags meant for YCM developers" OFF ) option( USE_CLANG_COMPLETER "Use Clang semantic completer for C/C++/ObjC" OFF ) option( USE_SYSTEM_LIBCLANG "Set to ON to use the system libclang library" OFF ) set( PATH_TO_LLVM_ROOT "" CACHE PATH "Path to the root of a LLVM+Clang binary distribution" ) set( EXTERNAL_LIBCLANG_PATH "" CACHE PATH "Path libclang library to use" ) if ( USE_CLANG_COMPLETER AND NOT USE_SYSTEM_LIBCLANG AND NOT PATH_TO_LLVM_ROOT ) message( "Downloading Clang 3.4" ) set( CLANG_URL "http://llvm.org/releases/3.4" ) if ( APPLE ) set( CLANG_DIRNAME "clang+llvm-3.4-x86_64-apple-darwin10.9" ) set( CLANG_MD5 "4f43ea0e87090ae5e7bec12373ca4927" ) set( CLANG_FILENAME "${CLANG_DIRNAME}.tar.gz" ) else() if ( 64_BIT_PLATFORM ) set( CLANG_DIRNAME "clang+llvm-3.4-x86_64-unknown-ubuntu12.04" ) set( CLANG_MD5 "6077459d20a7ff412eefc6ce3b9f5c85" ) set( CLANG_FILENAME "${CLANG_DIRNAME}.tar.xz" ) else() message( "No pre-built Clang 3.4 binaries for 32 bit linux, " "downloading Clang 3.3" ) set( CLANG_URL "http://llvm.org/releases/3.3" ) set( CLANG_DIRNAME "clang+llvm-3.3-i386-debian6" ) set( CLANG_MD5 "415d033b60659433d4631df894673802" ) set( CLANG_FILENAME "${CLANG_DIRNAME}.tar.bz2" ) endif() endif() file( DOWNLOAD "${CLANG_URL}/${CLANG_FILENAME}" "./${CLANG_FILENAME}" SHOW_PROGRESS EXPECTED_MD5 "${CLANG_MD5}" ) if ( CLANG_FILENAME MATCHES ".+bz2" ) execute_process( COMMAND tar -xjf ${CLANG_FILENAME} ) elseif( CLANG_FILENAME MATCHES ".+xz" ) execute_process( COMMAND tar -xJf ${CLANG_FILENAME} ) else() execute_process( COMMAND tar -xzf ${CLANG_FILENAME} ) endif() # And set PATH_TO_LLVM_ROOT set( PATH_TO_LLVM_ROOT "${CMAKE_CURRENT_BINARY_DIR}/../${CLANG_DIRNAME}" ) endif() if ( PATH_TO_LLVM_ROOT OR USE_SYSTEM_LIBCLANG OR EXTERNAL_LIBCLANG_PATH ) set( USE_CLANG_COMPLETER TRUE ) endif() if ( USE_CLANG_COMPLETER AND NOT PATH_TO_LLVM_ROOT AND NOT USE_SYSTEM_LIBCLANG AND NOT EXTERNAL_LIBCLANG_PATH ) message( FATAL_ERROR "You have not specified which libclang to use. You have several options:\n" " 1. Set PATH_TO_LLVM_ROOT to a path to the root of a LLVM+Clang binary " "distribution. You can download such a binary distro from llvm.org. This " "is the recommended approach.\n" " 2. Set USE_SYSTEM_LIBCLANG to ON; this makes YCM search for the system " "version of libclang.\n" " 3. Set EXTERNAL_LIBCLANG_PATH to a path to whatever " "libclang.[so|dylib|dll] you wish to use.\n" "You HAVE to pick one option. See the docs for more information.") endif() if ( USE_CLANG_COMPLETER ) message( "Using libclang to provide semantic completion for C/C++/ObjC" ) else() message( "NOT using libclang, no semantic completion for C/C++/ObjC will be " "available" ) endif() if ( PATH_TO_LLVM_ROOT ) set( CLANG_INCLUDES_DIR "${PATH_TO_LLVM_ROOT}/include" ) else() set( CLANG_INCLUDES_DIR "${CMAKE_SOURCE_DIR}/llvm/include" ) endif() if ( NOT IS_ABSOLUTE "${CLANG_INCLUDES_DIR}" ) get_filename_component(CLANG_INCLUDES_DIR "${CMAKE_BINARY_DIR}/${CLANG_INCLUDES_DIR}" ABSOLUTE) endif() if ( NOT EXTERNAL_LIBCLANG_PATH AND PATH_TO_LLVM_ROOT ) if ( MINGW ) set( LIBCLANG_SEARCH_PATH "${PATH_TO_LLVM_ROOT}/bin" ) else() set( LIBCLANG_SEARCH_PATH "${PATH_TO_LLVM_ROOT}/lib" ) endif() # Need TEMP because find_library does not work with an option variable find_library( TEMP NAMES clang libclang PATHS ${LIBCLANG_SEARCH_PATH} NO_DEFAULT_PATH ) set( EXTERNAL_LIBCLANG_PATH ${TEMP} ) endif() # This is a workaround for a CMake bug with include_directories(SYSTEM ...) # on Mac OS X. Bug report: http://public.kitware.com/Bug/view.php?id=10837 if ( APPLE ) set( CMAKE_INCLUDE_SYSTEM_FLAG_CXX "-isystem " ) endif() # The SYSTEM flag makes sure that -isystem[header path] is passed to the # compiler instead of the standard -I[header path]. Headers included with # -isystem do not generate warnings (and they shouldn't; e.g. boost warnings are # just noise for us since we won't be changing them). include_directories( SYSTEM ${BoostParts_SOURCE_DIR} ${PYTHON_INCLUDE_DIRS} ${CLANG_INCLUDES_DIR} ) file( GLOB_RECURSE SERVER_SOURCES *.h *.cpp ) # The test sources are a part of a different target, so we remove them # The CMakeFiles cpp file is picked up when the user creates an in-source build, # and we don't want that. We also remove client-specific code file( GLOB_RECURSE to_remove tests/*.h tests/*.cpp CMakeFiles/*.cpp *client* ) if( to_remove ) list( REMOVE_ITEM SERVER_SOURCES ${to_remove} ) endif() if ( USE_CLANG_COMPLETER ) include_directories( ${CMAKE_CURRENT_SOURCE_DIR} "${CMAKE_CURRENT_SOURCE_DIR}/ClangCompleter" ) add_definitions( -DUSE_CLANG_COMPLETER ) else() file( GLOB_RECURSE to_remove_clang ClangCompleter/*.h ClangCompleter/*.cpp ) if( to_remove_clang ) list( REMOVE_ITEM SERVER_SOURCES ${to_remove_clang} ) endif() endif() ############################################################################# # One can use the system libclang.[so|dylib] like so: # cmake -DUSE_SYSTEM_LIBCLANG=1 [...] # One can also explicitely pick the external libclang.[so|dylib] for use like so: # cmake -DEXTERNAL_LIBCLANG_PATH=/path/to/libclang.so [...] # The final .so we build will then first look in the same dir in which it is # located for libclang.so. This is provided by the rpath = $ORIGIN feature. if ( EXTERNAL_LIBCLANG_PATH OR USE_SYSTEM_LIBCLANG ) if ( USE_SYSTEM_LIBCLANG ) if ( APPLE ) set( ENV_LIB_PATHS ENV DYLD_LIBRARY_PATH ) elseif ( UNIX ) set( ENV_LIB_PATHS ENV LD_LIBRARY_PATH ) elseif ( WIN32 ) set( ENV_LIB_PATHS ENV PATH ) else () set( ENV_LIB_PATHS "" ) endif() # On Debian-based systems, llvm installs into /usr/lib/llvm-x.y. file( GLOB SYS_LLVM_PATHS "/usr/lib/llvm*/lib" ) # Need TEMP because find_library does not work with an option variable find_library( TEMP clang PATHS ${ENV_LIB_PATHS} /usr/lib /usr/lib/llvm ${SYS_LLVM_PATHS} /Library/Developer/CommandLineTools/usr/lib, /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib ) set( EXTERNAL_LIBCLANG_PATH ${TEMP} ) else() # For Macs, we do things differently; look further in this file. if ( NOT APPLE ) # Setting this to true makes sure that libraries we build will have our rpath # set even without having to do "make install" set( CMAKE_BUILD_WITH_INSTALL_RPATH TRUE ) set( CMAKE_INSTALL_RPATH "\$ORIGIN" ) endif() endif() set( LIBCLANG_TARGET ${EXTERNAL_LIBCLANG_PATH} ) message( "Using external libclang: ${EXTERNAL_LIBCLANG_PATH}" ) else() set( LIBCLANG_TARGET ) endif() if ( EXTRA_RPATH ) set( CMAKE_INSTALL_RPATH "${EXTRA_RPATH}:${CMAKE_INSTALL_RPATH}" ) endif() # Needed on Linux machines, but not on Macs if ( UNIX AND NOT APPLE ) set( EXTRA_LIBS rt ) endif() ############################################################################# # We don't actually need all of the files this picks up, just the ones needed by # PythonSupport.cpp. But this is easier to maintain and dead code elemination # will remove unused code. file( GLOB CLIENT_SOURCES *.h *.cpp ) file( GLOB SERVER_SPECIFIC *ycm_core* ) if( SERVER_SPECIFIC ) list( REMOVE_ITEM CLIENT_SOURCES ${SERVER_SPECIFIC} ) endif() add_library( ${CLIENT_LIB} SHARED ${CLIENT_SOURCES} ) target_link_libraries( ${CLIENT_LIB} BoostParts ${PYTHON_LIBRARIES} ${EXTRA_LIBS} ) ############################################################################# add_library( ${SERVER_LIB} SHARED ${SERVER_SOURCES} ) target_link_libraries( ${SERVER_LIB} BoostParts ${PYTHON_LIBRARIES} ${LIBCLANG_TARGET} ${EXTRA_LIBS} ) if( LIBCLANG_TARGET ) if( NOT WIN32 ) add_custom_command( TARGET ${SERVER_LIB} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${LIBCLANG_TARGET}" "$" ) else() add_custom_command( TARGET ${SERVER_LIB} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${PATH_TO_LLVM_ROOT}/bin/libclang.dll" "$") endif() endif() ############################################################################# # Convenience target that builds both support libs. add_custom_target( ${PROJECT_NAME} DEPENDS ${CLIENT_LIB} ${SERVER_LIB} ) ############################################################################# # Things are a bit different on Macs when using an external libclang.dylib; here # we want to make sure we use @loader_path/libclang.dylib instead of # @rpath/libclang.dylib in the final ycm_core.so. If we use the # @rpath version, then it may load the system libclang which the user # explicitely does not want (otherwise the user would specify # USE_SYSTEM_LIBCLANG). With @loader_path, we make sure that only the # libclang.dylib present in the same directory as our ycm_core.so # is used. if ( EXTERNAL_LIBCLANG_PATH AND APPLE ) add_custom_command( TARGET ${SERVER_LIB} POST_BUILD COMMAND install_name_tool "-change" "@rpath/libclang.dylib" "@loader_path/libclang.dylib" "$" ) endif() ############################################################################# # We don't want the "lib" prefix, it can screw up python when it tries to search # for our module set_target_properties( ${CLIENT_LIB} PROPERTIES PREFIX "") set_target_properties( ${SERVER_LIB} PROPERTIES PREFIX "") if ( WIN32 OR CYGWIN ) # This is the extension for compiled Python modules on Windows set_target_properties( ${CLIENT_LIB} PROPERTIES SUFFIX ".pyd") set_target_properties( ${SERVER_LIB} PROPERTIES SUFFIX ".pyd") else() # Even on macs, we want a .so extension instead of a .dylib which is what # cmake would give us by default. Python won't recognize a .dylib as a module, # but it will recognize a .so set_target_properties( ${CLIENT_LIB} PROPERTIES SUFFIX ".so") set_target_properties( ${SERVER_LIB} PROPERTIES SUFFIX ".so") endif() set_target_properties( ${CLIENT_LIB} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../../python ) set_target_properties( ${SERVER_LIB} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/../../python ) ############################################################################# # For some reason, Xcode is too dumb to understand the -isystem flag and thus # borks on warnings in Boost. if ( USE_DEV_FLAGS AND ( CMAKE_COMPILER_IS_GNUCXX OR COMPILER_IS_CLANG ) AND NOT CMAKE_GENERATOR_IS_XCODE ) # We want all warnings, and warnings should be treated as errors set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror" ) endif() ############################################################################# # We want warnings if we accidentally use C++11 features # We can't use this warning on FreeBSD because std headers on that OS are dumb. # See here: https://github.com/Valloric/YouCompleteMe/issues/260 if ( USE_DEV_FLAGS AND COMPILER_IS_CLANG AND NOT CMAKE_GENERATOR_IS_XCODE AND NOT SYSTEM_IS_FREEBSD ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wc++98-compat" ) endif() ############################################################################# if( SYSTEM_IS_SUNOS ) # SunOS needs this setting for thread support set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthreads" ) endif() add_subdirectory( tests ) vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Candidate.cpp000066400000000000000000000066371227567565400233300ustar00rootroot00000000000000// 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 . #include "standard.h" #include "Candidate.h" #include "Result.h" #include #include using boost::algorithm::all; using boost::algorithm::is_lower; namespace YouCompleteMe { namespace { LetterNode *FirstUppercaseNode( const std::list< LetterNode *> &list ) { LetterNode *node = NULL; foreach( LetterNode * current_node, list ) { if ( current_node->LetterIsUppercase() ) { node = current_node; break; } } return node; } } // unnamed namespace std::string GetWordBoundaryChars( const std::string &text ) { std::string result; for ( uint i = 0; i < text.size(); ++i ) { bool is_first_char_but_not_underscore = i == 0 && text[ i ] != '_'; bool is_good_uppercase = i > 0 && IsUppercase( text[ i ] ) && !IsUppercase( text[ i - 1 ] ); bool is_alpha_after_underscore = i > 0 && text[ i - 1 ] == '_' && isalpha( text[ i ] ); if ( is_first_char_but_not_underscore || is_good_uppercase || is_alpha_after_underscore ) { result.push_back( tolower( text[ i ] ) ); } } return result; } Bitset LetterBitsetFromString( const std::string &text ) { Bitset letter_bitset; foreach ( char letter, text ) { letter_bitset.set( IndexForChar( letter ) ); } return letter_bitset; } Candidate::Candidate( const std::string &text ) : text_( text ), word_boundary_chars_( GetWordBoundaryChars( text ) ), text_is_lowercase_( all( text, is_lower() ) ), letters_present_( LetterBitsetFromString( text ) ), root_node_( new LetterNode( text ) ) { } Result Candidate::QueryMatchResult( const std::string &query, bool case_sensitive ) const { LetterNode *node = root_node_.get(); int index_sum = 0; foreach ( char letter, query ) { const std::list< LetterNode *> *list = node->NodeListForLetter( letter ); if ( !list ) return Result( false ); if ( case_sensitive ) { // When the query letter is uppercase, then we force an uppercase match // but when the query letter is lowercase, then it can match both an // uppercase and a lowercase letter. This is by design and it's much // better than forcing lowercase letter matches. node = IsUppercase( letter ) ? FirstUppercaseNode( *list ) : list->front(); if ( !node ) return Result( false ); } else { node = list->front(); } index_sum += node->Index(); } return Result( true, &text_, text_is_lowercase_, index_sum, word_boundary_chars_, query ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Candidate.h000066400000000000000000000036041227567565400227640ustar00rootroot00000000000000// 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 . #ifndef CANDIDATE_H_R5LZH6AC #define CANDIDATE_H_R5LZH6AC #include "LetterNode.h" #include #include #include #include namespace YouCompleteMe { class Result; typedef std::bitset< NUM_LETTERS > Bitset; Bitset LetterBitsetFromString( const std::string &text ); // Public for tests std::string GetWordBoundaryChars( const std::string &text ); class Candidate : boost::noncopyable { public: explicit Candidate( const std::string &text ); inline const std::string &Text() const { return text_; } // Returns true if the candidate contains the bits from the query (it may also // contain other bits) inline bool MatchesQueryBitset( const Bitset &query_bitset ) const { return ( letters_present_ & query_bitset ) == query_bitset; } Result QueryMatchResult( const std::string &query, bool case_sensitive ) const; private: std::string text_; std::string word_boundary_chars_; bool text_is_lowercase_; Bitset letters_present_; boost::scoped_ptr< LetterNode > root_node_; }; } // namespace YouCompleteMe #endif /* end of include guard: CANDIDATE_H_R5LZH6AC */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/CandidateRepository.cpp000066400000000000000000000065761227567565400254320ustar00rootroot00000000000000// 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 . #include "CandidateRepository.h" #include "Candidate.h" #include "standard.h" #include "Utils.h" #include #include #include #ifdef USE_CLANG_COMPLETER # include "ClangCompleter/CompletionData.h" #endif // USE_CLANG_COMPLETER namespace YouCompleteMe { using boost::all; using boost::is_print; boost::mutex CandidateRepository::singleton_mutex_; CandidateRepository *CandidateRepository::instance_ = NULL; CandidateRepository &CandidateRepository::Instance() { boost::lock_guard< boost::mutex > locker( singleton_mutex_ ); if ( !instance_ ) { static CandidateRepository repo; instance_ = &repo; } return *instance_; } int CandidateRepository::NumStoredCandidates() { boost::lock_guard< boost::mutex > locker( holder_mutex_ ); return candidate_holder_.size(); } std::vector< const Candidate * > CandidateRepository::GetCandidatesForStrings( const std::vector< std::string > &strings ) { std::vector< const Candidate * > candidates; candidates.reserve( strings.size() ); { boost::lock_guard< boost::mutex > locker( holder_mutex_ ); foreach ( const std::string & candidate_text, strings ) { const std::string &validated_candidate_text = all( candidate_text, is_print( std::locale::classic() ) ) ? candidate_text : empty_; const Candidate *&candidate = GetValueElseInsert( candidate_holder_, validated_candidate_text, NULL ); if ( !candidate ) candidate = new Candidate( validated_candidate_text ); candidates.push_back( candidate ); } } return candidates; } #ifdef USE_CLANG_COMPLETER std::vector< const Candidate * > CandidateRepository::GetCandidatesForStrings( const std::vector< CompletionData > &datas ) { std::vector< const Candidate * > candidates; candidates.reserve( datas.size() ); { boost::lock_guard< boost::mutex > locker( holder_mutex_ ); foreach ( const CompletionData & data, datas ) { const Candidate *&candidate = GetValueElseInsert( candidate_holder_, data.original_string_, NULL ); if ( !candidate ) candidate = new Candidate( data.original_string_ ); candidates.push_back( candidate ); } } return candidates; } #endif // USE_CLANG_COMPLETER CandidateRepository::~CandidateRepository() { foreach ( const CandidateHolder::value_type & pair, candidate_holder_ ) { delete pair.second; } } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/CandidateRepository.h000066400000000000000000000043111227567565400250600ustar00rootroot00000000000000// 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 . #ifndef CANDIDATEREPOSITORY_H_K9OVCMHG #define CANDIDATEREPOSITORY_H_K9OVCMHG #include #include #include #include #include namespace YouCompleteMe { class Candidate; struct CompletionData; typedef boost::unordered_map< std::string, const Candidate * > CandidateHolder; // This singleton stores already built Candidate objects for candidate strings // that were already seen. If Candidates are requested for previously unseen // strings, new Candidate objects are built. // // This is shared by the identifier completer and the clang completer so that // work is not repeated. // // This class is thread-safe. class CandidateRepository : boost::noncopyable { public: static CandidateRepository &Instance(); int NumStoredCandidates(); std::vector< const Candidate * > GetCandidatesForStrings( const std::vector< std::string > &strings ); #ifdef USE_CLANG_COMPLETER std::vector< const Candidate * > GetCandidatesForStrings( const std::vector< CompletionData > &datas ); #endif // USE_CLANG_COMPLETER private: CandidateRepository() {}; ~CandidateRepository(); boost::mutex holder_mutex_; static boost::mutex singleton_mutex_; static CandidateRepository *instance_; const std::string empty_; // This data structure owns all the Candidate pointers CandidateHolder candidate_holder_; }; } // namespace YouCompleteMe #endif /* end of include guard: CANDIDATEREPOSITORY_H_K9OVCMHG */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/000077500000000000000000000000001227567565400236335ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangCompleter.cpp000066400000000000000000000123621227567565400272420ustar00rootroot00000000000000// Copyright (C) 2011-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 . #include "ClangCompleter.h" #include "exceptions.h" #include "Result.h" #include "Candidate.h" #include "TranslationUnit.h" #include "standard.h" #include "CandidateRepository.h" #include "CompletionData.h" #include "Utils.h" #include "ClangUtils.h" #include "ReleaseGil.h" #include #include using boost::shared_ptr; using boost::unordered_map; namespace YouCompleteMe { ClangCompleter::ClangCompleter() : clang_index_( clang_createIndex( 0, 0 ) ), translation_unit_store_( clang_index_ ) { // The libclang docs don't say what is the default value for crash recovery. // I'm pretty sure it's turned on by default, but I'm not going to take any // chances. clang_toggleCrashRecovery( true ); } ClangCompleter::~ClangCompleter() { // We need to destroy all TUs before calling clang_disposeIndex because // the translation units need to be destroyed before the index is destroyed. // Technically, a thread could still be holding onto a shared_ptr object // when we destroy the clang index, but since we're shutting down, we don't // really care. // In practice, this situation shouldn't happen because the server threads are // Python deamon threads and will all be killed before the main thread exits. translation_unit_store_.RemoveAll(); clang_disposeIndex( clang_index_ ); } bool ClangCompleter::UpdatingTranslationUnit( const std::string &filename ) { ReleaseGil unlock; shared_ptr< TranslationUnit > unit = translation_unit_store_.Get( filename ); if ( !unit ) return false; // Thankfully, an invalid, sentinel TU always returns true for // IsCurrentlyUpdating, so no caller will try to rely on the TU object, even // if unit is currently pointing to a sentinel. return unit->IsCurrentlyUpdating(); } std::vector< Diagnostic > ClangCompleter::UpdateTranslationUnit( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ) { ReleaseGil unlock; bool translation_unit_created; shared_ptr< TranslationUnit > unit = translation_unit_store_.GetOrCreate( filename, unsaved_files, flags, translation_unit_created ); if ( !unit ) return std::vector< Diagnostic >(); try { // There's no point in reparsing a TU that was just created, it was just // parsed in the TU constructor if ( !translation_unit_created ) return unit->Reparse( unsaved_files ); return unit->LatestDiagnostics(); } catch ( ClangParseError & ) { // If unit->Reparse fails, then the underlying TranslationUnit object is not // valid anymore and needs to be destroyed and removed from the filename -> // TU map. translation_unit_store_.Remove( filename ); } return std::vector< Diagnostic >(); } std::vector< CompletionData > ClangCompleter::CandidatesForLocationInFile( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ) { ReleaseGil unlock; shared_ptr< TranslationUnit > unit = translation_unit_store_.GetOrCreate( filename, unsaved_files, flags ); if ( !unit ) return std::vector< CompletionData >(); return unit->CandidatesForLocation( line, column, unsaved_files ); } Location ClangCompleter::GetDeclarationLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ) { ReleaseGil unlock; shared_ptr< TranslationUnit > unit = translation_unit_store_.GetOrCreate( filename, unsaved_files, flags ); if ( !unit ) { return Location(); } return unit->GetDeclarationLocation( line, column, unsaved_files ); } Location ClangCompleter::GetDefinitionLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ) { ReleaseGil unlock; shared_ptr< TranslationUnit > unit = translation_unit_store_.GetOrCreate( filename, unsaved_files, flags ); if ( !unit ) { return Location(); } return unit->GetDefinitionLocation( line, column, unsaved_files ); } void ClangCompleter::DeleteCachesForFile( const std::string &filename ) { ReleaseGil unlock; translation_unit_store_.Remove( filename ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangCompleter.h000066400000000000000000000046721227567565400267140ustar00rootroot00000000000000// 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 . #ifndef CLANGCOMPLETE_H_WLKDU0ZV #define CLANGCOMPLETE_H_WLKDU0ZV #include "UnsavedFile.h" #include "Diagnostic.h" #include "TranslationUnitStore.h" #include #include typedef struct CXTranslationUnitImpl *CXTranslationUnit; namespace YouCompleteMe { class TranslationUnit; struct CompletionData; struct Location; typedef std::vector< CompletionData > CompletionDatas; // All filename parameters must be absolute paths. class ClangCompleter : boost::noncopyable { public: ClangCompleter(); ~ClangCompleter(); bool UpdatingTranslationUnit( const std::string &filename ); std::vector< Diagnostic > UpdateTranslationUnit( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ); std::vector< CompletionData > CandidatesForLocationInFile( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ); Location GetDeclarationLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ); Location GetDefinitionLocation( const std::string &filename, int line, int column, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ); void DeleteCachesForFile( const std::string &filename ); private: ///////////////////////////// // PRIVATE MEMBER VARIABLES ///////////////////////////// CXIndex clang_index_; TranslationUnitStore translation_unit_store_; }; } // namespace YouCompleteMe #endif /* end of include guard: CLANGCOMPLETE_H_WLKDU0ZV */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangHelpers.cpp000066400000000000000000000162031227567565400267100ustar00rootroot00000000000000// 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 . #include "standard.h" #include "ClangHelpers.h" #include "ClangUtils.h" #include "Utils.h" #include "UnsavedFile.h" #include "Location.h" #include "Range.h" #include using boost::unordered_map; namespace YouCompleteMe { namespace { // NOTE: The passed in pointer should never be NULL! std::string FullDiagnosticText( CXDiagnostic cxdiagnostic ) { std::string full_text = CXStringToString( clang_formatDiagnostic( cxdiagnostic, clang_defaultDiagnosticDisplayOptions() ) ); // Note: clang docs say that a CXDiagnosticSet retrieved with // clang_getChildDiagnostics do NOT need to be released with // clang_diposeDiagnosticSet CXDiagnosticSet diag_set = clang_getChildDiagnostics( cxdiagnostic ); if ( !diag_set ) return full_text; uint num_child_diagnostics = clang_getNumDiagnosticsInSet( diag_set ); if ( !num_child_diagnostics ) return full_text; for ( uint i = 0; i < num_child_diagnostics; ++i ) { CXDiagnostic diagnostic = clang_getDiagnosticInSet( diag_set, i ); if ( !diagnostic ) continue; full_text.append( FullDiagnosticText( diagnostic ) ); } return full_text; } char DiagnosticSeverityToType( CXDiagnosticSeverity severity ) { switch ( severity ) { case CXDiagnostic_Ignored: case CXDiagnostic_Note: return 'I'; case CXDiagnostic_Warning: return 'W'; case CXDiagnostic_Error: case CXDiagnostic_Fatal: return 'E'; default: return 'E'; } } // Returns true when the provided completion string is available to the user; // unavailable completion strings refer to entities that are private/protected, // deprecated etc. bool CompletionStringAvailable( CXCompletionString completion_string ) { if ( !completion_string ) return false; return clang_getCompletionAvailability( completion_string ) == CXAvailability_Available; } std::vector< Range > GetRanges( const DiagnosticWrap &diagnostic_wrap ) { std::vector< Range > ranges; uint num_ranges = clang_getDiagnosticNumRanges( diagnostic_wrap.get() ); ranges.reserve( num_ranges ); for ( uint i = 0; i < num_ranges; ++i ) { ranges.push_back( Range( clang_getDiagnosticRange( diagnostic_wrap.get(), i ) ) ); } return ranges; } Range GetLocationExtent( CXSourceLocation source_location, CXTranslationUnit translation_unit ) { // If you think the below code is an idiotic way of getting the source range // for an identifier at a specific source location, you are not the only one. // I cannot believe that this is the only way to achieve this with the // libclang API in a robust way. // I've tried many simpler ways of doing this and they all fail in various // situations. CXSourceRange range = clang_getCursorExtent( clang_getCursor( translation_unit, source_location ) ); CXToken *tokens; uint num_tokens; clang_tokenize( translation_unit, range, &tokens, &num_tokens ); Location location( source_location ); Range final_range; for ( uint i = 0; i < num_tokens; ++i ) { Location token_location( clang_getTokenLocation( translation_unit, tokens[ i ] ) ); if ( token_location == location ) { std::string name = CXStringToString( clang_getTokenSpelling( translation_unit, tokens[ i ] ) ); Location end_location = location; end_location.column_number_ += name.length(); final_range = Range( location, end_location ); break; } } clang_disposeTokens( translation_unit, tokens, num_tokens ); return final_range; } } // unnamed namespace std::vector< CXUnsavedFile > ToCXUnsavedFiles( const std::vector< UnsavedFile > &unsaved_files ) { std::vector< CXUnsavedFile > clang_unsaved_files( unsaved_files.size() ); for ( uint i = 0; i < unsaved_files.size(); ++i ) { clang_unsaved_files[ i ].Filename = unsaved_files[ i ].filename_.c_str(); clang_unsaved_files[ i ].Contents = unsaved_files[ i ].contents_.c_str(); clang_unsaved_files[ i ].Length = unsaved_files[ i ].length_; } return clang_unsaved_files; } std::vector< CompletionData > ToCompletionDataVector( CXCodeCompleteResults *results ) { std::vector< CompletionData > completions; if ( !results || !results->Results ) return completions; completions.reserve( results->NumResults ); unordered_map< std::string, uint > seen_data; for ( uint i = 0; i < results->NumResults; ++i ) { CXCompletionResult completion_result = results->Results[ i ]; if ( !CompletionStringAvailable( completion_result.CompletionString ) ) continue; CompletionData data( completion_result ); uint index = GetValueElseInsert( seen_data, data.original_string_, completions.size() ); if ( index == completions.size() ) { completions.push_back( boost::move( data ) ); } else { // If we have already seen this completion, then this is an overload of a // function we have seen. We add the signature of the overload to the // detailed information. completions[ index ].detailed_info_ .append( data.return_type_ ) .append( " " ) .append( data.everything_except_return_type_ ) .append( "\n" ); } } return completions; } Diagnostic BuildDiagnostic( DiagnosticWrap diagnostic_wrap, CXTranslationUnit translation_unit ) { Diagnostic diagnostic; if ( !diagnostic_wrap ) return diagnostic; diagnostic.kind_ = DiagnosticSeverityToType( clang_getDiagnosticSeverity( diagnostic_wrap.get() ) ); // If this is an "ignored" diagnostic, there's no point in continuing since we // won't display those to the user if ( diagnostic.kind_ == 'I' ) return diagnostic; CXSourceLocation source_location = clang_getDiagnosticLocation( diagnostic_wrap.get() ); diagnostic.location_ = Location( source_location ); diagnostic.location_extent_ = GetLocationExtent( source_location, translation_unit ); diagnostic.ranges_ = GetRanges( diagnostic_wrap ); diagnostic.text_ = CXStringToString( clang_getDiagnosticSpelling( diagnostic_wrap.get() ) ); diagnostic.long_formatted_text_ = FullDiagnosticText( diagnostic_wrap.get() ); return diagnostic; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangHelpers.h000066400000000000000000000031511227567565400263530ustar00rootroot00000000000000// 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 . #ifndef CLANGHELPERS_H_T3ME71LG #define CLANGHELPERS_H_T3ME71LG #include "Diagnostic.h" #include "CompletionData.h" #include "UnsavedFile.h" #include #include #include #include namespace YouCompleteMe { typedef boost::shared_ptr < boost::remove_pointer< CXDiagnostic >::type > DiagnosticWrap; std::vector< CompletionData > ToCompletionDataVector( CXCodeCompleteResults *results ); // NOTE: CXUnsavedFiles store pointers to data in UnsavedFiles, so UnsavedFiles // need to outlive CXUnsavedFiles! std::vector< CXUnsavedFile > ToCXUnsavedFiles( const std::vector< UnsavedFile > &unsaved_files ); Diagnostic BuildDiagnostic( DiagnosticWrap diagnostic_wrap, CXTranslationUnit translation_unit ); } // namespace YouCompleteMe #endif /* end of include guard: CLANGHELPERS_H_T3ME71LG */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangUtils.cpp000066400000000000000000000031421227567565400264040ustar00rootroot00000000000000// 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 . #include "ClangUtils.h" #include "standard.h" namespace YouCompleteMe { std::string CXStringToString( CXString text ) { std::string final_string; if ( !text.data ) return final_string; final_string = std::string( clang_getCString( text ) ); clang_disposeString( text ); return final_string; } bool CursorIsValid( CXCursor cursor ) { return !clang_Cursor_isNull( cursor ) && !clang_isInvalid( clang_getCursorKind( cursor ) ); } bool CursorIsReference( CXCursor cursor ) { return clang_isReference( clang_getCursorKind( cursor ) ); } bool CursorIsDeclaration( CXCursor cursor ) { return clang_isDeclaration( clang_getCursorKind( cursor ) ); } std::string CXFileToFilepath( CXFile file ) { return CXStringToString( clang_getFileName( file ) ); } std::string ClangVersion() { return CXStringToString( clang_getClangVersion() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/ClangUtils.h000066400000000000000000000022731227567565400260550ustar00rootroot00000000000000// 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 . #ifndef CLANGUTILS_H_9MVHQLJS #define CLANGUTILS_H_9MVHQLJS #include #include namespace YouCompleteMe { std::string CXStringToString( CXString text ); bool CursorIsValid( CXCursor cursor ); bool CursorIsReference( CXCursor cursor ); bool CursorIsDeclaration( CXCursor cursor ); std::string CXFileToFilepath( CXFile file ); std::string ClangVersion(); } // namespace YouCompleteMe #endif /* end of include guard: CLANGUTILS_H_9MVHQLJS */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/CompilationDatabase.cpp000066400000000000000000000061441227567565400302470ustar00rootroot00000000000000// 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 . #include "CompilationDatabase.h" #include "ClangUtils.h" #include "standard.h" #include "ReleaseGil.h" #include #include #include #include using boost::lock_guard; using boost::unique_lock; using boost::try_to_lock_t; using boost::remove_pointer; using boost::shared_ptr; using boost::mutex; namespace YouCompleteMe { typedef shared_ptr < remove_pointer< CXCompileCommands >::type > CompileCommandsWrap; CompilationDatabase::CompilationDatabase( const std::string &path_to_directory ) : is_loaded_( false ) { CXCompilationDatabase_Error status; compilation_database_ = clang_CompilationDatabase_fromDirectory( path_to_directory.c_str(), &status ); is_loaded_ = status == CXCompilationDatabase_NoError; } CompilationDatabase::~CompilationDatabase() { clang_CompilationDatabase_dispose( compilation_database_ ); } bool CompilationDatabase::DatabaseSuccessfullyLoaded() { return is_loaded_; } bool CompilationDatabase::AlreadyGettingFlags() { unique_lock< mutex > lock( compilation_database_mutex_, try_to_lock_t() ); return !lock.owns_lock(); } CompilationInfoForFile CompilationDatabase::GetCompilationInfoForFile( const std::string &path_to_file ) { ReleaseGil unlock; CompilationInfoForFile info; if ( !is_loaded_ ) return info; lock_guard< mutex > lock( compilation_database_mutex_ ); CompileCommandsWrap commands( clang_CompilationDatabase_getCompileCommands( compilation_database_, path_to_file.c_str() ), clang_CompileCommands_dispose ); uint num_commands = clang_CompileCommands_getSize( commands.get() ); if ( num_commands < 1 ) { return info; } // We always pick the first command offered CXCompileCommand command = clang_CompileCommands_getCommand( commands.get(), 0 ); info.compiler_working_dir_ = CXStringToString( clang_CompileCommand_getDirectory( command ) ); uint num_flags = clang_CompileCommand_getNumArgs( command ); info.compiler_flags_.reserve( num_flags ); for ( uint i = 0; i < num_flags; ++i ) { info.compiler_flags_.push_back( CXStringToString( clang_CompileCommand_getArg( command, i ) ) ); } return info; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/CompilationDatabase.h000066400000000000000000000037251227567565400277160ustar00rootroot00000000000000// 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 . #ifndef COMPILATIONDATABASE_H_ZT7MQXPG #define COMPILATIONDATABASE_H_ZT7MQXPG #include #include #include #include #include #include namespace YouCompleteMe { struct CompilationInfoForFile { std::vector< std::string > compiler_flags_; std::string compiler_working_dir_; }; // Access to Clang's internal CompilationDatabase. This class is thread-safe. class CompilationDatabase : boost::noncopyable { public: CompilationDatabase( const std::string &path_to_directory ); ~CompilationDatabase(); bool DatabaseSuccessfullyLoaded(); // Returns true when a separate thread is already getting flags; this is // useful so that the caller doesn't need to block. bool AlreadyGettingFlags(); // NOTE: Multiple calls to this function from separate threads will be // serialized since Clang internals are not thread-safe. CompilationInfoForFile GetCompilationInfoForFile( const std::string &path_to_file ); private: bool is_loaded_; CXCompilationDatabase compilation_database_; boost::mutex compilation_database_mutex_; }; } // namespace YouCompleteMe #endif /* end of include guard: COMPILATIONDATABASE_H_ZT7MQXPG */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/CompletionData.cpp000066400000000000000000000161401227567565400272440ustar00rootroot00000000000000// 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 . #include "CompletionData.h" #include "ClangUtils.h" #include #include namespace { char CursorKindToVimKind( CXCursorKind kind ) { switch ( kind ) { case CXCursor_StructDecl: return 's'; case CXCursor_ClassDecl: case CXCursor_ClassTemplate: return 'c'; case CXCursor_EnumDecl: return 'e'; case CXCursor_UnexposedDecl: case CXCursor_UnionDecl: case CXCursor_TypedefDecl: return 't'; case CXCursor_FieldDecl: return 'm'; case CXCursor_FunctionDecl: case CXCursor_CXXMethod: case CXCursor_FunctionTemplate: case CXCursor_ConversionFunction: case CXCursor_Constructor: case CXCursor_Destructor: return 'f'; case CXCursor_VarDecl: return 'v'; case CXCursor_MacroDefinition: return 'd'; case CXCursor_ParmDecl: return 'p'; case CXCursor_Namespace: case CXCursor_NamespaceAlias: return 'n'; default: return 'u'; // for 'unknown', 'unsupported'... whatever you like } } bool IsMainCompletionTextInfo( CXCompletionChunkKind kind ) { return kind == CXCompletionChunk_Optional || kind == CXCompletionChunk_TypedText || kind == CXCompletionChunk_Placeholder || kind == CXCompletionChunk_LeftParen || kind == CXCompletionChunk_RightParen || kind == CXCompletionChunk_RightBracket || kind == CXCompletionChunk_LeftBracket || kind == CXCompletionChunk_LeftBrace || kind == CXCompletionChunk_RightBrace || kind == CXCompletionChunk_RightAngle || kind == CXCompletionChunk_LeftAngle || kind == CXCompletionChunk_Comma || kind == CXCompletionChunk_Colon || kind == CXCompletionChunk_SemiColon || kind == CXCompletionChunk_Equal || kind == CXCompletionChunk_Informative || kind == CXCompletionChunk_HorizontalSpace; } std::string ChunkToString( CXCompletionString completion_string, uint chunk_num ) { if ( !completion_string ) return std::string(); return YouCompleteMe::CXStringToString( clang_getCompletionChunkText( completion_string, chunk_num ) ); } std::string OptionalChunkToString( CXCompletionString completion_string, uint chunk_num ) { std::string final_string; if ( !completion_string ) return final_string; CXCompletionString optional_completion_string = clang_getCompletionChunkCompletionString( completion_string, chunk_num ); if ( !optional_completion_string ) return final_string; uint optional_num_chunks = clang_getNumCompletionChunks( optional_completion_string ); for ( uint j = 0; j < optional_num_chunks; ++j ) { CXCompletionChunkKind kind = clang_getCompletionChunkKind( optional_completion_string, j ); if ( kind == CXCompletionChunk_Optional ) { final_string.append( OptionalChunkToString( optional_completion_string, j ) ); } else { final_string.append( ChunkToString( optional_completion_string, j ) ); } } return final_string; } // NOTE: this function accepts the text param by value on purpose; it internally // needs a copy before processing the text so the copy might as well be made on // the parameter BUT if this code is compiled in C++11 mode a move constructor // can be called on the passed-in value. This is not possible if we accept the // param by const ref. std::string RemoveTwoConsecutiveUnderscores( std::string text ) { boost::erase_all( text, "__" ); return text; } } // unnamed namespace namespace YouCompleteMe { CompletionData::CompletionData( const CXCompletionResult &completion_result ) { CXCompletionString completion_string = completion_result.CompletionString; if ( !completion_string ) return; uint num_chunks = clang_getNumCompletionChunks( completion_string ); bool saw_left_paren = false; bool saw_function_params = false; for ( uint j = 0; j < num_chunks; ++j ) { ExtractDataFromChunk( completion_string, j, saw_left_paren, saw_function_params ); } kind_ = CursorKindToVimKind( completion_result.CursorKind ); // We remove any two consecutive underscores from the function definition // since identifiers with them are ugly, compiler-reserved names. Functions // from the standard library use parameter names like "__pos" and we want to // show them as just "pos". This will never interfere with client code since // ANY C++ identifier with two consecutive underscores in it is // compiler-reserved. everything_except_return_type_ = RemoveTwoConsecutiveUnderscores( boost::move( everything_except_return_type_ ) ); detailed_info_.append( return_type_ ) .append( " " ) .append( everything_except_return_type_ ) .append( "\n" ); } void CompletionData::ExtractDataFromChunk( CXCompletionString completion_string, uint chunk_num, bool &saw_left_paren, bool &saw_function_params ) { CXCompletionChunkKind kind = clang_getCompletionChunkKind( completion_string, chunk_num ); if ( IsMainCompletionTextInfo( kind ) ) { if ( kind == CXCompletionChunk_LeftParen ) { saw_left_paren = true; } else if ( saw_left_paren && !saw_function_params && kind != CXCompletionChunk_RightParen && kind != CXCompletionChunk_Informative ) { saw_function_params = true; everything_except_return_type_.append( " " ); } else if ( saw_function_params && kind == CXCompletionChunk_RightParen ) { everything_except_return_type_.append( " " ); } if ( kind == CXCompletionChunk_Optional ) { everything_except_return_type_.append( OptionalChunkToString( completion_string, chunk_num ) ); } else { everything_except_return_type_.append( ChunkToString( completion_string, chunk_num ) ); } } if ( kind == CXCompletionChunk_ResultType ) return_type_ = ChunkToString( completion_string, chunk_num ); if ( kind == CXCompletionChunk_TypedText ) original_string_ = ChunkToString( completion_string, chunk_num ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/CompletionData.h000066400000000000000000000077261227567565400267230ustar00rootroot00000000000000// 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 . #ifndef COMPLETIONDATA_H_2JCTF1NU #define COMPLETIONDATA_H_2JCTF1NU #include "standard.h" #include #include namespace YouCompleteMe { // This class holds pieces of information about a single completion coming from // clang. These pieces are shown in Vim's UI in different ways. // // Normally, the completion menu looks like this (without square brackets): // // [main completion text] [kind] [extra menu info] // [main completion text] [kind] [extra menu info] // [main completion text] [kind] [extra menu info] // ... (etc.) ... // // The user can also enable a "preview" window that will show extra information // about a completion at the top of the buffer. struct CompletionData { CompletionData() {} CompletionData( const CXCompletionResult &completion_result ); // What should actually be inserted into the buffer. For a function like // "int foo(int x)", this is just "foo". Same for a data member like "foo_": // we insert just "foo_". std::string TextToInsertInBuffer() { return original_string_; } // Currently, here we show the full function signature (without the return // type) if the current completion is a function or just the raw TypedText if // the completion is, say, a data member. So for a function like "int foo(int // x)", this would be "foo(int x)". For a data member like "count_", it would // be just "count_". std::string MainCompletionText() { return everything_except_return_type_; } // This is extra info shown in the pop-up completion menu, after the // completion text and the kind. Currently we put the return type of the // function here, if any. std::string ExtraMenuInfo() { return return_type_; } // This is used to show extra information in vim's preview window. This is the // window that vim usually shows at the top of the buffer. This should be used // for extra information about the completion. std::string DetailedInfoForPreviewWindow() { return detailed_info_; } bool operator== ( const CompletionData &other ) const { return kind_ == other.kind_ && everything_except_return_type_ == other.everything_except_return_type_ && return_type_ == other.return_type_ && original_string_ == other.original_string_; // detailed_info_ doesn't matter } std::string detailed_info_; std::string return_type_; // Vim's completion string "kind" // 'v' -> variable // 'f' -> function or method // 'm' -> member of struct/class (data member) // 't' -> typedef (but we're going to use it for types in general) // 'd' -> #define or macro char kind_; // The original, raw completion string. For a function like "int foo(int x)", // the original string is "foo". For a member data variable like "foo_", this // is just "foo_". This corresponds to clang's TypedText chunk of the // completion string. std::string original_string_; std::string everything_except_return_type_; private: void ExtractDataFromChunk( CXCompletionString completion_string, uint chunk_num, bool &saw_left_paren, bool &saw_function_params ); }; } // namespace YouCompleteMe #endif /* end of include guard: COMPLETIONDATA_H_2JCTF1NU */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/Diagnostic.h000066400000000000000000000026511227567565400260740ustar00rootroot00000000000000// 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 . #ifndef DIAGNOSTIC_H_BZH3BWIZ #define DIAGNOSTIC_H_BZH3BWIZ #include "standard.h" #include "Range.h" #include "Location.h" #include #include namespace YouCompleteMe { struct Diagnostic { bool operator== ( const Diagnostic &other ) const { return location_ == other.location_ && kind_ == other.kind_ && text_ == other.text_; } Location location_; Range location_extent_; std::vector< Range > ranges_; // Vim's error "kind" // 'I' -> informational // 'W' -> warning // 'E' -> error char kind_; std::string text_; std::string long_formatted_text_; }; } // namespace YouCompleteMe #endif /* end of include guard: DIAGNOSTIC_H_BZH3BWIZ */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/Location.h000066400000000000000000000037401227567565400255600ustar00rootroot00000000000000// 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 . #ifndef LOCATION_H_6TLFQH4I #define LOCATION_H_6TLFQH4I #include "standard.h" #include "ClangUtils.h" #include #include namespace YouCompleteMe { struct Location { // Creates an invalid location Location() : line_number_( 0 ), column_number_( 0 ), filename_( "" ) {} Location( const std::string &filename, uint line, uint column ) : line_number_( line ), column_number_( column ), filename_( filename ) {} Location( const CXSourceLocation &location ) { CXFile file; uint unused_offset; clang_getExpansionLocation( location, &file, &line_number_, &column_number_, &unused_offset ); filename_ = CXFileToFilepath( file ); } bool operator== ( const Location &other ) const { return line_number_ == other.line_number_ && column_number_ == other.column_number_ && filename_ == other.filename_; } bool IsValid() { return !filename_.empty(); } uint line_number_; uint column_number_; // The full, absolute path std::string filename_; }; } // namespace YouCompleteMe #endif /* end of include guard: LOCATION_H_6TLFQH4I */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/Range.cpp000066400000000000000000000017251227567565400254000ustar00rootroot00000000000000// 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 . #include "Range.h" #include "ClangUtils.h" namespace YouCompleteMe { Range::Range( const CXSourceRange &range ) { start_ = Location( clang_getRangeStart( range ) ); end_ = Location( clang_getRangeEnd( range ) ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/Range.h000066400000000000000000000024531227567565400250440ustar00rootroot00000000000000// 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 . #ifndef RANGE_H_4MFTIGQK #define RANGE_H_4MFTIGQK #include "standard.h" #include "Location.h" namespace YouCompleteMe { // Half-open, [start, end> struct Range { Range() {} Range( const Location &start_location, const Location &end_location ) : start_( start_location ), end_( end_location ) {} Range( const CXSourceRange &range ); bool operator== ( const Range &other ) const { return start_ == other.start_ && end_ == other.end_; } Location start_; Location end_; }; } // namespace YouCompleteMe #endif /* end of include guard: RANGE_H_4MFTIGQK */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/TranslationUnit.cpp000066400000000000000000000226161227567565400275040ustar00rootroot00000000000000// 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 . #include "TranslationUnit.h" #include "CompletionData.h" #include "standard.h" #include "exceptions.h" #include "ClangUtils.h" #include "ClangHelpers.h" #include #include using boost::unique_lock; using boost::mutex; using boost::try_to_lock_t; using boost::shared_ptr; using boost::remove_pointer; namespace YouCompleteMe { typedef shared_ptr < remove_pointer< CXCodeCompleteResults >::type > CodeCompleteResultsWrap; TranslationUnit::TranslationUnit() : filename_( "" ), clang_translation_unit_( NULL ) { } TranslationUnit::TranslationUnit( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags, CXIndex clang_index ) : filename_( filename ), clang_translation_unit_( NULL ) { std::vector< const char * > pointer_flags; pointer_flags.reserve( flags.size() ); foreach ( const std::string & flag, flags ) { pointer_flags.push_back( flag.c_str() ); } std::vector< CXUnsavedFile > cxunsaved_files = ToCXUnsavedFiles( unsaved_files ); const CXUnsavedFile *unsaved = cxunsaved_files.size() > 0 ? &cxunsaved_files[ 0 ] : NULL; clang_translation_unit_ = clang_parseTranslationUnit( clang_index, filename.c_str(), &pointer_flags[ 0 ], pointer_flags.size(), const_cast( unsaved ), cxunsaved_files.size(), clang_defaultEditingTranslationUnitOptions() ); if ( !clang_translation_unit_ ) boost_throw( ClangParseError() ); // Only with a reparse is the preable precompiled. I do not know why... // TODO: report this bug on the clang tracker Reparse( cxunsaved_files ); } TranslationUnit::~TranslationUnit() { Destroy(); } void TranslationUnit::Destroy() { unique_lock< mutex > lock( clang_access_mutex_ ); if ( clang_translation_unit_ ) { clang_disposeTranslationUnit( clang_translation_unit_ ); clang_translation_unit_ = NULL; } } std::vector< Diagnostic > TranslationUnit::LatestDiagnostics() { if ( !clang_translation_unit_ ) return std::vector< Diagnostic >(); unique_lock< mutex > lock( diagnostics_mutex_ ); return latest_diagnostics_; } bool TranslationUnit::IsCurrentlyUpdating() const { // We return true when the TU is invalid; an invalid TU also acts a sentinel, // preventing other threads from trying to use it. if ( !clang_translation_unit_ ) return true; unique_lock< mutex > lock( clang_access_mutex_, try_to_lock_t() ); return !lock.owns_lock(); } std::vector< Diagnostic > TranslationUnit::Reparse( const std::vector< UnsavedFile > &unsaved_files ) { std::vector< CXUnsavedFile > cxunsaved_files = ToCXUnsavedFiles( unsaved_files ); Reparse( cxunsaved_files ); unique_lock< mutex > lock( diagnostics_mutex_ ); return latest_diagnostics_; } void TranslationUnit::ReparseForIndexing( const std::vector< UnsavedFile > &unsaved_files ) { std::vector< CXUnsavedFile > cxunsaved_files = ToCXUnsavedFiles( unsaved_files ); Reparse( cxunsaved_files, CXTranslationUnit_PrecompiledPreamble | CXTranslationUnit_SkipFunctionBodies ); } std::vector< CompletionData > TranslationUnit::CandidatesForLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ) { unique_lock< mutex > lock( clang_access_mutex_ ); if ( !clang_translation_unit_ ) return std::vector< CompletionData >(); std::vector< CXUnsavedFile > cxunsaved_files = ToCXUnsavedFiles( unsaved_files ); const CXUnsavedFile *unsaved = cxunsaved_files.size() > 0 ? &cxunsaved_files[ 0 ] : NULL; // codeCompleteAt reparses the TU if the underlying source file has changed on // disk since the last time the TU was updated and there are no unsaved files. // If there are unsaved files, then codeCompleteAt will parse the in-memory // file contents we are giving it. In short, it is NEVER a good idea to call // clang_reparseTranslationUnit right before a call to clang_codeCompleteAt. // This only makes clang reparse the whole file TWICE, which has a huge impact // on latency. At the time of writing, it seems that most users of libclang // in the open-source world don't realize this (I checked). Some don't even // call reparse*, but parse* which is even less efficient. CodeCompleteResultsWrap results( clang_codeCompleteAt( clang_translation_unit_, filename_.c_str(), line, column, const_cast( unsaved ), cxunsaved_files.size(), clang_defaultCodeCompleteOptions() ), clang_disposeCodeCompleteResults ); std::vector< CompletionData > candidates = ToCompletionDataVector( results.get() ); return candidates; } Location TranslationUnit::GetDeclarationLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ) { ReparseForIndexing( unsaved_files ); unique_lock< mutex > lock( clang_access_mutex_ ); if ( !clang_translation_unit_ ) return Location(); CXCursor cursor = GetCursor( line, column ); if ( !CursorIsValid( cursor ) ) return Location(); CXCursor referenced_cursor = clang_getCursorReferenced( cursor ); if ( !CursorIsValid( referenced_cursor ) ) return Location(); return Location( clang_getCursorLocation( referenced_cursor ) ); } Location TranslationUnit::GetDefinitionLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ) { ReparseForIndexing( unsaved_files ); unique_lock< mutex > lock( clang_access_mutex_ ); if ( !clang_translation_unit_ ) return Location(); CXCursor cursor = GetCursor( line, column ); if ( !CursorIsValid( cursor ) ) return Location(); CXCursor definition_cursor = clang_getCursorDefinition( cursor ); if ( !CursorIsValid( definition_cursor ) ) return Location(); return Location( clang_getCursorLocation( definition_cursor ) ); } // Argument taken as non-const ref because we need to be able to pass a // non-const pointer to clang. This function (and clang too) will not modify the // param though. void TranslationUnit::Reparse( std::vector< CXUnsavedFile > &unsaved_files ) { Reparse( unsaved_files, clang_defaultEditingTranslationUnitOptions() ); } // Argument taken as non-const ref because we need to be able to pass a // non-const pointer to clang. This function (and clang too) will not modify the // param though. void TranslationUnit::Reparse( std::vector< CXUnsavedFile > &unsaved_files, uint parse_options ) { int failure = 0; { unique_lock< mutex > lock( clang_access_mutex_ ); if ( !clang_translation_unit_ ) return; CXUnsavedFile *unsaved = unsaved_files.size() > 0 ? &unsaved_files[ 0 ] : NULL; failure = clang_reparseTranslationUnit( clang_translation_unit_, unsaved_files.size(), unsaved, parse_options ); } if ( failure ) { Destroy(); boost_throw( ClangParseError() ); } UpdateLatestDiagnostics(); } void TranslationUnit::UpdateLatestDiagnostics() { unique_lock< mutex > lock1( clang_access_mutex_ ); unique_lock< mutex > lock2( diagnostics_mutex_ ); latest_diagnostics_.clear(); uint num_diagnostics = clang_getNumDiagnostics( clang_translation_unit_ ); latest_diagnostics_.reserve( num_diagnostics ); for ( uint i = 0; i < num_diagnostics; ++i ) { Diagnostic diagnostic = BuildDiagnostic( DiagnosticWrap( clang_getDiagnostic( clang_translation_unit_, i ), clang_disposeDiagnostic ), clang_translation_unit_ ); if ( diagnostic.kind_ != 'I' ) latest_diagnostics_.push_back( diagnostic ); } } CXCursor TranslationUnit::GetCursor( int line, int column ) { // ASSUMES A LOCK IS ALREADY HELD ON clang_access_mutex_! if ( !clang_translation_unit_ ) return clang_getNullCursor(); CXFile file = clang_getFile( clang_translation_unit_, filename_.c_str() ); CXSourceLocation source_location = clang_getLocation( clang_translation_unit_, file, line, column ); return clang_getCursor( clang_translation_unit_, source_location ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/TranslationUnit.h000066400000000000000000000055501227567565400271470ustar00rootroot00000000000000// 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 . #ifndef TRANSLATIONUNIT_H_XQ7I6SVA #define TRANSLATIONUNIT_H_XQ7I6SVA #include "UnsavedFile.h" #include "Diagnostic.h" #include "Location.h" #include #include #include #include #include namespace YouCompleteMe { struct CompletionData; typedef boost::shared_ptr< std::vector< CompletionData > > AsyncCompletions; class TranslationUnit : boost::noncopyable { public: // This constructor creates an invalid, sentinel TU. All of it's methods // return empty vectors, and IsCurrentlyUpdating always returns true so that // no callers try to rely on the invalid TU. TranslationUnit(); TranslationUnit( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags, CXIndex clang_index ); ~TranslationUnit(); void Destroy(); std::vector< Diagnostic > LatestDiagnostics(); bool IsCurrentlyUpdating() const; std::vector< Diagnostic > Reparse( const std::vector< UnsavedFile > &unsaved_files ); void ReparseForIndexing( const std::vector< UnsavedFile > &unsaved_files ); std::vector< CompletionData > CandidatesForLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ); Location GetDeclarationLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ); Location GetDefinitionLocation( int line, int column, const std::vector< UnsavedFile > &unsaved_files ); private: void Reparse( std::vector< CXUnsavedFile > &unsaved_files ); void Reparse( std::vector< CXUnsavedFile > &unsaved_files, uint parse_options ); void UpdateLatestDiagnostics(); CXCursor GetCursor( int line, int column ); ///////////////////////////// // PRIVATE MEMBER VARIABLES ///////////////////////////// std::string filename_; boost::mutex diagnostics_mutex_; std::vector< Diagnostic > latest_diagnostics_; mutable boost::mutex clang_access_mutex_; CXTranslationUnit clang_translation_unit_; }; } // namespace YouCompleteMe #endif /* end of include guard: TRANSLATIONUNIT_H_XQ7I6SVA */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/TranslationUnitStore.cpp000066400000000000000000000104361227567565400305160ustar00rootroot00000000000000// 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 . #include "TranslationUnitStore.h" #include "TranslationUnit.h" #include "Utils.h" #include "exceptions.h" #include #include #include using boost::lock_guard; using boost::shared_ptr; using boost::make_shared; using boost::mutex; namespace YouCompleteMe { namespace { std::size_t HashForFlags( const std::vector< std::string > &flags ) { return boost::hash< std::vector< std::string > >()( flags ); } } // unnamed namespace TranslationUnitStore::TranslationUnitStore( CXIndex clang_index ) : clang_index_( clang_index ) { } TranslationUnitStore::~TranslationUnitStore() { RemoveAll(); } shared_ptr< TranslationUnit > TranslationUnitStore::GetOrCreate( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ) { bool dont_care; return GetOrCreate( filename, unsaved_files, flags, dont_care ); } shared_ptr< TranslationUnit > TranslationUnitStore::GetOrCreate( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags, bool &translation_unit_created ) { translation_unit_created = false; { lock_guard< mutex > lock( filename_to_translation_unit_and_flags_mutex_ ); shared_ptr< TranslationUnit > current_unit = GetNoLock( filename ); if ( current_unit && HashForFlags( flags ) == filename_to_flags_hash_[ filename ] ) { return current_unit; } // We create and store an invalid, sentinel TU so that other threads don't // try to create a TU for the same file while we are trying to create this // TU object. When we are done creating the TU, we will overwrite this value // with the valid object. filename_to_translation_unit_[ filename ] = make_shared< TranslationUnit >(); // We need to store the flags for the sentinel TU so that other threads end // up returning the sentinel TU while the real one is being created. filename_to_flags_hash_[ filename ] = HashForFlags( flags ); } boost::shared_ptr< TranslationUnit > unit; try { unit = boost::make_shared< TranslationUnit >( filename, unsaved_files, flags, clang_index_ ); } catch ( ClangParseError & ) { Remove( filename ); return unit; } { lock_guard< mutex > lock( filename_to_translation_unit_and_flags_mutex_ ); filename_to_translation_unit_[ filename ] = unit; // Flags have already been stored. } translation_unit_created = true; return unit; } shared_ptr< TranslationUnit > TranslationUnitStore::Get( const std::string &filename ) { lock_guard< mutex > lock( filename_to_translation_unit_and_flags_mutex_ ); return GetNoLock( filename ); } bool TranslationUnitStore::Remove( const std::string &filename ) { lock_guard< mutex > lock( filename_to_translation_unit_and_flags_mutex_ ); Erase( filename_to_flags_hash_, filename ); return Erase( filename_to_translation_unit_, filename ); } void TranslationUnitStore::RemoveAll() { lock_guard< mutex > lock( filename_to_translation_unit_and_flags_mutex_ ); filename_to_translation_unit_.clear(); filename_to_flags_hash_.clear(); } shared_ptr< TranslationUnit > TranslationUnitStore::GetNoLock( const std::string &filename ) { return FindWithDefault( filename_to_translation_unit_, filename, shared_ptr< TranslationUnit >() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/TranslationUnitStore.h000066400000000000000000000054401227567565400301620ustar00rootroot00000000000000// 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 . #ifndef TRANSLATIONUNITSTORE_H_NGN0MCKB #define TRANSLATIONUNITSTORE_H_NGN0MCKB #include "TranslationUnit.h" #include "UnsavedFile.h" #include #include #include #include #include #include typedef void *CXIndex; namespace YouCompleteMe { class TranslationUnitStore : boost::noncopyable { public: TranslationUnitStore( CXIndex clang_index ); ~TranslationUnitStore(); // You can even call this function for the same filename from multiple // threads; the TU store will ensure only one TU is created. boost::shared_ptr< TranslationUnit > GetOrCreate( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags ); boost::shared_ptr< TranslationUnit > GetOrCreate( const std::string &filename, const std::vector< UnsavedFile > &unsaved_files, const std::vector< std::string > &flags, bool &translation_unit_created ); // Careful here! While GetOrCreate makes sure to take into account the flags // for the file before returning a stored TU (if the flags changed, the TU is // not really valid anymore and a new one should be built), this function does // not. You might end up getting a stale TU. boost::shared_ptr< TranslationUnit > Get( const std::string &filename ); bool Remove( const std::string &filename ); void RemoveAll(); private: // WARNING: This accesses filename_to_translation_unit_ without a lock! boost::shared_ptr< TranslationUnit > GetNoLock( const std::string &filename ); typedef boost::unordered_map < std::string, boost::shared_ptr< TranslationUnit > > TranslationUnitForFilename; typedef boost::unordered_map < std::string, std::size_t > FlagsHashForFilename; CXIndex clang_index_; TranslationUnitForFilename filename_to_translation_unit_; FlagsHashForFilename filename_to_flags_hash_; boost::mutex filename_to_translation_unit_and_flags_mutex_; }; } // namespace YouCompleteMe #endif // TRANSLATIONUNITSTORE_H_NGN0MCKB vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ClangCompleter/UnsavedFile.h000066400000000000000000000027351227567565400262200ustar00rootroot00000000000000// 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 . #ifndef UNSAVEDFILE_H_0GIYZQL4 #define UNSAVEDFILE_H_0GIYZQL4 #include struct UnsavedFile { UnsavedFile() : filename_( "" ), contents_( "" ), length_( 0 ) {} std::string filename_; std::string contents_; unsigned long length_; // We need this to be able to export this struct to Python via Boost.Python's // methods. I have no clue why, but it won't compile without it. // TODO: report this problem on the Boost bug tracker, the default equality // operator should be more than adequate here bool operator== ( const UnsavedFile &other ) const { return filename_ == other.filename_ && contents_ == other.contents_ && length_ == other.length_; } }; #endif /* end of include guard: UNSAVEDFILE_H_0GIYZQL4 */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/CustomAssert.cpp000066400000000000000000000060021227567565400240720ustar00rootroot00000000000000/* * Copyright (c) 2008, Power of Two Games LLC * 2013, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Power of Two Games LLC nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY POWER OF TWO GAMES LLC ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL POWER OF TWO GAMES LLC 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. */ #include "CustomAssert.h" #include #include namespace assert_ns { namespace { Assert::FailBehavior DefaultHandler(const char* condition, const char* msg, const char* file, const int line) { std::printf("%s(%d): Assert Failure: ", file, line); if (condition != NULL) std::printf("'%s' ", condition); if (msg != NULL) std::printf("%s", msg); std::printf("\n"); return Assert::Halt; } Assert::Handler& GetAssertHandlerInstance() { static Assert::Handler s_handler = &DefaultHandler; return s_handler; } } Assert::Handler Assert::GetHandler() { return GetAssertHandlerInstance(); } void Assert::SetHandler(Assert::Handler newHandler) { GetAssertHandlerInstance() = newHandler; } Assert::FailBehavior Assert::ReportFailure(const char* condition, const char* file, const int line, const char* msg, ...) { const char* message = NULL; if (msg != NULL) { char messageBuffer[1024]; { va_list args; va_start(args, msg); #if defined(_MSC_VER) vsnprintf_s(messageBuffer, 1024, 1024, msg, args); #else vsnprintf(messageBuffer, 1024, msg, args); #endif va_end(args); } message = messageBuffer; } return GetAssertHandlerInstance()(condition, message, file, line); } } vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/CustomAssert.h000066400000000000000000000072261227567565400235500ustar00rootroot00000000000000/* * Copyright (c) 2008, Power of Two Games LLC * 2013, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Power of Two Games LLC nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY POWER OF TWO GAMES LLC ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL POWER OF TWO GAMES LLC 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. */ #ifndef CUSTOM_ASSERT_H #define CUSTOM_ASSERT_H namespace assert_ns { namespace Assert { enum FailBehavior { Halt, Continue, }; typedef FailBehavior (*Handler)(const char* condition, const char* msg, const char* file, int line); Handler GetHandler(); void SetHandler(Handler newHandler); FailBehavior ReportFailure(const char* condition, const char* file, int line, const char* msg, ...); }} #if defined(_MSC_VER) # define X_HALT() __debugbreak() #elif defined(__GNUC__) || defined(__clang__) # define X_HALT() __builtin_trap() #else # define X_HALT() exit(__LINE__) #endif #define X_UNUSED(x) do { (void)sizeof(x); } while(0) #ifndef NDEBUG #define X_ASSERT(cond) \ do \ { \ if (!(cond)) \ { \ if (assert_ns::Assert::ReportFailure(#cond, __FILE__, __LINE__, 0) == \ assert_ns::Assert::Halt) \ X_HALT(); \ } \ } while(0) #define X_ASSERT_MSG(cond, msg, ...) \ do \ { \ if (!(cond)) \ { \ if (assert_ns::Assert::ReportFailure(#cond, __FILE__, __LINE__, (msg), __VA_ARGS__) == \ assert_ns::Assert::Halt) \ X_HALT(); \ } \ } while(0) #define X_ASSERT_FAIL(msg, ...) \ do \ { \ if (assert_ns::Assert::ReportFailure(0, __FILE__, __LINE__, (msg), __VA_ARGS__) == \ assert_ns::Assert::Halt) \ X_HALT(); \ } while(0) #define X_VERIFY(cond) X_ASSERT(cond) #define X_VERIFY_MSG(cond, msg, ...) X_ASSERT_MSG(cond, msg, ##__VA_ARGS__) #else #define X_ASSERT(condition) \ do { X_UNUSED(condition); } while(0) #define X_ASSERT_MSG(condition, msg, ...) \ do { X_UNUSED(condition); X_UNUSED(msg); } while(0) #define X_ASSERT_FAIL(msg, ...) \ do { X_UNUSED(msg); } while(0) #define X_VERIFY(cond) (void)(cond) #define X_VERIFY_MSG(cond, msg, ...) \ do { (void)(cond); X_UNUSED(msg); } while(0) #endif #define X_STATIC_ASSERT(x) \ typedef char StaticAssert[(x) ? 1 : -1]; #endif // CUSTOM_ASSERT_H vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierCompleter.cpp000066400000000000000000000063341227567565400254030ustar00rootroot00000000000000// 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 . #include "IdentifierCompleter.h" #include "standard.h" #include "Candidate.h" #include "IdentifierUtils.h" #include "Result.h" #include "Utils.h" #include "ReleaseGil.h" #include namespace YouCompleteMe { IdentifierCompleter::IdentifierCompleter() {} IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates ) { identifier_database_.AddIdentifiers( candidates, "", "" ); } IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates, const std::string &filetype, const std::string &filepath ) { identifier_database_.AddIdentifiers( candidates, filetype, filepath ); } void IdentifierCompleter::AddIdentifiersToDatabase( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ) { ReleaseGil unlock; identifier_database_.AddIdentifiers( new_candidates, filetype, filepath ); } void IdentifierCompleter::AddIdentifiersToDatabaseFromTagFiles( const std::vector< std::string > &absolute_paths_to_tag_files ) { ReleaseGil unlock; foreach( const std::string & path, absolute_paths_to_tag_files ) { identifier_database_.AddIdentifiers( ExtractIdentifiersFromTagsFile( path ) ); } } void IdentifierCompleter::AddIdentifiersToDatabaseFromBuffer( const std::string &buffer_contents, const std::string &filetype, const std::string &filepath, bool collect_from_comments_and_strings ) { ReleaseGil unlock; identifier_database_.ClearCandidatesStoredForFile( filetype, filepath ); std::string new_contents = collect_from_comments_and_strings ? buffer_contents : RemoveIdentifierFreeText( buffer_contents ); identifier_database_.AddIdentifiers( ExtractIdentifiersFromText( new_contents ), filetype, filepath ); } std::vector< std::string > IdentifierCompleter::CandidatesForQuery( const std::string &query ) const { return CandidatesForQueryAndType( query, "" ); } std::vector< std::string > IdentifierCompleter::CandidatesForQueryAndType( const std::string &query, const std::string &filetype ) const { ReleaseGil unlock; std::vector< Result > results; identifier_database_.ResultsForQueryAndType( query, filetype, results ); std::vector< std::string > candidates; candidates.reserve( results.size() ); foreach ( const Result & result, results ) { candidates.push_back( *result.Text() ); } return candidates; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierCompleter.h000066400000000000000000000044211227567565400250430ustar00rootroot00000000000000// 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 . #ifndef COMPLETER_H_7AR4UGXE #define COMPLETER_H_7AR4UGXE #include "IdentifierDatabase.h" #include #include #include #include #include #include namespace YouCompleteMe { class Candidate; class IdentifierCompleter : boost::noncopyable { public: IdentifierCompleter(); IdentifierCompleter( const std::vector< std::string > &candidates ); IdentifierCompleter( const std::vector< std::string > &candidates, const std::string &filetype, const std::string &filepath ); void AddIdentifiersToDatabase( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ); void AddIdentifiersToDatabaseFromTagFiles( const std::vector< std::string > &absolute_paths_to_tag_files ); void AddIdentifiersToDatabaseFromBuffer( const std::string &buffer_contents, const std::string &filetype, const std::string &filepath, bool collect_from_comments_and_strings ); // Only provided for tests! std::vector< std::string > CandidatesForQuery( const std::string &query ) const; std::vector< std::string > CandidatesForQueryAndType( const std::string &query, const std::string &filetype ) const; private: ///////////////////////////// // PRIVATE MEMBER VARIABLES ///////////////////////////// IdentifierDatabase identifier_database_; }; } // namespace YouCompleteMe #endif /* end of include guard: COMPLETER_H_7AR4UGXE */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierDatabase.cpp000066400000000000000000000120561227567565400251530ustar00rootroot00000000000000// 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 . #include "IdentifierDatabase.h" #include "standard.h" #include "Candidate.h" #include "CandidateRepository.h" #include "IdentifierUtils.h" #include "Result.h" #include "Utils.h" #include #include #include #include using boost::algorithm::any_of; using boost::algorithm::is_upper; namespace YouCompleteMe { IdentifierDatabase::IdentifierDatabase() : candidate_repository_( CandidateRepository::Instance() ) { } void IdentifierDatabase::AddIdentifiers( const FiletypeIdentifierMap &filetype_identifier_map ) { boost::lock_guard< boost::mutex > locker( filetype_candidate_map_mutex_ ); foreach ( const FiletypeIdentifierMap::value_type & filetype_and_map, filetype_identifier_map ) { foreach( const FilepathToIdentifiers::value_type & filepath_and_identifiers, filetype_and_map.second ) { AddIdentifiersNoLock( filepath_and_identifiers.second, filetype_and_map.first, filepath_and_identifiers.first ); } } } void IdentifierDatabase::AddIdentifiers( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ) { boost::lock_guard< boost::mutex > locker( filetype_candidate_map_mutex_ ); AddIdentifiersNoLock( new_candidates, filetype, filepath ); } void IdentifierDatabase::ClearCandidatesStoredForFile( const std::string &filetype, const std::string &filepath ) { boost::lock_guard< boost::mutex > locker( filetype_candidate_map_mutex_ ); GetCandidateSet( filetype, filepath ).clear(); } void IdentifierDatabase::ResultsForQueryAndType( const std::string &query, const std::string &filetype, std::vector< Result > &results ) const { FiletypeCandidateMap::const_iterator it; { boost::lock_guard< boost::mutex > locker( filetype_candidate_map_mutex_ ); it = filetype_candidate_map_.find( filetype ); if ( it == filetype_candidate_map_.end() || query.empty() ) return; } Bitset query_bitset = LetterBitsetFromString( query ); bool query_has_uppercase_letters = any_of( query, is_upper() ); boost::unordered_set< const Candidate * > seen_candidates; seen_candidates.reserve( candidate_repository_.NumStoredCandidates() ); { boost::lock_guard< boost::mutex > locker( filetype_candidate_map_mutex_ ); foreach ( const FilepathToCandidates::value_type & path_and_candidates, *it->second ) { foreach ( const Candidate * candidate, *path_and_candidates.second ) { if ( ContainsKey( seen_candidates, candidate ) ) continue; else seen_candidates.insert( candidate ); if ( !candidate->MatchesQueryBitset( query_bitset ) ) continue; Result result = candidate->QueryMatchResult( query, query_has_uppercase_letters ); if ( result.IsSubsequence() ) results.push_back( result ); } } } std::sort( results.begin(), results.end() ); } // WARNING: You need to hold the filetype_candidate_map_mutex_ before calling // this function and while using the returned set. std::set< const Candidate * > &IdentifierDatabase::GetCandidateSet( const std::string &filetype, const std::string &filepath ) { boost::shared_ptr< FilepathToCandidates > &path_to_candidates = filetype_candidate_map_[ filetype ]; if ( !path_to_candidates ) path_to_candidates.reset( new FilepathToCandidates() ); boost::shared_ptr< std::set< const Candidate * > > &candidates = ( *path_to_candidates )[ filepath ]; if ( !candidates ) candidates.reset( new std::set< const Candidate * >() ); return *candidates; } // WARNING: You need to hold the filetype_candidate_map_mutex_ before calling // this function and while using the returned set. void IdentifierDatabase::AddIdentifiersNoLock( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ) { std::set< const Candidate *> &candidates = GetCandidateSet( filetype, filepath ); std::vector< const Candidate * > repository_candidates = candidate_repository_.GetCandidatesForStrings( new_candidates ); candidates.insert( repository_candidates.begin(), repository_candidates.end() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierDatabase.h000066400000000000000000000063621227567565400246230ustar00rootroot00000000000000// 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 . #ifndef IDENTIFIERDATABASE_H_ZESX3CVR #define IDENTIFIERDATABASE_H_ZESX3CVR #include #include #include #include #include #include #include #include namespace YouCompleteMe { class Candidate; class Result; class CandidateRepository; // filepath -> identifiers typedef std::map< std::string, std::vector< std::string > > FilepathToIdentifiers; // filetype -> (filepath -> identifiers) typedef std::map< std::string, FilepathToIdentifiers > FiletypeIdentifierMap; // This class stores the database of identifiers the identifier completer has // seen. It stores them in a data structure that makes it easy to tell which // identifier came from which file and what files have which filetypes. // // The main point of this class is to isolate the parts of the code that need // access to this internal data structure so that it's easier to confirm that // mutexes are used correctly to protect concurrent access. // // This class is thread-safe. class IdentifierDatabase : boost::noncopyable { public: IdentifierDatabase(); void AddIdentifiers( const FiletypeIdentifierMap &filetype_identifier_map ); void AddIdentifiers( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ); void ClearCandidatesStoredForFile( const std::string &filetype, const std::string &filepath ); void ResultsForQueryAndType( const std::string &query, const std::string &filetype, std::vector< Result > &results ) const; private: std::set< const Candidate * > &GetCandidateSet( const std::string &filetype, const std::string &filepath ); void AddIdentifiersNoLock( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ); // filepath -> *( *candidate ) typedef boost::unordered_map < std::string, boost::shared_ptr< std::set< const Candidate * > > > FilepathToCandidates; // filetype -> *( filepath -> *( *candidate ) ) typedef boost::unordered_map < std::string, boost::shared_ptr< FilepathToCandidates > > FiletypeCandidateMap; CandidateRepository &candidate_repository_; FiletypeCandidateMap filetype_candidate_map_; mutable boost::mutex filetype_candidate_map_mutex_; }; } // namespace YouCompleteMe #endif /* end of include guard: IDENTIFIERDATABASE_H_ZESX3CVR */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierUtils.cpp000066400000000000000000000152741227567565400245540ustar00rootroot00000000000000// 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 . #include "IdentifierUtils.h" #include "Utils.h" #include "standard.h" #include #include #include #include namespace YouCompleteMe { namespace fs = boost::filesystem; namespace { const char *const COMMENT_AND_STRING_REGEX = "//.*?$" // Anything following '//' "|" "#.*?$" // Anything following '#' "|" "/\\*.*?\\*/" // C-style comments, '/* ... */' "|" // Anything inside single quotes, '...', but mind: // 1. that the starting single quote is not escaped // 2. the escaped slash (\\) // 3. the escaped single quote inside the string // "(? { bool operator()( const std::string &a, const std::string &b ) const { return a == b; } }; // List of languages Exuberant Ctags supports: // ctags --list-languages // To map a language name to a filetype, see this file: // :e $VIMRUNTIME/filetype.vim // This is a map of const char* and not std::string to prevent issues with // static initialization. const boost::unordered_map < const char *, const char *, boost::hash< std::string >, StringEqualityComparer > LANG_TO_FILETYPE = boost::assign::map_list_of ( "Ant" , "ant" ) ( "Asm" , "asm" ) ( "Awk" , "awk" ) ( "Basic" , "basic" ) ( "C++" , "cpp" ) ( "C#" , "cs" ) ( "C" , "c" ) ( "COBOL" , "cobol" ) ( "DosBatch" , "dosbatch" ) ( "Eiffel" , "eiffel" ) ( "Erlang" , "erlang" ) ( "Fortran" , "fortran" ) ( "HTML" , "html" ) ( "Java" , "java" ) ( "JavaScript" , "javascript" ) ( "Lisp" , "lisp" ) ( "Lua" , "lua" ) ( "Make" , "make" ) ( "MatLab" , "matlab" ) ( "OCaml" , "ocaml" ) ( "Pascal" , "pascal" ) ( "Perl" , "perl" ) ( "PHP" , "php" ) ( "Python" , "python" ) ( "REXX" , "rexx" ) ( "Ruby" , "ruby" ) ( "Scheme" , "scheme" ) ( "Sh" , "sh" ) ( "SLang" , "slang" ) ( "SML" , "sml" ) ( "SQL" , "sql" ) ( "Tcl" , "tcl" ) ( "Tex" , "tex" ) ( "Vera" , "vera" ) ( "Verilog" , "verilog" ) ( "VHDL" , "vhdl" ) ( "Vim" , "vim" ) ( "YACC" , "yacc" ); const char *const NOT_FOUND = "YCMFOOBAR_NOT_FOUND"; } // unnamed namespace std::string RemoveIdentifierFreeText( std::string text ) { boost::erase_all_regex( text, boost::regex( COMMENT_AND_STRING_REGEX ) ); return text; } std::vector< std::string > ExtractIdentifiersFromText( const std::string &text ) { std::string::const_iterator start = text.begin(); std::string::const_iterator end = text.end(); boost::smatch matches; const boost::regex expression( IDENTIFIER_REGEX ); std::vector< std::string > identifiers; while ( boost::regex_search( start, end, matches, expression ) ) { identifiers.push_back( matches[ 0 ] ); start = matches[ 0 ].second; } return identifiers; } FiletypeIdentifierMap ExtractIdentifiersFromTagsFile( const fs::path &path_to_tag_file ) { FiletypeIdentifierMap filetype_identifier_map; std::string tags_file_contents; try { tags_file_contents = ReadUtf8File( path_to_tag_file ); } catch ( ... ) { return filetype_identifier_map; } std::string::const_iterator start = tags_file_contents.begin(); std::string::const_iterator end = tags_file_contents.end(); boost::smatch matches; const boost::regex expression( TAG_REGEX ); const boost::match_flag_type options = boost::match_not_dot_newline; while ( boost::regex_search( start, end, matches, expression, options ) ) { start = matches[ 0 ].second; std::string language( matches[ 3 ] ); std::string filetype = FindWithDefault( LANG_TO_FILETYPE, language.c_str(), NOT_FOUND ); if ( filetype == NOT_FOUND ) continue; std::string identifier( matches[ 1 ] ); fs::path path( matches[ 2 ].str() ); if ( path.is_relative() ) path = path_to_tag_file.parent_path() / path; filetype_identifier_map[ filetype ][ path.string() ].push_back( identifier ); } return filetype_identifier_map; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/IdentifierUtils.h000066400000000000000000000031351227567565400242120ustar00rootroot00000000000000// 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 . #ifndef IDENTIFIERUTILS_CPP_WFFUZNET #define IDENTIFIERUTILS_CPP_WFFUZNET #include "IdentifierDatabase.h" #include #include #include namespace YouCompleteMe { // NOTE: this function accepts the text param by value on purpose; it internally // needs a copy before processing the text so the copy might as well be made on // the parameter BUT if this code is compiled in C++11 mode a move constructor // can be called on the passed-in value. This is not possible if we accept the // param by const ref. std::string RemoveIdentifierFreeText( std::string text ); std::vector< std::string > ExtractIdentifiersFromText( const std::string &text ); FiletypeIdentifierMap ExtractIdentifiersFromTagsFile( const boost::filesystem::path &path_to_tag_file ); } // namespace YouCompleteMe #endif /* end of include guard: IDENTIFIERUTILS_CPP_WFFUZNET */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/LetterNode.cpp000066400000000000000000000033461227567565400235130ustar00rootroot00000000000000// 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 . #include "LetterNode.h" #include "standard.h" namespace YouCompleteMe { LetterNode::LetterNode( char letter, int index ) : is_uppercase_( IsUppercase( letter ) ), index_( index ) { } // TODO: this class needs tests LetterNode::LetterNode( const std::string &text ) : is_uppercase_( false ), index_( -1 ) { letternode_per_text_index_.resize( text.size() ); for ( uint i = 0; i < text.size(); ++i ) { char letter = text[ i ]; LetterNode *node = new LetterNode( letter, i ); letters_[ letter ].push_back( node ); letternode_per_text_index_[ i ] = boost::shared_ptr< LetterNode >( node ); } for ( int i = static_cast< int >( letternode_per_text_index_.size() ) - 1; i >= 0; --i ) { LetterNode *node_to_add = letternode_per_text_index_[ i ].get(); for ( int j = i - 1; j >= 0; --j ) { letternode_per_text_index_[ j ]->PrependNodeForLetter( text[ i ], node_to_add ); } } } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/LetterNode.h000066400000000000000000000033361227567565400231570ustar00rootroot00000000000000// 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 . #ifndef LETTERNODE_H_EIZ6JVWC #define LETTERNODE_H_EIZ6JVWC #include "LetterNodeListMap.h" #include #include #include #include #include namespace YouCompleteMe { class LetterNode : boost::noncopyable { public: LetterNode( char letter, int index ); // this is for root nodes explicit LetterNode( const std::string &text ); inline bool LetterIsUppercase() const { return is_uppercase_; } inline const std::list< LetterNode * > *NodeListForLetter( char letter ) { return letters_.ListPointerAt( letter ); } inline void PrependNodeForLetter( char letter, LetterNode *node ) { letters_[ letter ].push_front( node ); } inline int Index() const { return index_; } private: LetterNodeListMap letters_; std::vector< boost::shared_ptr< LetterNode > > letternode_per_text_index_; bool is_uppercase_; int index_; }; } // namespace YouCompleteMe #endif /* end of include guard: LETTERNODE_H_EIZ6JVWC */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/LetterNodeListMap.cpp000066400000000000000000000042541227567565400250040ustar00rootroot00000000000000// 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 . #include "LetterNodeListMap.h" #include "standard.h" #include namespace YouCompleteMe { const int kNumLetters = NUM_LETTERS; static const int kLettersIndexStart = 0; static const int kNumbersIndexStart = 26; bool IsUppercase( char letter ) { return 'A' <= letter && letter <= 'Z'; } int IndexForChar( char letter ) { if ( IsUppercase( letter ) ) return letter + ( 'a' - 'A' ); return letter; } LetterNodeListMap::LetterNodeListMap() { std::fill( letters_.begin(), letters_.end(), static_cast< std::list< LetterNode * >* >( NULL ) ); } LetterNodeListMap::~LetterNodeListMap() { for ( uint i = 0; i < letters_.size(); ++i ) { delete letters_[ i ]; } } bool LetterNodeListMap::HasLetter( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode * > *list = letters_[ letter_index ]; return list; } std::list< LetterNode * > &LetterNodeListMap::operator[] ( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode * > *list = letters_[ letter_index ]; if ( list ) return *list; letters_[ letter_index ] = new std::list< LetterNode * >(); return *letters_[ letter_index ]; } std::list< LetterNode * > *LetterNodeListMap::ListPointerAt( char letter ) { return letters_[ IndexForChar( letter ) ]; } bool LetterNodeListMap::HasLetter( char letter ) const { return letters_[ IndexForChar( letter ) ] != NULL; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/LetterNodeListMap.h000066400000000000000000000027641227567565400244550ustar00rootroot00000000000000// 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 . #ifndef LETTERNODELISTMAP_H_BRK2UMC1 #define LETTERNODELISTMAP_H_BRK2UMC1 #include #include #include #define NUM_LETTERS 128 namespace YouCompleteMe { class LetterNode; extern const int kNumLetters; int IndexForChar( char letter ); bool IsUppercase( char letter ); class LetterNodeListMap : boost::noncopyable { public: LetterNodeListMap(); ~LetterNodeListMap(); bool HasLetter( char letter ); std::list< LetterNode * > &operator[] ( char letter ); std::list< LetterNode * > *ListPointerAt( char letter ); bool HasLetter( char letter ) const; private: boost::array< std::list< LetterNode * >*, NUM_LETTERS > letters_; }; } // namespace YouCompleteMe #endif /* end of include guard: LETTERNODELISTMAP_H_BRK2UMC1 */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/PythonSupport.cpp000066400000000000000000000072211227567565400243200ustar00rootroot00000000000000// 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 . #include "PythonSupport.h" #include "standard.h" #include "Result.h" #include "Candidate.h" #include "CandidateRepository.h" #include "ReleaseGil.h" #include #include #include using boost::algorithm::any_of; using boost::algorithm::is_upper; using boost::python::len; using boost::python::str; using boost::python::extract; using boost::python::object; typedef boost::python::list pylist; namespace YouCompleteMe { namespace { std::string GetUtf8String( const boost::python::object &string_or_unicode ) { extract< std::string > to_string( string_or_unicode ); if ( to_string.check() ) return to_string(); return extract< std::string >( str( string_or_unicode ).encode( "utf8" ) ); } std::vector< const Candidate * > CandidatesFromObjectList( const pylist &candidates, const std::string &candidate_property ) { int num_candidates = len( candidates ); std::vector< std::string > candidate_strings; candidate_strings.reserve( num_candidates ); for ( int i = 0; i < num_candidates; ++i ) { if ( candidate_property.empty() ) { candidate_strings.push_back( GetUtf8String( candidates[ i ] ) ); } else { object holder = extract< object >( candidates[ i ] ); candidate_strings.push_back( GetUtf8String( holder[ candidate_property.c_str() ] ) ); } } return CandidateRepository::Instance().GetCandidatesForStrings( candidate_strings ); } } // unnamed namespace boost::python::list FilterAndSortCandidates( const boost::python::list &candidates, const std::string &candidate_property, const std::string &query ) { pylist filtered_candidates; if ( query.empty() ) { return candidates; } int num_candidates = len( candidates ); std::vector< const Candidate * > repository_candidates = CandidatesFromObjectList( candidates, candidate_property ); std::vector< ResultAnd< int > > object_and_results; { ReleaseGil unlock; Bitset query_bitset = LetterBitsetFromString( query ); bool query_has_uppercase_letters = any_of( query, is_upper() ); for ( int i = 0; i < num_candidates; ++i ) { const Candidate *candidate = repository_candidates[ i ]; if ( !candidate->MatchesQueryBitset( query_bitset ) ) continue; Result result = candidate->QueryMatchResult( query, query_has_uppercase_letters ); if ( result.IsSubsequence() ) { ResultAnd< int > object_and_result( i, result ); object_and_results.push_back( boost::move( object_and_result ) ); } } std::sort( object_and_results.begin(), object_and_results.end() ); } foreach ( const ResultAnd< int > &object_and_result, object_and_results ) { filtered_candidates.append( candidates[ object_and_result.extra_object_ ] ); } return filtered_candidates; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/PythonSupport.h000066400000000000000000000025671227567565400237750ustar00rootroot00000000000000// 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 . #ifndef PYTHONSUPPORT_H_KWGFEX0V #define PYTHONSUPPORT_H_KWGFEX0V #include namespace YouCompleteMe { // Given a list of python objects (that represent completion candidates) in a // python list |candidates|, a |candidate_property| on which to filter and sort // the candidates and a user query, returns a new sorted python list with the // original objects that survived the filtering. boost::python::list FilterAndSortCandidates( const boost::python::list &candidates, const std::string &candidate_property, const std::string &query ); } // namespace YouCompleteMe #endif /* end of include guard: PYTHONSUPPORT_H_KWGFEX0V */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ReleaseGil.h000066400000000000000000000021601227567565400231200ustar00rootroot00000000000000// 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 . #ifndef RELEASEGIL_H_RDIEBSQ1 #define RELEASEGIL_H_RDIEBSQ1 #include namespace YouCompleteMe { class ReleaseGil { public: ReleaseGil() { thread_state_ = PyEval_SaveThread(); } ~ReleaseGil() { PyEval_RestoreThread( thread_state_ ); } private: PyThreadState *thread_state_; }; } // namespace YouCompleteMe #endif /* end of include guard: RELEASEGIL_H_RDIEBSQ1 */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Result.cpp000066400000000000000000000160751227567565400227270ustar00rootroot00000000000000// 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 . #include "Result.h" #include "standard.h" #include "Utils.h" #include #include #include #include using boost::algorithm::istarts_with; namespace YouCompleteMe { namespace { char ChangeCharCase( char c ) { if ( std::isupper( c, std::locale() ) ) return std::tolower( c, std::locale() ); return std::toupper( c, std::locale() ); } bool CharLessThanWithLowercasePriority(const char &first, const char &second) { char swap_first = ChangeCharCase( first ); char swap_second = ChangeCharCase( second ); return swap_first < swap_second; } bool StringLessThanWithLowercasePriority(const std::string &first, const std::string &second) { return std::lexicographical_compare( first.begin(), first.end(), second.begin(), second.end(), boost::function< bool( const char&, const char& ) >( &CharLessThanWithLowercasePriority ) ); } int LongestCommonSubsequenceLength( const std::string &first, const std::string &second ) { const std::string &longer = first.size() > second.size() ? first : second; const std::string &shorter = first.size() > second.size() ? second : first; int longer_len = longer.size(); int shorter_len = shorter.size(); std::vector previous( shorter_len + 1, 0 ); std::vector current( shorter_len + 1, 0 ); for ( int i = 0; i < longer_len; ++i ) { for ( int j = 0; j < shorter_len; ++j ) { if ( toupper( longer[ i ] ) == toupper( shorter[ j ] ) ) current[ j + 1 ] = previous[ j ] + 1; else current[ j + 1 ] = std::max( current[ j ], previous[ j + 1 ] ); } for ( int j = 0; j < shorter_len; ++j ) { previous[ j + 1 ] = current[ j + 1 ]; } } return current[ shorter_len ]; } int NumWordBoundaryCharMatches( const std::string &query, const std::string &word_boundary_chars ) { return LongestCommonSubsequenceLength( query, word_boundary_chars ); } } // unnamed namespace Result::Result() : query_is_empty_( true ), is_subsequence_( false ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( false ), char_match_index_sum_( 0 ), text_( NULL ) { } Result::Result( bool is_subsequence ) : query_is_empty_( true ), is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( false ), char_match_index_sum_( 0 ), text_( NULL ) { } Result::Result( bool is_subsequence, const std::string *text, bool text_is_lowercase, int char_match_index_sum, const std::string &word_boundary_chars, const std::string &query ) : query_is_empty_( true ), is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( text_is_lowercase ), char_match_index_sum_( char_match_index_sum ), text_( text ) { if ( is_subsequence ) SetResultFeaturesFromQuery( word_boundary_chars, query ); } bool Result::operator< ( const Result &other ) const { // Yes, this is ugly but it also needs to be fast. Since this is called a // bazillion times, we have to make sure only the required comparisons are // made, and no more. if ( !query_is_empty_ ) { if ( first_char_same_in_query_and_text_ != other.first_char_same_in_query_and_text_ ) { return first_char_same_in_query_and_text_; } bool equal_wb_ratios = AlmostEqual( ratio_of_word_boundary_chars_in_query_, other.ratio_of_word_boundary_chars_in_query_ ); bool equal_wb_utilization = AlmostEqual( word_boundary_char_utilization_, other.word_boundary_char_utilization_ ); if ( AlmostEqual( ratio_of_word_boundary_chars_in_query_, 1.0 ) || AlmostEqual( other.ratio_of_word_boundary_chars_in_query_, 1.0 ) ) { if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } } if ( query_is_candidate_prefix_ != other.query_is_candidate_prefix_ ) return query_is_candidate_prefix_; if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } if ( char_match_index_sum_ != other.char_match_index_sum_ ) return char_match_index_sum_ < other.char_match_index_sum_; if ( text_->length() != other.text_->length() ) return text_->length() < other.text_->length(); if ( text_is_lowercase_ != other.text_is_lowercase_ ) return text_is_lowercase_; } // Lexicographic comparison, but we prioritize lowercase letters over // uppercase ones. So "foo" < "Foo". return StringLessThanWithLowercasePriority( *text_, *other.text_ ); } void Result::SetResultFeaturesFromQuery( const std::string &word_boundary_chars, const std::string &query ) { query_is_empty_ = query.empty(); if ( query.empty() || text_->empty() ) return; first_char_same_in_query_and_text_ = toupper( query[ 0 ] ) == toupper( ( *text_ )[ 0 ] ); int num_wb_matches = NumWordBoundaryCharMatches( query, word_boundary_chars ); ratio_of_word_boundary_chars_in_query_ = num_wb_matches / static_cast< double >( query.length() ); word_boundary_char_utilization_ = num_wb_matches / static_cast< double >( word_boundary_chars.length() ); query_is_candidate_prefix_ = istarts_with( *text_, query ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Result.h000066400000000000000000000070721227567565400223710ustar00rootroot00000000000000// 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 . #ifndef RESULT_H_CZYD2SGN #define RESULT_H_CZYD2SGN #include namespace YouCompleteMe { class Result { public: Result(); explicit Result( bool is_subsequence ); Result( bool is_subsequence, const std::string *text, bool text_is_lowercase, int char_match_index_sum, const std::string &word_boundary_chars, const std::string &query ); bool operator< ( const Result &other ) const; inline bool IsSubsequence() const { return is_subsequence_; } inline const std::string *Text() const { return text_; } private: void SetResultFeaturesFromQuery( const std::string &query, const std::string &word_boundary_chars ); // true when the query for which the result was created was an empty string; // in these cases we just use a lexicographic comparison bool query_is_empty_; // true when the characters of the query are a subsequence of the characters // in the candidate text, e.g. the characters "abc" are a subsequence for // "xxaygbefc" but not for "axxcb" since they occur in the correct order ('a' // then 'b' then 'c') in the first string but not in the second. bool is_subsequence_; // true when the first character of the query and the candidate match bool first_char_same_in_query_and_text_; // number of word boundary matches / number of chars in query double ratio_of_word_boundary_chars_in_query_; // number of word boundary matches / number of all word boundary chars double word_boundary_char_utilization_; // true when the query is a prefix of the candidate string, e.g. "foo" query // for "foobar" candidate. bool query_is_candidate_prefix_; // true when the candidate text is all lowercase, e.g. "foo" candidate. bool text_is_lowercase_; // The sum of the indexes of all the letters the query "hit" in the candidate // text. For instance, the result for the query "abc" in the candidate // "012a45bc8" has char_match_index_sum of 3 + 6 + 7 = 16 because those are // the char indexes of those letters in the candidate string. int char_match_index_sum_; // points to the full candidate text const std::string *text_; }; template< class T > struct ResultAnd { // TODO: Swap the order of these parameters ResultAnd( T extra_object, const Result &result ) : extra_object_( extra_object ), result_( result ) {} bool operator< ( const ResultAnd &other ) const { return result_ < other.result_; } T extra_object_; Result result_; }; template< class T > struct ResultAnd { ResultAnd( const T *extra_object, const Result &result ) : extra_object_( extra_object ), result_( result ) {} bool operator< ( const ResultAnd &other ) const { return result_ < other.result_; } const T *extra_object_; Result result_; }; } // namespace YouCompleteMe #endif /* end of include guard: RESULT_H_CZYD2SGN */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Utils.cpp000066400000000000000000000032321227567565400225400ustar00rootroot00000000000000// 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 . #include "Utils.h" #include #include #include #include namespace fs = boost::filesystem; namespace YouCompleteMe { bool AlmostEqual( double a, double b ) { return std::abs( a - b ) <= ( std::numeric_limits< double >::epsilon() * std::max( std::abs( a ), std::abs( b ) ) ); } std::string ReadUtf8File( const fs::path &filepath ) { fs::ifstream file( filepath, std::ios::in | std::ios::binary ); std::vector< char > contents( ( std::istreambuf_iterator< char >( file ) ), std::istreambuf_iterator< char >() ); if ( contents.size() == 0 ) return std::string(); return std::string( contents.begin(), contents.end() ); } void WriteUtf8File( const fs::path &filepath, const std::string &contents ) { fs::ofstream file; file.open( filepath ); file << contents; file.close(); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/Utils.h000066400000000000000000000046141227567565400222120ustar00rootroot00000000000000// 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 . #ifndef UTILS_H_KEPMRPBH #define UTILS_H_KEPMRPBH #include #include #include namespace fs = boost::filesystem; namespace YouCompleteMe { bool AlmostEqual( double a, double b ); // Reads the entire contents of the specified file. If the file does not exist, // an exception is thrown. std::string ReadUtf8File( const fs::path &filepath ); // Writes the entire contents of the specified file. If the file does not exist, // an exception is thrown. void WriteUtf8File( const fs::path &filepath, const std::string &contents ); template typename Container::mapped_type & GetValueElseInsert( Container &container, const Key &key, const typename Container::mapped_type &value ) { return container.insert( typename Container::value_type( key, value ) ) .first->second; } template bool ContainsKey( Container &container, const Key &key ) { return container.find( key ) != container.end(); } template typename Container::mapped_type FindWithDefault( Container &container, const Key &key, const typename Container::mapped_type &value ) { typename Container::const_iterator it = container.find( key ); return it != container.end() ? it->second : value; } template bool Erase( Container &container, const Key &key ) { typename Container::iterator it = container.find( key ); if ( it != container.end() ) { container.erase( it ); return true; } return false; } } // namespace YouCompleteMe #endif /* end of include guard: UTILS_H_KEPMRPBH */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/exceptions.h000066400000000000000000000026311227567565400232700ustar00rootroot00000000000000// 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 . #ifndef EXCEPTIONS_H_3PHJ9YOB #define EXCEPTIONS_H_3PHJ9YOB #include namespace YouCompleteMe { #define boost_throw(x) BOOST_THROW_EXCEPTION(x) // YouCompleteMe uses the "Exception types as semantic tags" idiom. // For more information, see this link: // http://www.boost.org/doc/libs/1_50_0/libs/exception/doc/exception_types_as_simple_semantic_tags.html /** * The common base for all exceptions. */ struct ExceptionBase: virtual std::exception, virtual boost::exception {}; /** * Thrown when a file does not exist. */ struct ClangParseError : virtual ExceptionBase {}; } // namespace YouCompleteMe #endif /* end of include guard: EXCEPTIONS_H_3PHJ9YOB */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/standard.h000066400000000000000000000016241227567565400227100ustar00rootroot00000000000000// 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 . #include #include "CustomAssert.h" // We're most definitely not going to use // it as BOOST_FOREACH. #define foreach BOOST_FOREACH typedef unsigned int uint; vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/000077500000000000000000000000001227567565400220765ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/CMakeLists.txt000066400000000000000000000056031227567565400246420ustar00rootroot00000000000000# Copyright (C) 2011 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 . project( ycm_core_tests ) cmake_minimum_required( VERSION 2.8 ) # The gtest library triggers these warnings, so we turn them off; it's not up to # us to fix gtest warnings, it's up to upstream. if ( COMPILER_IS_CLANG ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long -Wno-variadic-macros -Wno-missing-field-initializers -Wno-unused-private-field" ) endif() add_subdirectory( gmock ) include_directories( ${ycm_support_libs_SOURCE_DIR} ) include_directories( SYSTEM ${gtest_SOURCE_DIR} ${gtest_SOURCE_DIR}/include ${gmock_SOURCE_DIR} ${gmock_SOURCE_DIR}/include ) link_directories( ${Boost_LIBRARY_DIRS} ${PYTHON_LIBRARIES} ) file( GLOB_RECURSE SOURCES *.h *.cpp ) # We don't want gmock sources in this target file( GLOB_RECURSE to_remove gmock/*.h gmock/*.cpp CMakeFiles/*.cpp testdata/*.cpp testdata/*.h ) if( to_remove ) list( REMOVE_ITEM SOURCES ${to_remove} ) endif() if ( NOT USE_CLANG_COMPLETER ) file( GLOB_RECURSE to_remove_clang ClangCompleter/*.h ClangCompleter/*.cpp ) if( to_remove_clang ) list( REMOVE_ITEM SOURCES ${to_remove_clang} ) endif() endif() add_executable( ${PROJECT_NAME} ${SOURCES} ) target_link_libraries( ${PROJECT_NAME} ${SERVER_LIB} ${CLIENT_LIB} gmock ) if ( NOT CMAKE_GENERATOR_IS_XCODE ) # The test executable expects a "testdata" dir in its working directory. Why? # Because there's NO reliable, cross-platform way of getting the directory in # which the executable is located. add_custom_target( copy_testdata COMMAND cmake -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/testdata ${CMAKE_CURRENT_BINARY_DIR}/testdata ) else() add_custom_target( copy_testdata COMMAND cmake -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/testdata ${CMAKE_CURRENT_BINARY_DIR}/Debug/testdata COMMAND cmake -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/testdata ${CMAKE_CURRENT_BINARY_DIR}/Release/testdata ) endif() add_dependencies( ${PROJECT_NAME} copy_testdata ) vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/CandidateRepository_test.cpp000066400000000000000000000032241227567565400276160ustar00rootroot00000000000000// 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 . #include #include "CandidateRepository.h" #include "Candidate.h" #include "Result.h" namespace YouCompleteMe { TEST( CandidateRepositoryTest, EmptyCandidatesForUnicode ) { std::vector< std::string > inputs; inputs.push_back( "fooδιακριτικός" ); inputs.push_back( "fooδιακός" ); CandidateRepository &repo = CandidateRepository::Instance(); std::vector< const Candidate * > candidates = repo.GetCandidatesForStrings( inputs ); EXPECT_EQ( "", candidates[ 0 ]->Text() ); EXPECT_EQ( "", candidates[ 1 ]->Text() ); } TEST( CandidateRepositoryTest, EmptyCandidatesForNonPrintable ) { std::vector< std::string > inputs; inputs.push_back( "\x01\x05\x0a\x15" ); CandidateRepository &repo = CandidateRepository::Instance(); std::vector< const Candidate * > candidates = repo.GetCandidatesForStrings( inputs ); EXPECT_EQ( "", candidates[ 0 ]->Text() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/Candidate_test.cpp000066400000000000000000000241301227567565400255150ustar00rootroot00000000000000// 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 . #include #include "Candidate.h" #include "Result.h" namespace YouCompleteMe { TEST( GetWordBoundaryCharsTest, SimpleOneWord ) { EXPECT_EQ( "s", GetWordBoundaryChars( "simple" ) ); } TEST( GetWordBoundaryCharsTest, UnderscoreInMiddle ) { EXPECT_EQ( "sf", GetWordBoundaryChars( "simple_foo" ) ); } TEST( GetWordBoundaryCharsTest, UnderscoreStart ) { EXPECT_EQ( "s", GetWordBoundaryChars( "_simple" ) ); } TEST( GetWordBoundaryCharsTest, ManyUnderscoreStart ) { EXPECT_EQ( "s", GetWordBoundaryChars( "___simple" ) ); } TEST( GetWordBoundaryCharsTest, UnderscoreStartAndInMiddle ) { EXPECT_EQ( "sf", GetWordBoundaryChars( "_simple_foo" ) ); } TEST( GetWordBoundaryCharsTest, ManyUnderscoreStartAndInMiddle ) { EXPECT_EQ( "sf", GetWordBoundaryChars( "___simple__foo" ) ); } TEST( GetWordBoundaryCharsTest, SimpleCapitalStart ) { EXPECT_EQ( "s", GetWordBoundaryChars( "Simple" ) ); } TEST( GetWordBoundaryCharsTest, SimpleCapitalTwoWord ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "SimpleStuff" ) ); } TEST( GetWordBoundaryCharsTest, SimpleCapitalTwoWordUnderscoreMiddle ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "Simple_Stuff" ) ); } TEST( GetWordBoundaryCharsTest, JavaCase ) { EXPECT_EQ( "ssf", GetWordBoundaryChars( "simpleStuffFoo" ) ); } TEST( GetWordBoundaryCharsTest, UppercaseSequence ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "simpleSTUFF" ) ); } TEST( GetWordBoundaryCharsTest, UppercaseSequenceInMiddle ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "simpleSTUFFfoo" ) ); } TEST( GetWordBoundaryCharsTest, UppercaseSequenceInMiddleUnderscore ) { EXPECT_EQ( "ssf", GetWordBoundaryChars( "simpleSTUFF_Foo" ) ); } TEST( GetWordBoundaryCharsTest, UppercaseSequenceInMiddleUnderscoreLowercase ) { EXPECT_EQ( "ssf", GetWordBoundaryChars( "simpleSTUFF_foo" ) ); } TEST( GetWordBoundaryCharsTest, AllCapsSimple ) { EXPECT_EQ( "s", GetWordBoundaryChars( "SIMPLE" ) ); } TEST( GetWordBoundaryCharsTest, AllCapsUnderscoreStart ) { EXPECT_EQ( "s", GetWordBoundaryChars( "_SIMPLE" ) ); } TEST( GetWordBoundaryCharsTest, AllCapsUnderscoreMiddle ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "SIMPLE_STUFF" ) ); } TEST( GetWordBoundaryCharsTest, AllCapsUnderscoreMiddleAndStart ) { EXPECT_EQ( "ss", GetWordBoundaryChars( "_SIMPLE_STUFF" ) ); } TEST( CandidateTest, TextValid ) { std::string text = "foo"; Candidate candidate( text ); EXPECT_EQ( text, candidate.Text() ); } TEST( CandidateTest, MatchesQueryBitsetWhenMatch ) { Candidate candidate( "foobaaar" ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "foobaaar" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "fobar" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "rabof" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "bfroa" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "fbr" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "r" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "bbb" ) ) ); EXPECT_TRUE( candidate.MatchesQueryBitset( LetterBitsetFromString( "" ) ) ); } TEST( CandidateTest, DoesntMatchQueryBitset ) { Candidate candidate( "foobar" ); EXPECT_FALSE( candidate.MatchesQueryBitset( LetterBitsetFromString( "foobare" ) ) ); EXPECT_FALSE( candidate.MatchesQueryBitset( LetterBitsetFromString( "gggg" ) ) ); EXPECT_FALSE( candidate.MatchesQueryBitset( LetterBitsetFromString( "x" ) ) ); EXPECT_FALSE( candidate.MatchesQueryBitset( LetterBitsetFromString( "nfoobar" ) ) ); EXPECT_FALSE( candidate.MatchesQueryBitset( LetterBitsetFromString( "fbrmmm" ) ) ); } TEST( CandidateTest, QueryMatchResultCaseInsensitiveIsSubsequence ) { Candidate candidate( "foobaaar" ); EXPECT_TRUE( candidate.QueryMatchResult( "foobaaar", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "foOBAaar", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "FOOBAAAR", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fobar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fbr" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "f" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "F" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "o" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "O" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "a" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "r" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "b" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "bar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oa" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "obr" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oo" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "aaa" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "AAA" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "" , false ).IsSubsequence() ); } TEST( CandidateTest, QueryMatchResultCaseInsensitiveIsntSubsequence ) { Candidate candidate( "foobaaar" ); EXPECT_FALSE( candidate.QueryMatchResult( "foobra" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "frb" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "brf" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "x" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "9" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "-" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "~" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( " " , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "rabof" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "oabfr" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "ooo" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "baaara" , false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "ffoobaaar", false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "xfoobaaar", false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( " foobaaar", false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "foobaaar ", false ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "ff" , false ).IsSubsequence() ); } TEST( CandidateTest, QueryMatchResultCaseSensitiveIsSubsequence ) { Candidate candidate( "FooBaAAr" ); EXPECT_TRUE( candidate.QueryMatchResult( "FooBaAAr", true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "FBAA" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "F" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "AA" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "A" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "B" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "foobaaar", true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "foobaAAr", true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fbAA" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fbaa" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "b" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "f" , true ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fbar" , true ).IsSubsequence() ); } TEST( CandidateTest, QueryMatchResultCaseSensitiveIsntSubsequence ) { Candidate candidate( "FooBaAAr" ); EXPECT_FALSE( candidate.QueryMatchResult( "goo" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "R" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "O" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "OO" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "OBA" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FBAR" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FBAAR" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "Oar" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FooBAAAr", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FOoBaAAr", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FOobaaar", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "fOobaaar", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "foobaaaR", true ).IsSubsequence() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/ClangCompleter/000077500000000000000000000000001227567565400247755ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/ClangCompleter/ClangCompleter_test.cpp000066400000000000000000000035011227567565400314360ustar00rootroot00000000000000// 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 . #include "ClangCompleter.h" #include "CompletionData.h" #include "../TestUtils.h" #include #include #include namespace YouCompleteMe { using ::testing::ElementsAre; using ::testing::WhenSorted; TEST( ClangCompleterTest, CandidatesForLocationInFile ) { ClangCompleter completer; std::vector< CompletionData > completions = completer.CandidatesForLocationInFile( PathToTestFile( "basic.cpp" ).string(), 11, 7, std::vector< UnsavedFile >(), std::vector< std::string >() ); EXPECT_TRUE( !completions.empty() ); } TEST( ClangCompleterTest, GetDefinitionLocation ) { ClangCompleter completer; std::string filename = PathToTestFile( "basic.cpp" ).string(); // Clang operates on the reasonable assumption that line and column numbers // are 1-based. Location actual_location = completer.GetDefinitionLocation( filename, 9, 3, std::vector< UnsavedFile >(), std::vector< std::string >() ); EXPECT_EQ( Location( filename, 1, 8 ), actual_location ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/ClangCompleter/TranslationUnit_test.cpp000066400000000000000000000073531227567565400317060ustar00rootroot00000000000000// 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 . #include "TranslationUnit.h" #include "exceptions.h" #include "Utils.h" #include #include #include #include namespace fs = boost::filesystem; using ::testing::ElementsAre; using ::testing::WhenSorted; namespace YouCompleteMe { class TranslationUnitTest : public ::testing::Test { protected: virtual void SetUp() { clang_index_ = clang_createIndex( 0, 0 ); } virtual void TearDown() { clang_disposeIndex( clang_index_ ); } CXIndex clang_index_; }; TEST_F( TranslationUnitTest, ExceptionThrownOnParseFailure ) { fs::path test_file = fs::temp_directory_path() / fs::unique_path(); std::string junk = "#&9112(^(^#>@(^@!@(&#@a}}}}{nthoeu\n&&^^&^&!#%%@@!aeu"; WriteUtf8File( test_file, junk ); std::vector< std::string > flags; flags.push_back( junk ); EXPECT_THROW( TranslationUnit( test_file.string(), std::vector< UnsavedFile >(), flags, NULL ), ClangParseError ); } TEST_F( TranslationUnitTest, GoToDefinitionWorks ) { fs::path path_to_testdata = fs::current_path() / fs::path( "testdata" ); fs::path test_file = path_to_testdata / fs::path( "goto.cpp" ); TranslationUnit unit( test_file.string(), std::vector< UnsavedFile >(), std::vector< std::string >(), clang_index_ ); Location location = unit.GetDefinitionLocation( 15, 3, std::vector< UnsavedFile >() ); EXPECT_EQ( 1, location.line_number_ ); EXPECT_EQ( 8, location.column_number_ ); EXPECT_TRUE( !location.filename_.empty() ); } TEST_F( TranslationUnitTest, GoToDefinitionFails ) { fs::path path_to_testdata = fs::current_path() / fs::path( "testdata" ); fs::path test_file = path_to_testdata / fs::path( "goto.cpp" ); TranslationUnit unit( test_file.string(), std::vector< UnsavedFile >(), std::vector< std::string >(), clang_index_ ); Location location = unit.GetDefinitionLocation( 17, 3, std::vector< UnsavedFile >() ); EXPECT_FALSE( location.IsValid() ); } TEST_F( TranslationUnitTest, GoToDeclarationWorks ) { fs::path path_to_testdata = fs::current_path() / fs::path( "testdata" ); fs::path test_file = path_to_testdata / fs::path( "goto.cpp" ); TranslationUnit unit( test_file.string(), std::vector< UnsavedFile >(), std::vector< std::string >(), clang_index_ ); Location location = unit.GetDeclarationLocation( 17, 3, std::vector< UnsavedFile >() ); EXPECT_EQ( 12, location.line_number_ ); EXPECT_EQ( 8, location.column_number_ ); EXPECT_TRUE( !location.filename_.empty() ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/IdentifierCompleter_test.cpp000066400000000000000000000221271227567565400276020ustar00rootroot00000000000000// 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 . #include #include #include "IdentifierCompleter.h" #include "Utils.h" #include "TestUtils.h" using ::testing::ElementsAre; using ::testing::WhenSorted; namespace YouCompleteMe { // This differs from what we expect from the ClangCompleter. That one should // return results for an empty query. TEST( IdentifierCompleterTest, EmptyQueryNoResults ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar" ) ).CandidatesForQuery( "" ), ElementsAre() ); } TEST( IdentifierCompleterTest, NoDuplicatesReturned ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar", "foobar", "foobar" ) ).CandidatesForQuery( "foo" ), ElementsAre( "foobar" ) ); } TEST( IdentifierCompleterTest, OneCandidate ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar" ) ).CandidatesForQuery( "fbr" ), ElementsAre( "foobar" ) ); } TEST( IdentifierCompleterTest, ManyCandidateSimple ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar", "foobartest", "Foobartest" ) ).CandidatesForQuery( "fbr" ), WhenSorted( ElementsAre( "Foobartest", "foobar", "foobartest" ) ) ); } TEST( IdentifierCompleterTest, SmartCaseFiltering ) { EXPECT_THAT( IdentifierCompleter( StringVector( "fooBar", "fooBaR" ) ).CandidatesForQuery( "fBr" ), ElementsAre( "fooBaR", "fooBar" ) ); } TEST( IdentifierCompleterTest, FirstCharSameAsQueryWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar", "afoobar" ) ).CandidatesForQuery( "fbr" ), ElementsAre( "foobar", "afoobar" ) ); } TEST( IdentifierCompleterTest, CompleteMatchForWordBoundaryCharsWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "FooBarQux", "FBaqux" ) ).CandidatesForQuery( "fbq" ), ElementsAre( "FooBarQux", "FBaqux" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "CompleterTest", "CompleteMatchForWordBoundaryCharsWins" ) ) .CandidatesForQuery( "ct" ), ElementsAre( "CompleterTest", "CompleteMatchForWordBoundaryCharsWins" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "FooBar", "FooBarRux" ) ).CandidatesForQuery( "fbr" ), ElementsAre( "FooBarRux", "FooBar" ) ); } TEST( IdentifierCompleterTest, RatioUtilizationTieBreak ) { EXPECT_THAT( IdentifierCompleter( StringVector( "aGaaFooBarQux", "aBaafbq" ) ).CandidatesForQuery( "fbq" ), ElementsAre( "aGaaFooBarQux", "aBaafbq" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "aFooBarQux", "afbq" ) ).CandidatesForQuery( "fbq" ), ElementsAre( "aFooBarQux", "afbq" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "acaaCaaFooGxx", "aCaafoog" ) ).CandidatesForQuery( "caafoo" ), ElementsAre( "acaaCaaFooGxx", "aCaafoog" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "FooBarQux", "FooBarQuxZaa" ) ).CandidatesForQuery( "fbq" ), ElementsAre( "FooBarQux", "FooBarQuxZaa" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "FooBar", "FooBarRux" ) ).CandidatesForQuery( "fba" ), ElementsAre( "FooBar", "FooBarRux" ) ); } TEST( IdentifierCompleterTest, QueryPrefixOfCandidateWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar", "fbaroo" ) ).CandidatesForQuery( "foo" ), ElementsAre( "foobar", "fbaroo" ) ); } TEST( IdentifierCompleterTest, LowerMatchCharIndexSumWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "ratio_of_word_boundary_chars_in_query_", "first_char_same_in_query_and_text_" ) ) .CandidatesForQuery( "charinq" ), ElementsAre( "first_char_same_in_query_and_text_", "ratio_of_word_boundary_chars_in_query_" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "barfooq", "barquxfoo" ) ).CandidatesForQuery( "foo" ), ElementsAre( "barfooq", "barquxfoo" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "xxxxxxabc", "xxabcxxxx" ) ).CandidatesForQuery( "abc" ), ElementsAre( "xxabcxxxx", "xxxxxxabc" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "FooBarQux", "FaBarQux" ) ).CandidatesForQuery( "fbq" ), ElementsAre( "FaBarQux", "FooBarQux" ) ); } TEST( IdentifierCompleterTest, ShorterCandidateWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "CompleterT", "CompleterTest" ) ).CandidatesForQuery( "co" ), ElementsAre( "CompleterT", "CompleterTest" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "CompleterT", "CompleterTest" ) ).CandidatesForQuery( "plet" ), ElementsAre( "CompleterT", "CompleterTest" ) ); } TEST( IdentifierCompleterTest, SameLowercaseCandidateWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "foobar", "Foobar" ) ).CandidatesForQuery( "foo" ), ElementsAre( "foobar", "Foobar" ) ); } TEST( IdentifierCompleterTest, PreferLowercaseCandidate ) { EXPECT_THAT( IdentifierCompleter( StringVector( "chatContentExtension", "ChatContentExtension" ) ).CandidatesForQuery( "chatContent" ), ElementsAre( "chatContentExtension", "ChatContentExtension" ) ); EXPECT_THAT( IdentifierCompleter( StringVector( "fooBar", "FooBar" ) ).CandidatesForQuery( "oba" ), ElementsAre( "fooBar", "FooBar" ) ); } TEST( IdentifierCompleterTest, ShorterAndLowercaseWins ) { EXPECT_THAT( IdentifierCompleter( StringVector( "STDIN_FILENO", "stdin" ) ).CandidatesForQuery( "std" ), ElementsAre( "stdin", "STDIN_FILENO" ) ); } TEST( IdentifierCompleterTest, AddIdentifiersToDatabaseFromBufferWorks ) { IdentifierCompleter completer; completer.AddIdentifiersToDatabaseFromBuffer( "foo foogoo ba", "foo", "/foo/bar", false ); EXPECT_THAT( completer.CandidatesForQueryAndType( "oo", "foo" ), ElementsAre( "foo", "foogoo" ) ); } TEST( IdentifierCompleterTest, TagsEndToEndWorks ) { IdentifierCompleter completer; std::vector< std::string > tag_files; tag_files.push_back( PathToTestFile( "basic.tags" ).string() ); completer.AddIdentifiersToDatabaseFromTagFiles( tag_files ); EXPECT_THAT( completer.CandidatesForQueryAndType( "fo", "cpp" ), ElementsAre( "foosy", "fooaaa" ) ); } // TODO: tests for filepath and filetype candidate storing } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/IdentifierUtils_test.cpp000066400000000000000000000124311227567565400267450ustar00rootroot00000000000000// 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 . #include "IdentifierUtils.h" #include "TestUtils.h" #include "IdentifierDatabase.h" #include #include #include namespace YouCompleteMe { namespace fs = boost::filesystem; using ::testing::ElementsAre; using ::testing::ContainerEq; using ::testing::WhenSorted; TEST( IdentifierUtilsTest, RemoveIdentifierFreeTextComments ) { EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar //foo \n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar #foo \n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar /* foo \n" " foo2 */\n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); } TEST( IdentifierUtilsTest, RemoveIdentifierFreeTextSimpleStrings ) { EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar 'foo'\n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar \"foo\"\n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); } TEST( IdentifierUtilsTest, RemoveIdentifierFreeTextEscapedQuotesInStrings ) { EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar 'fo\\'oz\\nfoo'\n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar \"fo\\\"oz\\nfoo\"\n" "qux" ).c_str(), "foo \n" "bar \n" "qux" ); } TEST( IdentifierUtilsTest, RemoveIdentifierFreeTextEscapedSlashesInStrings ) { EXPECT_STREQ( RemoveIdentifierFreeText( "foo \n" "bar \"fo\\\\\"baz\n" "qux \"qwe\"" ).c_str(), "foo \n" "bar baz\n" "qux " ); EXPECT_STREQ( RemoveIdentifierFreeText( "foo '\\\\'\n" "bar '\\\\'\n" "qux '\\\\'" ).c_str(), "foo \n" "bar \n" "qux " ); } TEST( IdentifierUtilsTest, RemoveIdentifierFreeTextEscapedQuotesStartStrings ) { EXPECT_STREQ( RemoveIdentifierFreeText( "\\\"foo\\\"" "'\"'" "'bar' zoo'test'" ).c_str(), "\\\"foo\\\" zoo" ); EXPECT_STREQ( RemoveIdentifierFreeText( "\\'foo\\'" "\"'\"" "\"bar\" zoo\"test\"" ).c_str(), "\\'foo\\' zoo" ); } TEST( IdentifierUtilsTest, ExtractIdentifiersFromTextWorks ) { EXPECT_THAT( ExtractIdentifiersFromText( "foo $_bar \n&BazGoo\n FOO= !!! '-' - _ (x) one-two !moo [qqq]" ), ElementsAre( "foo", "_bar", "BazGoo", "FOO", "_", "x", "one", "two", "moo", "qqq" ) ); } TEST( IdentifierUtilsTest, ExtractIdentifiersFromTagsFileWorks ) { fs::path testfile = PathToTestFile( "basic.tags" ); fs::path testfile_parent = testfile.parent_path(); FiletypeIdentifierMap expected; expected[ "cpp" ][ ( testfile_parent / "foo" ).string() ] .push_back( "i1" ); expected[ "cpp" ][ ( testfile_parent / "bar" ).string() ] .push_back( "i1" ); expected[ "cpp" ][ ( testfile_parent / "foo" ).string() ] .push_back( "foosy" ); expected[ "cpp" ][ ( testfile_parent / "bar" ).string() ] .push_back( "fooaaa" ); expected[ "c" ][ "/foo/zoo" ].push_back( "Floo::goo" ); expected[ "c" ][ "/foo/goo maa" ].push_back( "!goo" ); expected[ "cs" ][ "/m_oo" ].push_back( "#bleh" ); EXPECT_THAT( ExtractIdentifiersFromTagsFile( testfile ), ContainerEq( expected ) ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/IndexForChar_test.cpp000066400000000000000000000024431227567565400261600ustar00rootroot00000000000000// 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 . #include #include "LetterNodeListMap.h" namespace YouCompleteMe { TEST( IndexForCharTest, Basic ) { EXPECT_EQ( static_cast( 'a' ), IndexForChar( 'a' ) ); EXPECT_EQ( static_cast( 'a' ), IndexForChar( 'A' ) ); EXPECT_EQ( static_cast( 'z' ), IndexForChar( 'z' ) ); EXPECT_EQ( static_cast( 'z' ), IndexForChar( 'Z' ) ); EXPECT_EQ( static_cast( '[' ), IndexForChar( '[' ) ); EXPECT_EQ( static_cast( ' ' ), IndexForChar( ' ' ) ); EXPECT_EQ( static_cast( '~' ), IndexForChar( '~' ) ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/IsUppercase_test.cpp000066400000000000000000000023131227567565400260630ustar00rootroot00000000000000// 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 . #include #include "LetterNodeListMap.h" namespace YouCompleteMe { TEST( IsUppercaseTest, Basic ) { EXPECT_TRUE( IsUppercase( 'A' ) ); EXPECT_TRUE( IsUppercase( 'B' ) ); EXPECT_TRUE( IsUppercase( 'Z' ) ); EXPECT_FALSE( IsUppercase( 'a' ) ); EXPECT_FALSE( IsUppercase( 'b' ) ); EXPECT_FALSE( IsUppercase( 'z' ) ); EXPECT_FALSE( IsUppercase( '$' ) ); EXPECT_FALSE( IsUppercase( '@' ) ); EXPECT_FALSE( IsUppercase( '~' ) ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/LetterBitsetFromString_test.cpp000066400000000000000000000022511227567565400302660ustar00rootroot00000000000000// 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 . #include #include "Candidate.h" namespace YouCompleteMe { TEST( LetterBitsetFromStringTest, Basic ) { Bitset expected; expected.set( IndexForChar( 'a' ) ); expected.set( IndexForChar( 'o' ) ); expected.set( IndexForChar( 'c' ) ); expected.set( IndexForChar( 'f' ) ); expected.set( IndexForChar( 'b' ) ); std::string text = "abcfoof"; EXPECT_EQ( expected, LetterBitsetFromString( text ) ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/TestUtils.cpp000066400000000000000000000041661227567565400245510ustar00rootroot00000000000000// 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 . #include "TestUtils.h" namespace YouCompleteMe { namespace fs = boost::filesystem; std::vector< std::string > StringVector( const std::string &a, const std::string &b, const std::string &c, const std::string &d, const std::string &e, const std::string &f, const std::string &g, const std::string &h, const std::string &i ) { std::vector< std::string > string_vector; string_vector.push_back( a ); if ( !b.empty() ) string_vector.push_back( b ); if ( !c.empty() ) string_vector.push_back( c ); if ( !d.empty() ) string_vector.push_back( d ); if ( !e.empty() ) string_vector.push_back( e ); if ( !f.empty() ) string_vector.push_back( f ); if ( !g.empty() ) string_vector.push_back( g ); if ( !h.empty() ) string_vector.push_back( h ); if ( !i.empty() ) string_vector.push_back( i ); return string_vector; } boost::filesystem::path PathToTestFile( const std::string &filepath ) { fs::path path_to_testdata = fs::current_path() / fs::path( "testdata" ); return path_to_testdata / fs::path( filepath ); } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/TestUtils.h000066400000000000000000000033251227567565400242120ustar00rootroot00000000000000// 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 . #ifndef TESTUTILS_H_G4RKMGUD #define TESTUTILS_H_G4RKMGUD #include #include #include namespace YouCompleteMe { std::vector< std::string > StringVector( const std::string &a, const std::string &b = std::string(), const std::string &c = std::string(), const std::string &d = std::string(), const std::string &e = std::string(), const std::string &f = std::string(), const std::string &g = std::string(), const std::string &h = std::string(), const std::string &i = std::string() ); boost::filesystem::path PathToTestFile( const std::string &filepath ); } // namespace YouCompleteMe #endif /* end of include guard: TESTUTILS_H_G4RKMGUD */ vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/main.cpp000066400000000000000000000004361227567565400235310ustar00rootroot00000000000000#include "gtest/gtest.h" #include "gmock/gmock.h" #include int main( int argc, char **argv ) { Py_Initialize(); // Necessary because of usage of the ReleaseGil class PyEval_InitThreads(); testing::InitGoogleMock( &argc, argv ); return RUN_ALL_TESTS(); } vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/testdata/000077500000000000000000000000001227567565400237075ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/testdata/basic.cpp000066400000000000000000000002001227567565400254640ustar00rootroot00000000000000struct Foo { int x; int y; char c; }; int main() { Foo foo; // The location after the dot is line 11, col 7 foo. } vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/testdata/basic.tags000066400000000000000000000011661227567565400256540ustar00rootroot00000000000000!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ !_TAG_FILE_SORTED 2 /0=unsorted, 1=sorted, 2=foldcase/ !_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ !_TAG_PROGRAM_NAME Exuberant Ctags // !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ !_TAG_PROGRAM_VERSION 5.8 // i1 foo junky;'junklanguage:C++ i1 bar junky;'junklanguage:C++ foosy foo junky;"'junk language:C++ zanzibar fooaaa bar junky;"'junk language:C++ zanzibar bloa foo junky Floo::goo /foo/zoo language:C !goo /foo/goo maa language:C zoro /foo language:fakelang #bleh /m_oo 123ntoh;;;\"eu language:C# ;\" vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/tests/testdata/goto.cpp000066400000000000000000000002411227567565400253600ustar00rootroot00000000000000struct Foo { int bar; int zoo; }; struct Bar { int foo; int zoo; }; struct Foo; struct Zoo; void func() { Foo foo; foo.bar = 5; Zoo *zoo = 0; } vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/versioning.cpp000066400000000000000000000016231227567565400236250ustar00rootroot00000000000000// 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 . namespace YouCompleteMe { int YcmCoreVersion() { // We increment this every time when we want to force users to recompile // ycm_core. return 8; } } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/versioning.h000066400000000000000000000014521227567565400232720ustar00rootroot00000000000000// 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 . namespace YouCompleteMe { int YcmCoreVersion(); } // namespace YouCompleteMe vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ycm_client_support.cpp000066400000000000000000000025441227567565400253670ustar00rootroot00000000000000// 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 . #include "IdentifierCompleter.h" #include "PythonSupport.h" #include "versioning.h" #include #include BOOST_PYTHON_MODULE(ycm_client_support) { using namespace boost::python; using namespace YouCompleteMe; // Necessary because of usage of the ReleaseGil class PyEval_InitThreads(); def( "FilterAndSortCandidates", FilterAndSortCandidates ); def( "YcmCoreVersion", YcmCoreVersion ); } // Boost.Thread forces us to implement this. // We don't use any thread-specific (local) storage so it's fine to implement // this as an empty function. namespace boost { void tss_cleanup_implemented() {} }; vim-youcompleteme-0+20140207+git18be5c2/cpp/ycm/ycm_core.cpp000066400000000000000000000146001227567565400232410ustar00rootroot00000000000000// 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 . #include "IdentifierCompleter.h" #include "PythonSupport.h" #include "versioning.h" #ifdef USE_CLANG_COMPLETER # include "ClangCompleter.h" # include "ClangUtils.h" # include "CompletionData.h" # include "Diagnostic.h" # include "Location.h" # include "Range.h" # include "UnsavedFile.h" # include "CompilationDatabase.h" #endif // USE_CLANG_COMPLETER #include #include #include bool HasClangSupport() { #ifdef USE_CLANG_COMPLETER return true; #else return false; #endif // USE_CLANG_COMPLETER } BOOST_PYTHON_MODULE(ycm_core) { using namespace boost::python; using namespace YouCompleteMe; // Necessary because of usage of the ReleaseGil class PyEval_InitThreads(); def( "HasClangSupport", HasClangSupport ); def( "FilterAndSortCandidates", FilterAndSortCandidates ); def( "YcmCoreVersion", YcmCoreVersion ); class_< IdentifierCompleter, boost::noncopyable >( "IdentifierCompleter" ) .def( "AddIdentifiersToDatabase", &IdentifierCompleter::AddIdentifiersToDatabase ) .def( "AddIdentifiersToDatabaseFromTagFiles", &IdentifierCompleter::AddIdentifiersToDatabaseFromTagFiles ) .def( "AddIdentifiersToDatabaseFromBuffer", &IdentifierCompleter::AddIdentifiersToDatabaseFromBuffer ) .def( "CandidatesForQueryAndType", &IdentifierCompleter::CandidatesForQueryAndType ); // TODO: rename these *Vec classes to *Vector; don't forget the python file class_< std::vector< std::string >, boost::shared_ptr< std::vector< std::string > > >( "StringVec" ) .def( vector_indexing_suite< std::vector< std::string > >() ); #ifdef USE_CLANG_COMPLETER def( "ClangVersion", ClangVersion ); // CAREFUL HERE! For filename and contents we are referring directly to // Python-allocated and -managed memory since we are accepting pointers to // data members of python objects. We need to ensure that those objects // outlive our UnsavedFile objects. class_< UnsavedFile >( "UnsavedFile" ) .add_property( "filename_", make_getter( &UnsavedFile::filename_ ), make_setter( &UnsavedFile::filename_, return_value_policy< reference_existing_object >() ) ) .add_property( "contents_", make_getter( &UnsavedFile::contents_ ), make_setter( &UnsavedFile::contents_, return_value_policy< reference_existing_object >() ) ) .def_readwrite( "length_", &UnsavedFile::length_ ); class_< std::vector< UnsavedFile > >( "UnsavedFileVec" ) .def( vector_indexing_suite< std::vector< UnsavedFile > >() ); class_< ClangCompleter, boost::noncopyable >( "ClangCompleter" ) .def( "GetDeclarationLocation", &ClangCompleter::GetDeclarationLocation ) .def( "GetDefinitionLocation", &ClangCompleter::GetDefinitionLocation ) .def( "DeleteCachesForFile", &ClangCompleter::DeleteCachesForFile ) .def( "UpdatingTranslationUnit", &ClangCompleter::UpdatingTranslationUnit ) .def( "UpdateTranslationUnit", &ClangCompleter::UpdateTranslationUnit ) .def( "CandidatesForLocationInFile", &ClangCompleter::CandidatesForLocationInFile ); class_< CompletionData >( "CompletionData" ) .def( "TextToInsertInBuffer", &CompletionData::TextToInsertInBuffer ) .def( "MainCompletionText", &CompletionData::MainCompletionText ) .def( "ExtraMenuInfo", &CompletionData::ExtraMenuInfo ) .def( "DetailedInfoForPreviewWindow", &CompletionData::DetailedInfoForPreviewWindow ) .def_readonly( "kind_", &CompletionData::kind_ ); class_< std::vector< CompletionData >, boost::shared_ptr< std::vector< CompletionData > > >( "CompletionVec" ) .def( vector_indexing_suite< std::vector< CompletionData > >() ); class_< Location >( "Location" ) .def_readonly( "line_number_", &Location::line_number_ ) .def_readonly( "column_number_", &Location::column_number_ ) .def_readonly( "filename_", &Location::filename_ ) .def( "IsValid", &Location::IsValid ); class_< Range >( "Range" ) .def_readonly( "start_", &Range::start_ ) .def_readonly( "end_", &Range::end_ ); class_< std::vector< Range > >( "RangeVec" ) .def( vector_indexing_suite< std::vector< Range > >() ); class_< Diagnostic >( "Diagnostic" ) .def_readonly( "ranges_", &Diagnostic::ranges_ ) .def_readonly( "location_", &Diagnostic::location_ ) .def_readonly( "location_extent_", &Diagnostic::location_extent_ ) .def_readonly( "kind_", &Diagnostic::kind_ ) .def_readonly( "text_", &Diagnostic::text_ ) .def_readonly( "long_formatted_text_", &Diagnostic::long_formatted_text_ ); class_< std::vector< Diagnostic > >( "DiagnosticVec" ) .def( vector_indexing_suite< std::vector< Diagnostic > >() ); class_< CompilationDatabase, boost::noncopyable >( "CompilationDatabase", init< std::string >() ) .def( "DatabaseSuccessfullyLoaded", &CompilationDatabase::DatabaseSuccessfullyLoaded ) .def( "AlreadyGettingFlags", &CompilationDatabase::AlreadyGettingFlags ) .def( "GetCompilationInfoForFile", &CompilationDatabase::GetCompilationInfoForFile ); class_< CompilationInfoForFile, boost::shared_ptr< CompilationInfoForFile > >( "CompilationInfoForFile", no_init ) .def_readonly( "compiler_working_dir_", &CompilationInfoForFile::compiler_working_dir_ ) .def_readonly( "compiler_flags_", &CompilationInfoForFile::compiler_flags_ ); #endif // USE_CLANG_COMPLETER } // Boost.Thread forces us to implement this. // We don't use any thread-specific (local) storage so it's fine to implement // this as an empty function. namespace boost { void tss_cleanup_implemented() {} }; vim-youcompleteme-0+20140207+git18be5c2/doc/000077500000000000000000000000001227567565400201275ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/doc/youcompleteme.txt000066400000000000000000002641471227567565400235750ustar00rootroot00000000000000*youcompleteme.txt* YouCompleteMe: a code-completion engine for Vim =============================================================================== Contents ~ 1. Introduction |youcompleteme-introduction| 2. Mac OS X super-quick installation |youcompleteme-mac-os-x-super-quick-installation| 3. Ubuntu Linux x64 super-quick installation |youcompleteme-ubuntu-linux-x64-super-quick-installation| 4. Windows Installation |youcompleteme-windows-installation| 5. Full Installation Guide |youcompleteme-full-installation-guide| 6. 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 Engine Usage |youcompleteme-general-semantic-completion-engine-usage| 5. C-family Semantic Completion Engine Usage |youcompleteme-c-family-semantic-completion-engine-usage| 6. Python semantic completion |youcompleteme-python-semantic-completion| 7. C# semantic completion |youcompleteme-c-semantic-completion| 8. Semantic completion for other languages |youcompleteme-semantic-completion-for-other-languages| 9. Writing New Semantic Completers |youcompleteme-writing-new-semantic-completers| 10. Diagnostic display |youcompleteme-diagnostic-display| 1. Diagnostic highlighting groups |youcompleteme-diagnostic-highlighting-groups| 7. 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 |:YcmCompleter| command 8. YcmCompleter subcommands |youcompleteme-ycmcompleter-subcommands| 1. The |GoToDeclaration| subcommand 2. The |GoToDefinition| subcommand 3. The |GoToDefinitionElseDeclaration| subcommand 4. The |ClearCompilationFlagCache| subcommand 5. The |StartServer| subcommand 6. The |StopServer| subcommand 7. The |RestartServer| subcommand 9. 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_path_to_python_interpreter| option 23. The |g:ycm_server_use_vim_stdout| option 24. The |g:ycm_server_keep_logfiles| option 25. The |g:ycm_server_log_level| option 26. The |g:ycm_csharp_server_port| option 27. The |g:ycm_auto_start_csharp_server| option 28. The |g:ycm_auto_stop_csharp_server| 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 10. 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 a linker warning regarding |libpython| on Mac when compiling YCM 4. 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| 5. It appears that YCM is not working |youcompleteme-it-appears-that-ycm-is-not-working| 6. Sometimes it takes much longer to get semantic completions than normal |youcompleteme-sometimes-it-takes-much-longer-to-get-semantic-completions-than-normal| 7. YCM auto-inserts completion strings I don't want! |youcompleteme-ycm-auto-inserts-completion-strings-i-dont-want| 8. I get a 'E227: mapping already exists for ' error when I start Vim |E227:-mapping-already-exists-for-blah| 9. I get "'GLIBC_2.XX' not found (required by libclang.so)" when starting Vim |GLIBC_2.XX-not-found()| 10. 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| 11. 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| 12. Vim segfaults when I use the semantic completer in Ruby files |youcompleteme-vim-segfaults-when-i-use-semantic-completer-in-ruby-files| 13. I get 'LONG_BIT definition appears wrong for platform' when compiling |LONG_BIT-definition-appears-wrong-for-platform| 14. I get 'libpython2.7.a [...] relocation R_X86_64_32' when compiling |libpython2.7.a-...-relocation-R_X86_64_32| 15. I get 'Vim: Caught deadly signal SEGV' on Vim startup |Vim:-Caught-deadly-signal-SEGV| 16. YCM does not read identifiers from my tags files |youcompleteme-ycm-does-not-read-identifiers-from-my-tags-files| 17. 'CTRL-U' in insert mode does not work |CTRL-sub-U| 18. YCM conflicts with UltiSnips TAB key usage |youcompleteme-ycm-conflicts-with-ultisnips-tab-key-usage| 19. Why isn't YCM just written in plain VimScript, FFS? |youcompleteme-why-isnt-ycm-just-written-in-plain-vimscript-ffs| 20. Why does YCM demand such a recent version of Vim? |youcompleteme-why-does-ycm-demand-such-recent-version-of-vim| 21. I get annoying messages in Vim's status area when I type |youcompleteme-i-get-annoying-messages-in-vims-status-area-when-i-type| 22. Nasty bugs happen if I have the 'vim-autoclose' plugin installed |vim-sub-autoclose| 23. Is there some sort of YCM mailing list? I have questions |youcompleteme-is-there-sort-of-ycm-mailing-list-i-have-questions| 24. I get an internal compiler error when installing |youcompleteme-i-get-an-internal-compiler-error-when-installing| 25. I get weird errors when I press 'Ctrl-C' in Vim |Ctrl-sub-C| 26. Why did YCM stop using Syntastic for diagnostics display? |youcompleteme-why-did-ycm-stop-using-syntastic-for-diagnostics-display| 27. Completion doesn't work with the C++ standard library headers |youcompleteme-completion-doesnt-work-with-c-standard-library-headers| 11. Contact |youcompleteme-contact| 12. Project Management |youcompleteme-project-management| 13. License |youcompleteme-license| 14. References |youcompleteme-references| =============================================================================== *youcompleteme-introduction* Introduction ~ Image: Build Status [1] 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 semantic, Clang [3]-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 [4]-based completion engine for Python, an OmniSharp [5]-based completion engine for C# 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 [6]) 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 [7] 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 [8]) 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 YCM also provides semantic go-to-definition/declaration commands for C-family languages & Python. Expect more IDE features powered by the various YCM semantic engines in the future. You'll also find that YCM has filepath completers (try typing './' in a file) and a completer that integrates with UltiSnips [9]. =============================================================================== *youcompleteme-mac-os-x-super-quick-installation* Mac OS X super-quick installation ~ 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 [10]. 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 [10] 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 [11]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the ycm_support_libs library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. It's recommended that you have the latest Xcode installed along with the latest Command Line Tools (that you install from within Xcode). Install CMake. Preferably with Homebrew [12], but here's the stand-alone CMake installer [13]. _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.sh --clang-completer < Compiling YCM **without** semantic support for C-family languages: > cd ~/.vim/bundle/YouCompleteMe ./install.sh < If you want semantic C# support, you should add '--omnisharp-completer' to the install script as well. 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-super-quick-installation* Ubuntu Linux x64 super-quick installation ~ 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.584 with python2 support. At the time of writing, the version of Vim shipping with Ubuntu is too old. You may need to compile Vim from source [14] (don't worry, it's easy). Install YouCompleteMe with Vundle [11]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the ycm_support_libs 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'. Compiling YCM **with** semantic support for C-family languages: > cd ~/.vim/bundle/YouCompleteMe ./install.sh --clang-completer < Compiling YCM **without** semantic support for C-family languages: > cd ~/.vim/bundle/YouCompleteMe ./install.sh < If you want semantic C# support, you should add '--omnisharp-completer' to the install script as well. 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-installation* Windows Installation ~ YCM has **no official support for Windows**, but that doesn't mean you can't get it to work there. See the Windows Installation Guide [15] wiki page. Feel free to add to it. =============================================================================== *youcompleteme-full-installation-guide* Full Installation Guide ~ These are the steps necessary to get YCM working on a Unix OS like Linux or Mac OS X. My apologies to Windows users, but I don't have a guide for them. The code is platform agnostic, so if everything is configured correctly, YCM _should_ work on Windows without issues (but as of writing, it's untested on that platform). 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_support_libs 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.584 _and_ that it has support for python2 scripting**. Inside Vim, type ':version'. Look at the first two to three lines of output; it should say 'Vi IMproved 7.3' and then below that, 'Included patches: 1-X', where X will be some number. That number needs to be 584 or higher. If your version of Vim is not recent enough, you may need to compile Vim from source [14] (don't worry, it's easy). After you have made sure that you have Vim 7.3.584+, type the following in Vim: ":echo has('python')". The output should be 1. If it's 0, then get a version of Vim with Python support. 2. **Install YCM** with Vundle [11] (or Pathogen [16], but Vundle is a better idea). With Vundle, this would mean adding a "Bundle 'Valloric/YouCompleteMe'" line to your vimrc [17]. 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 neccessary.] **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.4 or higher, but can in theory work with any 3.2+ version as well. You can use the system libclang _only if you are sure it is version 3.3 or higher_, otherwise don't. Even if it is, I recommend using the official binaries from llvm.org [18] if at all possible. Make sure you download the correct archive file for your OS. 4. **Compile the 'ycm_support_libs' libraries** that YCM needs. These libs are the C++ engines 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 [13] cmake from its project site. Mac users can also get it through Homebrew [12] with 'brew install cmake'. You also need to make sure you have Python headers installed. On a Debian-like Linux distro, this would be 'sudo apt-get install python- dev'. On Mac they should already be present. 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 "Unix Makefiles" . ~/.vim/bundle/YouCompleteMe/cpp < 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). With that in mind, run the following command in the 'ycm_build' directory: > cmake -G "Unix Makefiles" -DPATH_TO_LLVM_ROOT=~/ycm_temp/llvm_root_dir . ~/.vim/bundle/YouCompleteMe/cpp < Now that makefiles have been generated, simply run: > make ycm_support_libs < 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. 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. Running the 'make' command will also place the 'libclang.[so|dylib]' in the 'YouCompleteMe/python' folder for you if you compiled with clang support (it needs to be there for YCM to work). 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-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_ 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 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-engine-usage* General Semantic Completion Engine Usage ~ - 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-engine-usage* C-family Semantic Completion Engine Usage ~ 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' [19] 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 [20] is also supported. Again, see the above linked example 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-python-semantic-completion* Python semantic completion ~ YCM uses Jedi [4] to power its semantic completion for Python. This should "just work" without any configuration from the user. You do NOT need to install Jedi yourself; YCM uses it as a git subrepo. If you're installing YCM with Vundle (which is the recommended way) then Vundle will make sure that the subrepo is checked out when you do ':BundleInstall'. If you're installing YCM by hand, then you need to run 'git submodule update --init --recursive' when you're checking out the YCM repository. That's it. But again, installing YCM with Vundle takes care of all of this for you. In the future expect to see features like go-to-definition for Python as well. ------------------------------------------------------------------------------- *youcompleteme-c-semantic-completion* C# semantic completion ~ YCM uses OmniSharp [5] to provide semantic completion for C#. It's used as a git subrepo. If you're installing YCM with Vundle (which is the recommended way) then Vundle will make sure that the subrepo is checked out when you do ':BundleInstall'. If you're installing YCM by hand, then you need to run 'git submodule update --init --recursive' when you're checking out the YCM repository. OmniSharp is written in C# and has to be compiled. The 'install.sh' script takes care of this if you pass '--omnisharp-completer' as an argument. ------------------------------------------------------------------------------- *youcompleteme-semantic-completion-for-other-languages* Semantic completion for other languages ~ 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 [21]. 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 -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 [22]. 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 [22]. 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 if you compiled YCM with Clang support. 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 :YcmForceCompileAndDiagnostics' 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 '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 [23] (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. 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 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 :YcmForceCompileAndDiagnostics' 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. 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 *:YcmCompleter* command This command can be used to invoke 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 information about the commands you can call for the selected completer. See the _YcmCompleter subcommands_ section for more information on the available subcommands. =============================================================================== *youcompleteme-ycmcompleter-subcommands* YcmCompleter subcommands ~ [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 jd :YcmCompleter GoToDefinitionElseDeclaration' maps the 'jd' sequence to the longer subcommand invocation. The various 'GoTo*' 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). ------------------------------------------------------------------------------- The *GoToDeclaration* subcommand Looks up the symbol under the cursor and jumps to its declaration. Supported in filetypes: 'c, cpp, objc, objcpp, python, cs' ------------------------------------------------------------------------------- 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, python, cs' ------------------------------------------------------------------------------- The *GoToDefinitionElseDeclaration* subcommand Looks 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. Supported in filetypes: 'c, cpp, objc, objcpp, python, cs' ------------------------------------------------------------------------------- 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' ------------------------------------------------------------------------------- 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' ------------------------------------------------------------------------------- The *RestartServer* subcommand Restarts the semantic-engine-as-localhost-server for those semantic engines that work as separate servers that YCM talks to. Supported in filetypes: 'cs' =============================================================================== *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 [17] 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 [17] 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 '' 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 \} < ------------------------------------------------------------------------------- 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: '{}' > let g:ycm_filetype_specific_completion_to_disable = {} < ------------------------------------------------------------------------------- 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. 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 [24]. 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:' 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 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_path_to_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. The YCM client running inside Vim always uses the Python interpreter that's embedded inside Vim. Default: "''" > let g:ycm_path_to_python_interpreter = '' < ------------------------------------------------------------------------------- The *g:ycm_server_use_vim_stdout* option By default, the 'ycmd' completion server writes logs to logfiles. When this option is set to '1', the server writes logs to Vim's stdout (so you'll see them in the console). Default: '0' > let g:ycm_server_use_vim_stdout = 0 < ------------------------------------------------------------------------------- The *g:ycm_server_keep_logfiles* option When this option is set to '1', the 'ycmd' completion server 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 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_csharp_server_port* option The port number (on 'localhost') on which the OmniSharp server should be started. Default: '2000' > let g:ycm_csharp_server_port = 2000 < ------------------------------------------------------------------------------- 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_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 '' to this list. Default: "['', '']" > let g:ycm_key_list_select_completion = ['', ''] < ------------------------------------------------------------------------------- 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 '' 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: "['', '']" > let g:ycm_key_list_previous_completion = ['', ''] < ------------------------------------------------------------------------------- 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 '' to Vim when the user types '' so YCM will make sure that '' is used in the map command when you're editing in console Vim, and '' in GUI Vim. This means that you can just press '' 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: '' > let g:ycm_key_invoke_completion = '' < ------------------------------------------------------------------------------- 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: 'd' > let g:ycm_key_detailed_diagnostics = '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. 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->'. Default: '[see next line]' > let g:ycm_semantic_triggers = { \ 'c' : ['->', '.'], \ 'objc' : ['->', '.'], \ 'ocaml' : ['.', '#'], \ 'cpp,objcpp' : ['->', '.', '::'], \ 'perl' : ['->'], \ 'php' : ['->', '::'], \ 'cs,java,javascript,d,vim,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 requeried 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 < =============================================================================== *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. 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 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 compile flags for the file if the file is a C-family language file and you have compiled in Clang support. ------------------------------------------------------------------------------- *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 '', '' or '' (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 ' 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 '' 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 [10]. 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 [25] 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 ""' part, where '' 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.2 libclang. Some distros ship with a system 'libclang.so' that identifies itself as 3.2 but is not; it was cut from the upstream sources before the official 3.2 release and some API changes (like the addition of the CompileCommands API) were added after their cut. So just go through the installation guide and make sure you are using a correct 'libclang.so'. I recommend downloading prebuilt binaries from llvm.org. ------------------------------------------------------------------------------- *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 [26] to produce your tags files since the only supported tag format is the Exuberant Ctags format [24]. 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:' field in the tags output. 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 '' 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 fitering. ------------------------------------------------------------------------------- *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 back at original' and similar, then sadly there's no fix for those. Vim will emit them no matter how hard I try to silence them. You'll have to learn to ignore them. It's a shitty "solution", I know. There's an outstanding patch for Vim that fixes this issue [27], but at the time of writing Vim upstream hasn't yet merged it in. ------------------------------------------------------------------------------- *vim-sub-autoclose* Nasty bugs happen if I have the 'vim-autoclose' plugin installed ~ Use the delimitMate [28] 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 [29] 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. ------------------------------------------------------------------------------- *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 '' is too annoying (agreed, it is), we suggest mapping it to something more convenient. On a QWERTY keyboard, a good pick for the '' map is 'inoremap jk '. 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 [30]) 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. Compiling from 'clang' the binary uses the correct default header search paths but compiling from 'libclang.so' does not. The issue seems to impact some OS's more than others. It appears that OS X Mavericks in particular has problems with this. The current 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 [31] for details. =============================================================================== *youcompleteme-contact* Contact ~ If you have questions about the plugin or need help, please use the ycm-users [29] mailing list. If you have bug reports or feature suggestions, please use the issue tracker [32]. The latest version of the plugin is available at http://valloric.github.io/YouCompleteMe/. The author's homepage is http://val.markovic.io. =============================================================================== *youcompleteme-project-management* Project Management ~ This open-source project is run by me, Strahinja Val Markovic. I also happen to work for Google and the code I write here is under Google copyright (for the sake of simplicity and other reasons). This does **NOT** mean that this is an official Google product (it isn't) or that Google has (or wants to have) anything to do with it. =============================================================================== *youcompleteme-license* License ~ This software is licensed under the GPL v3 license [33]. © 2013 Google Inc. Image: Bitdeli Badge [34] =============================================================================== *youcompleteme-references* References ~ [1] https://travis-ci.org/Valloric/YouCompleteMe [2] https://travis-ci.org/Valloric/YouCompleteMe.png?branch=travis [3] http://clang.llvm.org/ [4] https://github.com/davidhalter/jedi [5] https://github.com/nosami/OmniSharpServer [6] http://i.imgur.com/0OP4ood.gif [7] http://en.wikipedia.org/wiki/Subsequence [8] https://github.com/scrooloose/syntastic [9] https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt [10] http://code.google.com/p/macvim/#Download [11] https://github.com/gmarik/vundle#about [12] http://mxcl.github.com/homebrew/ [13] http://www.cmake.org/cmake/resources/software.html [14] https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source [15] https://github.com/Valloric/YouCompleteMe/wiki/Windows-Installation-Guide [16] https://github.com/tpope/vim-pathogen#pathogenvim [17] http://vimhelp.appspot.com/starting.txt.html#vimrc [18] http://llvm.org/releases/download.html#3.3 [19] https://github.com/Valloric/YouCompleteMe/blob/master/cpp/ycm/.ycm_extra_conf.py [20] http://clang.llvm.org/docs/JSONCompilationDatabase.html [21] http://eclim.org/ [22] https://github.com/Valloric/YouCompleteMe/blob/master/python/ycm/completers/completer.py [23] https://github.com/Valloric/ListToggle [24] http://ctags.sourceforge.net/FORMAT [25] https://github.com/Valloric/YouCompleteMe/issues/18 [26] http://ctags.sourceforge.net/ [27] https://groups.google.com/forum/#!topic/vim_dev/WeBBjkXE8H8 [28] https://github.com/Raimondi/delimitMate [29] https://groups.google.com/forum/?hl=en#!forum/ycm-users [30] https://github.com/Valloric/YouCompleteMe/issues/593 [31] https://github.com/Valloric/YouCompleteMe/issues/303 [32] https://github.com/Valloric/YouCompleteMe/issues?state=open [33] http://www.gnu.org/copyleft/gpl.html [34] https://bitdeli.com/free [35] https://d2weczhvl823v0.cloudfront.net/Valloric/youcompleteme/trend.png vim: ft=help vim-youcompleteme-0+20140207+git18be5c2/install.sh000077500000000000000000000077061227567565400214010ustar00rootroot00000000000000#!/usr/bin/env bash set -e function command_exists { hash "$1" 2>/dev/null ; } function cmake_install { if [[ `uname -s` == "Darwin" ]]; then homebrew_cmake_install else linux_cmake_install fi } function homebrew_cmake_install { if command_exists brew; then brew install cmake else echo "Homebrew was not found installed in your system." echo "Go to http://mxcl.github.com/homebrew/ and follow the instructions." echo "Or install CMake somehow and retry." exit 1 fi } function python_finder { python_library="-DPYTHON_LIBRARY=" python_include="-DPYTHON_INCLUDE_DIR=" # The CMake 'FindPythonLibs' Module does not work properly. # So we are forced to do its job for it. python_prefix=$(python-config --prefix | sed 's/^[ \t]*//') if [ -f "${python_prefix}/Python" ]; then python_library+="${python_prefix}/Python" python_include+="${python_prefix}/Headers" else which_python=$(python -c 'import sys;print(sys.version)' | sed 's/^[ \t]*//') which_python="python${which_python:0:3}" lib_python="${python_prefix}/lib/lib${which_python}" if [ -f "${lib_python}.a" ]; then python_library+="${lib_python}.a" else python_library+="${lib_python}.dylib" fi python_include+="${python_prefix}/include/${which_python}" fi echo "${python_library} ${python_include}" } function num_cores { if command_exists nproc; then num_cpus=$(nproc) else num_cpus=1 if [[ `uname -s` == "Linux" ]]; then num_cpus=$(grep -c ^processor /proc/cpuinfo) else # Works on Mac and FreeBSD num_cpus=$(sysctl -n hw.ncpu) fi fi echo $num_cpus } function install { ycm_dir=`pwd` build_dir=`mktemp -d -t ycm_build.XXXXXX` pushd $build_dir if [[ `uname -s` == "Darwin" ]]; then cmake -G "Unix Makefiles" $(python_finder) "$@" . $ycm_dir/cpp else cmake -G "Unix Makefiles" "$@" . $ycm_dir/cpp fi make -j $(num_cores) ycm_support_libs popd rm -rf $build_dir } function testrun { ycm_dir=`pwd` build_dir=`mktemp -d -t ycm_build.XXXXXX` pushd $build_dir cmake -G "Unix Makefiles" "$@" . $ycm_dir/cpp make -j $(num_cores) ycm_core_tests cd ycm/tests LD_LIBRARY_PATH=$ycm_dir/python ./ycm_core_tests popd rm -rf $build_dir } function linux_cmake_install { echo "Please install CMake using your package manager and retry." exit 1 } function usage { echo "Usage: $0 [--clang-completer [--system-libclang]] [--omnisharp-completer]" exit 0 } function check_third_party_libs { libs_present=true for folder in third_party/*; do num_files_in_folder=$(find $folder -maxdepth 1 -mindepth 1 | wc -l) if [[ $num_files_in_folder -eq 0 ]]; then libs_present=false fi done if ! $libs_present; then echo "Some folders in ./third_party are empty; you probably forgot to run:" printf "\n\tgit submodule update --init --recursive\n\n" exit 1 fi } cmake_args="" omnisharp_completer=false for flag in $@; do case "$flag" in --clang-completer) cmake_args="-DUSE_CLANG_COMPLETER=ON" ;; --system-libclang) cmake_args="$cmake_args -DUSE_SYSTEM_LIBCLANG=ON" ;; --omnisharp-completer) omnisharp_completer=true ;; *) usage ;; esac done if [[ $cmake_args == *-DUSE_SYSTEM_LIBCLANG=ON* ]] && \ [[ $cmake_args != *-DUSE_CLANG_COMPLETER=ON* ]]; then usage fi check_third_party_libs if ! command_exists cmake; then echo "CMake is required to build YouCompleteMe." cmake_install fi if [ -z "$YCM_TESTRUN" ]; then install $cmake_args $EXTRA_CMAKE_ARGS else testrun $cmake_args $EXTRA_CMAKE_ARGS fi if $omnisharp_completer; then buildcommand="msbuild" if ! command_exists msbuild; then buildcommand="xbuild" if ! command_exists xbuild; then echo "msbuild or xbuild is required to build Omnisharp" exit 1 fi fi ycm_dir=`pwd` build_dir=$ycm_dir"/python/ycm/completers/cs/OmniSharpServer" cd $build_dir $buildcommand cd $ycm_dir fi vim-youcompleteme-0+20140207+git18be5c2/plugin/000077500000000000000000000000001227567565400206605ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/plugin/youcompleteme.vim000066400000000000000000000121241227567565400242640ustar00rootroot00000000000000" 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 . " This is basic vim plugin boilerplate let s:save_cpo = &cpo set cpo&vim if exists( "g:loaded_youcompleteme" ) finish elseif v:version < 703 || (v:version == 703 && !has('patch584')) echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires Vim 7.3.584+" | \ echohl None finish elseif !has( 'python' ) echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires Vim compiled with " . \ " Python 2.x support" | \ echohl None finish endif let s:script_folder_path = escape( expand( ':p:h' ), '\' ) function! s:HasYcmCore() let path_prefix = s:script_folder_path . '/../python/' if filereadable(path_prefix . 'ycm_client_support.so') && \ filereadable(path_prefix . 'ycm_core.so') return 1 elseif filereadable(path_prefix . 'ycm_client_support.pyd') && \ filereadable(path_prefix . 'ycm_core.pyd') return 1 elseif filereadable(path_prefix . 'ycm_client_support.dll') && \ filereadable(path_prefix . 'ycm_core.dll') return 1 endif return 0 endfunction let g:ycm_check_if_ycm_core_present = \ get( g:, 'ycm_check_if_ycm_core_present', 1 ) if g:ycm_check_if_ycm_core_present && !s:HasYcmCore() echohl WarningMsg | \ echomsg "ycm_client_support.[so|pyd|dll] and " . \ "ycm_core.[so|pyd|dll] not detected; you need to compile " . \ "YCM before using it. Read the docs!" | \ echohl None finish endif let g:loaded_youcompleteme = 1 " NOTE: Most defaults are in default_settings.json. They are loaded into Vim " global 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 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', ['', ''] ) let g:ycm_key_list_previous_completion = \ get( g:, 'ycm_key_list_previous_completion', ['', ''] ) let g:ycm_key_invoke_completion = \ get( g:, 'ycm_key_invoke_completion', '' ) let g:ycm_key_detailed_diagnostics = \ get( g:, 'ycm_key_detailed_diagnostics', 'd' ) let g:ycm_cache_omnifunc = \ get( g:, 'ycm_cache_omnifunc', 1 ) let g:ycm_server_use_vim_stdout = \ get( g:, 'ycm_server_use_vim_stdout', 0 ) 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_path_to_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', '>>' ) ) " 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 let &cpo = s:save_cpo unlet s:save_cpo vim-youcompleteme-0+20140207+git18be5c2/print_todos.sh000077500000000000000000000002101227567565400222560ustar00rootroot00000000000000#!/bin/bash ag \ --ignore gmock \ --ignore jedi/ \ --ignore OmniSharpServer \ --ignore testdata \ TODO \ cpp/ycm python autoload plugin vim-youcompleteme-0+20140207+git18be5c2/python/000077500000000000000000000000001227567565400207035ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/test_requirements.txt000066400000000000000000000001061227567565400252230ustar00rootroot00000000000000flake8>=2.0 mock>=1.0.1 nose>=1.3.0 PyHamcrest>=1.8.0 WebTest>=2.0.9 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/000077500000000000000000000000001227567565400214735ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/__init__.py000066400000000000000000000000001227567565400235720ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/base.py000066400000000000000000000134411227567565400227620ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import vim from ycm import vimsupport from ycm import utils from ycm import user_options_store import ycm_client_support YCM_VAR_PREFIX = 'ycm_' def BuildServerConf(): """Builds a dictionary mapping YCM Vim user options to values. Option names don't have the 'ycm_' prefix.""" vim_globals = vimsupport.GetReadOnlyVimGlobals( force_python_objects = True ) server_conf = {} for key, value in vim_globals.items(): if not key.startswith( YCM_VAR_PREFIX ): continue try: new_value = int( value ) except: new_value = value new_key = key[ len( YCM_VAR_PREFIX ): ] server_conf[ new_key ] = new_value return server_conf def LoadJsonDefaultsIntoVim(): defaults = user_options_store.DefaultOptions() vim_defaults = {} for key, value in defaults.iteritems(): vim_defaults[ 'ycm_' + key ] = value vimsupport.LoadDictIntoVimGlobals( vim_defaults, overwrite = False ) def CompletionStartColumn(): """Returns the 0-based index where the completion string should start. So if the user enters: foo.bar^ with the cursor being at the location of the caret, then the starting column would be the index of the letter 'b'. """ line = vim.current.line start_column = vimsupport.CurrentColumn() while start_column > 0 and utils.IsIdentifierChar( line[ start_column - 1 ] ): start_column -= 1 return start_column def CurrentIdentifierFinished(): current_column = vimsupport.CurrentColumn() previous_char_index = current_column - 1 if previous_char_index < 0: return True line = vim.current.line try: previous_char = line[ previous_char_index ] except IndexError: return False if utils.IsIdentifierChar( previous_char ): return False if ( not utils.IsIdentifierChar( previous_char ) and previous_char_index > 0 and utils.IsIdentifierChar( line[ previous_char_index - 1 ] ) ): return True else: return line[ : current_column ].isspace() def LastEnteredCharIsIdentifierChar(): current_column = vimsupport.CurrentColumn() previous_char_index = current_column - 1 if previous_char_index < 0: return False line = vim.current.line try: previous_char = line[ previous_char_index ] except IndexError: return False return utils.IsIdentifierChar( previous_char ) 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 type( candidate ) is dict: new_candidate = candidate.copy() if not 'abbr' 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 type( candidate ) is str: 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 COMPATIBLE_WITH_CORE_VERSION = 8 def CompatibleWithYcmCore(): try: current_core_version = ycm_client_support.YcmCoreVersion() except AttributeError: return False return current_core_version == COMPATIBLE_WITH_CORE_VERSION vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/000077500000000000000000000000001227567565400227515ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/__init__.py000066400000000000000000000000001227567565400250500ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/base_request.py000066400000000000000000000141441227567565400260110ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import vim import json import requests import urlparse from retries import retries from requests_futures.sessions import FuturesSession from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor from ycm import vimsupport from ycm.server.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 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 ): if method == 'POST': return BaseRequest.session.post( _BuildUri( handler ), data = json.dumps( data ), headers = HEADERS, timeout = timeout ) if method == 'GET': return BaseRequest.session.get( _BuildUri( handler ), headers = HEADERS, timeout = timeout ) @retries( 5, delay = 0.5, backoff = 1.5 ) def DelayedSendRequest( data, handler, method ): if method == 'POST': return requests.post( _BuildUri( handler ), data = json.dumps( data ), headers = HEADERS ) if method == 'GET': return requests.get( _BuildUri( handler ), headers = HEADERS ) if not _CheckServerIsHealthyWithCache(): return EXECUTOR.submit( DelayedSendRequest, data, handler, method ) return SendRequest( data, handler, method, timeout ) session = FuturesSession( executor = EXECUTOR ) server_location = 'http://localhost:6666' def BuildRequestData( start_column = None, query = None, include_buffer_data = True ): line, column = vimsupport.CurrentLineAndColumn() filepath = vimsupport.GetCurrentBufferFilepath() request_data = { 'filetypes': vimsupport.CurrentFiletypes(), 'line_num': line, 'column_num': column, 'start_column': start_column, 'line_value': vim.current.line, 'filepath': filepath } if include_buffer_data: request_data[ 'file_data' ] = vimsupport.GetUnsavedAndCurrentBufferData() if query: request_data[ 'query' ] = query return request_data def JsonFromFuture( future ): response = future.result() if response.status_code == requests.codes.server_error: _RaiseExceptionForData( 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 _BuildUri( handler ): return urlparse.urljoin( BaseRequest.server_location, handler ) SERVER_HEALTHY = False def _CheckServerIsHealthyWithCache(): global SERVER_HEALTHY def _ServerIsHealthy(): response = requests.get( _BuildUri( 'healthy' ) ) response.raise_for_status() return response.json() if SERVER_HEALTHY: return True try: SERVER_HEALTHY = _ServerIsHealthy() return SERVER_HEALTHY except: return False def _RaiseExceptionForData( data ): if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__: raise UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] ) raise ServerError( '{0}: {1}'.format( data[ 'exception' ][ 'TYPE' ], data[ 'message' ] ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/command_request.py000066400000000000000000000057001227567565400265130ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import vim from ycm.client.base_request import BaseRequest, BuildRequestData, ServerError from ycm import vimsupport from ycm.utils import ToUtf8IfNeeded class CommandRequest( BaseRequest ): def __init__( self, arguments, completer_target = None ): super( CommandRequest, self ).__init__() self._arguments = arguments self._completer_target = ( completer_target if completer_target else 'filetype_default' ) self._is_goto_command = ( arguments and arguments[ 0 ].startswith( 'GoTo' ) ) 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 as e: vimsupport.PostVimMessage( e ) def Response( self ): return self._response def RunPostCommandActionsIfNeeded( self ): if not self._is_goto_command or not self.Done() or not self._response: return if isinstance( self._response, list ): defs = [ _BuildQfListItem( x ) for x in self._response ] vim.eval( 'setqflist( %s )' % repr( defs ) ) vim.eval( 'youcompleteme#OpenGoToList()' ) else: vimsupport.JumpToLocation( self._response[ 'filepath' ], self._response[ 'line_num' ] + 1, self._response[ 'column_num' ] + 1) 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' ] = ToUtf8IfNeeded( goto_data_item[ 'filepath' ] ) if 'description' in goto_data_item: qf_item[ 'text' ] = ToUtf8IfNeeded( goto_data_item[ 'description' ] ) if 'line_num' in goto_data_item: qf_item[ 'lnum' ] = goto_data_item[ 'line_num' ] + 1 if 'column_num' in goto_data_item: qf_item[ 'col' ] = goto_data_item[ 'column_num' ] return qf_item vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/completion_request.py000066400000000000000000000053651227567565400272550ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ycm import base from ycm import vimsupport from ycm.utils import ToUtf8IfNeeded from ycm.client.base_request import ( BaseRequest, BuildRequestData, JsonFromFuture ) TIMEOUT_SECONDS = 0.5 class CompletionRequest( BaseRequest ): def __init__( self, extra_data = None ): super( CompletionRequest, self ).__init__() self._completion_start_column = base.CompletionStartColumn() # This field is also used by the omni_completion_request subclass self.request_data = BuildRequestData( self._completion_start_column ) if extra_data: self.request_data.update( extra_data ) def CompletionStartColumn( self ): return self._completion_start_column def Start( self, query ): self.request_data[ 'query' ] = query self._response_future = self.PostDataToHandlerAsync( self.request_data, 'completions', TIMEOUT_SECONDS ) def Done( self ): return self._response_future.done() def Response( self ): if not self._response_future: return [] try: return [ _ConvertCompletionDataToVimData( x ) for x in JsonFromFuture( self._response_future ) ] except Exception as e: vimsupport.PostVimMessage( str( e ) ) return [] def _ConvertCompletionDataToVimData( completion_data ): # see :h complete-items for a description of the dictionary fields vim_data = { 'word' : ToUtf8IfNeeded( completion_data[ 'insertion_text' ] ), 'dup' : 1, } if 'menu_text' in completion_data: vim_data[ 'abbr' ] = ToUtf8IfNeeded( completion_data[ 'menu_text' ] ) if 'extra_menu_info' in completion_data: vim_data[ 'menu' ] = ToUtf8IfNeeded( completion_data[ 'extra_menu_info' ] ) if 'kind' in completion_data: vim_data[ 'kind' ] = ToUtf8IfNeeded( completion_data[ 'kind' ] ) if 'detailed_info' in completion_data: vim_data[ 'info' ] = ToUtf8IfNeeded( completion_data[ 'detailed_info' ] ) return vim_data vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/event_notification.py000066400000000000000000000051311227567565400272120ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ycm import vimsupport from ycm.server.responses import UnknownExtraConf from ycm.client.base_request import ( BaseRequest, BuildRequestData, JsonFromFuture ) 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 Exception as e: vimsupport.PostVimMessage( str( 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' ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/omni_completion_request.py000066400000000000000000000023101227567565400302620ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ycm.client.completion_request import CompletionRequest class OmniCompletionRequest( CompletionRequest ): def __init__( self, omni_completer ): super( OmniCompletionRequest, self ).__init__() self._omni_completer = omni_completer def Start( self, query ): self.request_data[ 'query' ] = query self._results = self._omni_completer.ComputeCandidates( self.request_data ) def Done( self ): return True def Response( self ): return self._results vim-youcompleteme-0+20140207+git18be5c2/python/ycm/client/ycmd_keepalive.py000066400000000000000000000031211227567565400263010ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . 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 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/000077500000000000000000000000001227567565400236505ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/__init__.py000066400000000000000000000000001227567565400257470ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/000077500000000000000000000000001227567565400244205ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/__init__.py000066400000000000000000000000001227567565400265170ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/identifier_completer.py000066400000000000000000000176631227567565400312030ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import os import logging import ycm_core from collections import defaultdict from ycm.completers.general_completer import GeneralCompleter # from ycm.completers.general import syntax_parse from ycm import utils from ycm.utils import ToUtf8IfNeeded from ycm.server import responses MAX_IDENTIFIER_COMPLETIONS_RETURNED = 10 SYNTAX_FILENAME = 'YCM_PLACEHOLDER_FOR_SYNTAX' class IdentifierCompleter( GeneralCompleter ): def __init__( self, user_options ): super( IdentifierCompleter, self ).__init__( user_options ) self._completer = ycm_core.IdentifierCompleter() self._tags_file_last_mtime = defaultdict( int ) self._logger = logging.getLogger( __name__ ) def ShouldUseNow( self, request_data ): return self.QueryLengthAboveMinThreshold( request_data ) def ComputeCandidates( self, request_data ): if not self.ShouldUseNow( request_data ): return [] completions = self._completer.CandidatesForQueryAndType( ToUtf8IfNeeded( utils.SanitizeQuery( request_data[ 'query' ] ) ), ToUtf8IfNeeded( request_data[ 'filetypes' ][ 0 ] ) ) completions = completions[ : MAX_IDENTIFIER_COMPLETIONS_RETURNED ] completions = _RemoveSmallCandidates( completions, self.user_options[ 'min_num_identifier_candidate_chars' ] ) return [ responses.BuildCompletionData( x ) for x in completions ] def AddIdentifier( self, identifier, request_data ): filetype = request_data[ 'filetypes' ][ 0 ] filepath = request_data[ 'filepath' ] if not filetype or not filepath or not identifier: return vector = ycm_core.StringVec() vector.append( ToUtf8IfNeeded( identifier ) ) self._logger.info( 'Adding ONE buffer identifier for file: %s', filepath ) self._completer.AddIdentifiersToDatabase( vector, ToUtf8IfNeeded( filetype ), ToUtf8IfNeeded( filepath ) ) def AddPreviousIdentifier( self, request_data ): self.AddIdentifier( _PreviousIdentifier( self.user_options[ 'min_num_of_chars_for_completion' ], request_data ), request_data ) def AddIdentifierUnderCursor( self, request_data ): cursor_identifier = _GetCursorIdentifier( request_data ) if not cursor_identifier: return self.AddIdentifier( cursor_identifier, request_data ) def AddBufferIdentifiers( self, request_data ): filetype = request_data[ 'filetypes' ][ 0 ] filepath = request_data[ 'filepath' ] collect_from_comments_and_strings = bool( self.user_options[ 'collect_identifiers_from_comments_and_strings' ] ) if not filetype or not filepath: return text = request_data[ 'file_data' ][ filepath ][ 'contents' ] self._logger.info( 'Adding buffer identifiers for file: %s', filepath ) self._completer.AddIdentifiersToDatabaseFromBuffer( ToUtf8IfNeeded( text ), ToUtf8IfNeeded( filetype ), ToUtf8IfNeeded( filepath ), collect_from_comments_and_strings ) def AddIdentifiersFromTagFiles( self, tag_files ): absolute_paths_to_tag_files = ycm_core.StringVec() for tag_file in tag_files: try: current_mtime = os.path.getmtime( tag_file ) except: continue last_mtime = self._tags_file_last_mtime[ tag_file ] # We don't want to repeatedly process the same file over and over; we only # process if it's changed since the last time we looked at it if current_mtime <= last_mtime: continue self._tags_file_last_mtime[ tag_file ] = current_mtime absolute_paths_to_tag_files.append( ToUtf8IfNeeded( tag_file ) ) if not absolute_paths_to_tag_files: return self._completer.AddIdentifiersToDatabaseFromTagFiles( absolute_paths_to_tag_files ) def AddIdentifiersFromSyntax( self, keyword_list, filetypes ): keyword_vector = ycm_core.StringVec() for keyword in keyword_list: keyword_vector.append( ToUtf8IfNeeded( keyword ) ) filepath = SYNTAX_FILENAME + filetypes[ 0 ] self._completer.AddIdentifiersToDatabase( keyword_vector, ToUtf8IfNeeded( filetypes[ 0 ] ), ToUtf8IfNeeded( filepath ) ) def OnFileReadyToParse( self, request_data ): self.AddBufferIdentifiers( request_data ) if 'tag_files' in request_data: self.AddIdentifiersFromTagFiles( request_data[ 'tag_files' ] ) if 'syntax_keywords' in request_data: self.AddIdentifiersFromSyntax( request_data[ 'syntax_keywords' ], request_data[ 'filetypes' ] ) def OnInsertLeave( self, request_data ): self.AddIdentifierUnderCursor( request_data ) def OnCurrentIdentifierFinished( self, request_data ): self.AddPreviousIdentifier( request_data ) def _PreviousIdentifier( min_num_completion_start_chars, request_data ): line_num = request_data[ 'line_num' ] column_num = request_data[ 'column_num' ] filepath = request_data[ 'filepath' ] contents_per_line = ( request_data[ 'file_data' ][ filepath ][ 'contents' ].split( '\n' ) ) line = contents_per_line[ line_num ] end_column = column_num while end_column > 0 and not utils.IsIdentifierChar( line[ end_column - 1 ] ): end_column -= 1 # Look at the previous line if we reached the end of the current one if end_column == 0: try: line = contents_per_line[ line_num - 1 ] except: return "" end_column = len( line ) while end_column > 0 and not utils.IsIdentifierChar( line[ end_column - 1 ] ): end_column -= 1 start_column = end_column while start_column > 0 and utils.IsIdentifierChar( line[ start_column - 1 ] ): start_column -= 1 if end_column - start_column < min_num_completion_start_chars: return "" return line[ start_column : end_column ] def _RemoveSmallCandidates( candidates, min_num_candidate_size_chars ): if min_num_candidate_size_chars == 0: return candidates return [ x for x in candidates if len( x ) >= min_num_candidate_size_chars ] # This is meant to behave like 'expand(" 0 and utils.IsIdentifierChar( line[ identifier_start - 1 ] ): identifier_start -= 1 return identifier_start def FindIdentifierEnd( line, valid_char_column ): identifier_end = valid_char_column while identifier_end < len( line ) - 1 and utils.IsIdentifierChar( line[ identifier_end + 1 ] ): identifier_end += 1 return identifier_end + 1 column_num = request_data[ 'column_num' ] line = request_data[ 'line_value' ] try: valid_char_column = FindFirstValidChar( line, column_num ) return line[ FindIdentifierStart( line, valid_char_column ) : FindIdentifierEnd( line, valid_char_column ) ] except: return '' vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/omni_completer.py000066400000000000000000000067361227567565400300220ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import vim from ycm import vimsupport from ycm import base from ycm.completers.completer import Completer from ycm.client.base_request import BuildRequestData 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' ] ) # We let the caller call this without passing in request_data. This is useful # for figuring out should we even be preparing the "real" request_data in # omni_completion_request. The real request_data is much bigger and takes # longer to prepare, and we want to avoid creating it twice. def ShouldUseNow( self, request_data = None ): if not self._omnifunc: return False if not request_data: request_data = _BuildRequestDataSubstitute() 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: return [] omnifunc_call = [ self._omnifunc, "(0,'", vimsupport.EscapeForVim( request_data[ 'query' ] ), "')" ] items = vim.eval( ''.join( omnifunc_call ) ) if 'words' in items: items = items[ 'words' ] if not hasattr( items, '__iter__' ): raise TypeError( OMNIFUNC_NOT_LIST ) return 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 = vim.eval( '&omnifunc' ) def _BuildRequestDataSubstitute(): data = BuildRequestData( include_buffer_data = False ) data[ 'start_column' ] = base.CompletionStartColumn() return data vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/tests/000077500000000000000000000000001227567565400255625ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/all/tests/identifier_completer_test.py000066400000000000000000000062241227567565400333730ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from nose.tools import eq_ from ycm.completers.all import identifier_completer def GetCursorIdentifier_StartOfLine_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': 'foo' } ) ) eq_( 'fooBar', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': 'fooBar' } ) ) def GetCursorIdentifier_EndOfLine_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 2, 'line_value': 'foo' } ) ) def GetCursorIdentifier_PastEndOfLine_test(): eq_( '', identifier_completer._GetCursorIdentifier( { 'column_num': 10, 'line_value': 'foo' } ) ) def GetCursorIdentifier_NegativeColumn_test(): eq_( '', identifier_completer._GetCursorIdentifier( { 'column_num': -10, 'line_value': 'foo' } ) ) def GetCursorIdentifier_StartOfLine_StopsAtNonIdentifierChar_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': 'foo(goo)' } ) ) def GetCursorIdentifier_AtNonIdentifier_test(): eq_( 'goo', identifier_completer._GetCursorIdentifier( { 'column_num': 3, 'line_value': 'foo(goo)' } ) ) def GetCursorIdentifier_WalksForwardForIdentifier_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': ' foo' } ) ) def GetCursorIdentifier_FindsNothingForward_test(): eq_( '', identifier_completer._GetCursorIdentifier( { 'column_num': 4, 'line_value': 'foo ()***()' } ) ) def GetCursorIdentifier_SingleCharIdentifier_test(): eq_( 'f', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': ' f ' } ) ) def GetCursorIdentifier_StartsInMiddleOfIdentifier_test(): eq_( 'foobar', identifier_completer._GetCursorIdentifier( { 'column_num': 3, 'line_value': 'foobar' } ) ) def GetCursorIdentifier_LineEmpty_test(): eq_( '', identifier_completer._GetCursorIdentifier( { 'column_num': 11, 'line_value': '' } ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/c/000077500000000000000000000000001227567565400240725ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/c/hook.py000066400000000000000000000016751227567565400254150ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import ycm_core from ycm.completers.cpp.clang_completer import ClangCompleter def GetCompleter( user_options ): if ycm_core.HasClangSupport(): return ClangCompleter( user_options ) else: return None vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/completer.py000066400000000000000000000255321227567565400262230ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import abc import threading from collections import defaultdict from ycm.utils import ToUtf8IfNeeded, ForceSemanticCompletion, RunningInsideVim if RunningInsideVim(): from ycm_client_support import FilterAndSortCandidates else: from ycm_core import FilterAndSortCandidates from ycm.completers.completer_utils import TriggersForFiletype from ycm.server.responses import NoDiagnosticSupport NO_USER_COMMANDS = 'This completer does not define any commands.' class Completer( object ): """A base class for all Completers in YCM. Here's several important things you need to know if you're writing a custom Completer. The following are functions that the Vim part of YCM will be calling on your Completer: ShouldUseNow() is called with the start column of where a potential completion string should start and the current line (string) the cursor is on. For instance, if the user's input is 'foo.bar' and the cursor is on the 'r' in 'bar', start_column will be the 0-based index of 'b' in the line. Your implementation of ShouldUseNow() should return True if your semantic completer should be used and False otherwise. This is important to get right. You want to return False if you can't provide completions because then the identifier completer will kick in, and that's better than nothing. Note that it's HIGHLY likely that you want to override the ShouldUseNowInner() function instead of ShouldUseNow() directly (although chances are that you probably won't have any need to override either). ShouldUseNow() will call your *Inner version of the function and will also make sure that the completion cache is taken into account. You'll see this pattern repeated throughout the Completer API; YCM calls the "main" version of the function and that function calls the *Inner version while taking into account the cache. The cache is important and is a nice performance boost. When the user types in "foo.", your completer will return a list of all member functions and variables that can be accessed on the "foo" object. The Completer API caches this list. The user will then continue typing, let's say "foo.ba". On every keystroke after the dot, the Completer API will take the cache into account and will NOT re-query your completer but will in fact provide fuzzy-search on the candidate strings that were stored in the cache. ComputeCandidates() is the main entry point when the user types. For "foo.bar", the user query is "bar" and completions matching this string should be shown. It should return the list of candidates. The format of the result can be a list of strings or a more complicated list of dictionaries. Use ycm.server.responses.BuildCompletionData to build the detailed response. See clang_completer.py to see how its used in practice. Again, you probably want to override ComputeCandidatesInner(). You also need to implement the SupportedFiletypes() function which should return a list of strings, where the strings are Vim filetypes your completer supports. clang_completer.py is a good example of a "complicated" completer. A good example of a simple completer is ultisnips_completer.py. The On* functions are provided for your convenience. They are called when their specific events occur. For instance, the identifier completer collects all the identifiers in the file in OnFileReadyToParse() which gets called when the user stops typing for 2 seconds (Vim's CursorHold and CursorHoldI events). One special function is OnUserCommand. It is called when the user uses the command :YcmCompleter and is passed all extra arguments used on command invocation (e.g. OnUserCommand(['first argument', 'second'])). This can be used for completer-specific commands such as reloading external configuration. When the command is called with no arguments you should print a short summary of the supported commands or point the user to the help section where this information can be found. Override the Shutdown() member function if your Completer subclass needs to do custom cleanup logic on server shutdown.""" __metaclass__ = abc.ABCMeta def __init__( self, user_options ): self.user_options = user_options self.min_num_chars = user_options[ 'min_num_of_chars_for_completion' ] self.triggers_for_filetype = ( TriggersForFiletype( user_options[ 'semantic_triggers' ] ) if user_options[ 'auto_trigger' ] else defaultdict( set ) ) self._completions_cache = CompletionsCache() # It's highly likely you DON'T want to override this function but the *Inner # version of it. def ShouldUseNow( self, request_data ): if not self.ShouldUseNowInner( request_data ): self._completions_cache.Invalidate() return False # We have to do the cache valid check and get the completions as part of one # call because we have to ensure a different thread doesn't change the cache # data. cache_completions = self._completions_cache.GetCompletionsIfCacheValid( request_data[ 'line_num' ], request_data[ 'start_column' ] ) # If None, then the cache isn't valid and we know we should return true if cache_completions is None: return True else: previous_results_were_valid = bool( cache_completions ) return previous_results_were_valid def ShouldUseNowInner( self, request_data ): current_line = request_data[ 'line_value' ] start_column = request_data[ 'start_column' ] line_length = len( current_line ) if not line_length or start_column - 1 >= line_length: return False filetype = self._CurrentFiletype( request_data[ 'filetypes' ] ) triggers = self.triggers_for_filetype[ filetype ] for trigger in triggers: index = -1 trigger_length = len( trigger ) while True: line_index = start_column + index if line_index < 0 or current_line[ line_index ] != trigger[ index ]: break if abs( index ) == trigger_length: return True index -= 1 return False def QueryLengthAboveMinThreshold( self, request_data ): query_length = request_data[ 'column_num' ] - request_data[ 'start_column' ] return query_length >= self.min_num_chars # It's highly likely you DON'T want to override this function but the *Inner # version of it. def ComputeCandidates( self, request_data ): if ( not ForceSemanticCompletion( request_data ) and not self.ShouldUseNow( request_data ) ): return [] candidates = self._GetCandidatesFromSubclass( request_data ) if request_data[ 'query' ]: candidates = self.FilterAndSortCandidates( candidates, request_data[ 'query' ] ) return candidates def _GetCandidatesFromSubclass( self, request_data ): cache_completions = self._completions_cache.GetCompletionsIfCacheValid( request_data[ 'line_num' ], request_data[ 'start_column' ] ) if cache_completions: return cache_completions else: raw_completions = self.ComputeCandidatesInner( request_data ) self._completions_cache.Update( request_data[ 'line_num' ], request_data[ 'start_column' ], raw_completions ) return raw_completions def ComputeCandidatesInner( self, request_data ): pass def DefinedSubcommands( self ): return [] def UserCommandsHelpMessage( self ): subcommands = self.DefinedSubcommands() if subcommands: return ( 'Supported commands are:\n' + '\n'.join( subcommands ) + '\nSee the docs for information on what they do.' ) else: return 'This Completer has no supported subcommands.' def FilterAndSortCandidates( self, candidates, query ): if not candidates: return [] # We need to handle both an omni_completer style completer and a server # style completer if 'words' in candidates: candidates = candidates[ 'words' ] sort_property = '' if 'word' in candidates[ 0 ]: sort_property = 'word' elif 'insertion_text' in candidates[ 0 ]: sort_property = 'insertion_text' matches = FilterAndSortCandidates( candidates, sort_property, ToUtf8IfNeeded( query ) ) return matches def OnFileReadyToParse( self, request_data ): pass def OnBufferVisit( self, request_data ): pass def OnBufferUnload( self, request_data ): pass def OnInsertLeave( self, request_data ): pass def OnUserCommand( self, arguments, request_data ): raise NotImplementedError( NO_USER_COMMANDS ) def OnCurrentIdentifierFinished( self, request_data ): pass def GetDiagnosticsForCurrentFile( self, request_data ): raise NoDiagnosticSupport def GetDetailedDiagnostic( self, request_data ): raise NoDiagnosticSupport def _CurrentFiletype( self, filetypes ): supported = self.SupportedFiletypes() for filetype in filetypes: if filetype in supported: return filetype return filetypes[0] @abc.abstractmethod def SupportedFiletypes( self ): pass def DebugInfo( self, request_data ): return '' def Shutdown( self ): pass class CompletionsCache( object ): def __init__( self ): self._access_lock = threading.Lock() self.Invalidate() def Invalidate( self ): with self._access_lock: self._line = -1 self._column = -1 self._completions = [] def Update( self, line, column, completions ): with self._access_lock: self._line = line self._column = column self._completions = completions def GetCompletions( self ): with self._access_lock: return self._completions def GetCompletionsIfCacheValid( self, current_line, start_column ): with self._access_lock: if not self._CacheValidNoLock( current_line, start_column ): return None return self._completions def CacheValid( self, current_line, start_column ): with self._access_lock: return self._CacheValidNoLock( current_line, start_column ) def _CacheValidNoLock( self, current_line, start_column ): return current_line == self._line and start_column == self._column vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/completer_utils.py000066400000000000000000000044711227567565400274420ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from collections import defaultdict from copy import deepcopy import os DEFAULT_FILETYPE_TRIGGERS = { 'c' : ['->', '.'], 'objc' : ['->', '.'], 'ocaml' : ['.', '#'], 'cpp,objcpp' : ['->', '.', '::'], 'perl' : ['->'], 'php' : ['->', '::'], 'cs,java,javascript,d,vim,python,perl6,scala,vb,elixir,go' : ['.'], 'ruby' : ['.', '::'], 'lua' : ['.', ':'], 'erlang' : [':'], } def _FiletypeTriggerDictFromSpec( trigger_dict_spec ): triggers_for_filetype = defaultdict( set ) for key, value in trigger_dict_spec.iteritems(): filetypes = key.split( ',' ) for filetype in filetypes: triggers_for_filetype[ filetype ].update( value ) return triggers_for_filetype def _FiletypeDictUnion( dict_one, dict_two ): """Returns a new filetye dict that's a union of the provided two dicts. Dict params are supposed to be type defaultdict(set).""" final_dict = deepcopy( dict_one ) for key, value in dict_two.iteritems(): final_dict[ key ].update( value ) return final_dict def TriggersForFiletype( user_triggers ): default_triggers = _FiletypeTriggerDictFromSpec( DEFAULT_FILETYPE_TRIGGERS ) return _FiletypeDictUnion( default_triggers, dict( user_triggers ) ) def _PathToCompletersFolder(): dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) ) return os.path.join( dir_of_current_script ) def PathToFiletypeCompleterPluginLoader( filetype ): return os.path.join( _PathToCompletersFolder(), filetype, 'hook.py' ) def FiletypeCompleterExistsForFiletype( filetype ): return os.path.exists( PathToFiletypeCompleterPluginLoader( filetype ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/completer_utils_test.py000066400000000000000000000033571227567565400305030ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from collections import defaultdict from nose.tools import eq_ from ycm.test_utils import MockVimModule vim_mock = MockVimModule() from ycm.completers import completer_utils def FiletypeTriggerDictFromSpec_Works_test(): eq_( defaultdict( set, { 'foo': set(['zoo', 'bar']), 'goo': set(['moo']), 'moo': set(['moo']), 'qux': set(['q']) } ), completer_utils._FiletypeTriggerDictFromSpec( { 'foo': ['zoo', 'bar'], 'goo,moo': ['moo'], 'qux': ['q'] } ) ) def FiletypeDictUnion_Works_test(): eq_( defaultdict( set, { 'foo': set(['zoo', 'bar', 'maa']), 'goo': set(['moo']), 'bla': set(['boo']), 'qux': set(['q']) } ), completer_utils._FiletypeDictUnion( defaultdict( set, { 'foo': set(['zoo', 'bar']), 'goo': set(['moo']), 'qux': set(['q']) } ), defaultdict( set, { 'foo': set(['maa']), 'bla': set(['boo']), 'qux': set(['q']) } ) ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/000077500000000000000000000000001227567565400244325ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/__init__.py000066400000000000000000000000001227567565400265310ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/clang_completer.py000066400000000000000000000246621227567565400301540ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from collections import defaultdict import ycm_core from ycm.server import responses from ycm import extra_conf_store from ycm.utils import ToUtf8IfNeeded from ycm.completers.completer import Completer from ycm.completers.cpp.flags import Flags, PrepareFlagsForClang CLANG_FILETYPES = set( [ 'c', 'cpp', 'objc', 'objcpp' ] ) MIN_LINES_IN_FILE_TO_PARSE = 5 PARSING_FILE_MESSAGE = 'Still parsing file, no completions yet.' NO_COMPILE_FLAGS_MESSAGE = 'Still no compile flags, no completions yet.' INVALID_FILE_MESSAGE = 'File is invalid.' NO_COMPLETIONS_MESSAGE = 'No completions found; errors in the file?' FILE_TOO_SHORT_MESSAGE = ( 'File is less than {0} lines long; not compiling.'.format( MIN_LINES_IN_FILE_TO_PARSE ) ) NO_DIAGNOSTIC_MESSAGE = 'No diagnostic for current line!' PRAGMA_DIAG_TEXT_TO_IGNORE = '#pragma once in main file' TOO_MANY_ERRORS_DIAG_TEXT_TO_IGNORE = 'too many errors emitted, stopping now' class ClangCompleter( Completer ): def __init__( self, user_options ): super( ClangCompleter, self ).__init__( user_options ) self._max_diagnostics_to_display = user_options[ 'max_diagnostics_to_display' ] self._completer = ycm_core.ClangCompleter() self._flags = Flags() self._diagnostic_store = None def SupportedFiletypes( self ): return CLANG_FILETYPES def GetUnsavedFilesVector( self, request_data ): files = ycm_core.UnsavedFileVec() for filename, file_data in request_data[ 'file_data' ].iteritems(): if not ClangAvailableForFiletypes( file_data[ 'filetypes' ] ): continue contents = file_data[ 'contents' ] if not contents or not filename: continue unsaved_file = ycm_core.UnsavedFile() utf8_contents = ToUtf8IfNeeded( contents ) unsaved_file.contents_ = utf8_contents unsaved_file.length_ = len( utf8_contents ) unsaved_file.filename_ = ToUtf8IfNeeded( filename ) files.append( unsaved_file ) return files def ComputeCandidatesInner( self, request_data ): filename = request_data[ 'filepath' ] if not filename: return if self._completer.UpdatingTranslationUnit( ToUtf8IfNeeded( filename ) ): raise RuntimeError( PARSING_FILE_MESSAGE ) flags = self._FlagsForRequest( request_data ) if not flags: raise RuntimeError( NO_COMPILE_FLAGS_MESSAGE ) files = self.GetUnsavedFilesVector( request_data ) line = request_data[ 'line_num' ] + 1 column = request_data[ 'start_column' ] + 1 results = self._completer.CandidatesForLocationInFile( ToUtf8IfNeeded( filename ), line, column, files, flags ) if not results: raise RuntimeError( NO_COMPLETIONS_MESSAGE ) return [ ConvertCompletionData( x ) for x in results ] def DefinedSubcommands( self ): return [ 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration', 'ClearCompilationFlagCache'] def OnUserCommand( self, arguments, request_data ): if not arguments: raise ValueError( self.UserCommandsHelpMessage() ) command = arguments[ 0 ] if command == 'GoToDefinition': return self._GoToDefinition( request_data ) elif command == 'GoToDeclaration': return self._GoToDeclaration( request_data ) elif command == 'GoToDefinitionElseDeclaration': return self._GoToDefinitionElseDeclaration( request_data ) elif command == 'ClearCompilationFlagCache': return self._ClearCompilationFlagCache() raise ValueError( self.UserCommandsHelpMessage() ) def _LocationForGoTo( self, goto_function, request_data ): filename = request_data[ 'filepath' ] if not filename: raise ValueError( INVALID_FILE_MESSAGE ) flags = self._FlagsForRequest( request_data ) if not flags: raise ValueError( NO_COMPILE_FLAGS_MESSAGE ) files = self.GetUnsavedFilesVector( request_data ) line = request_data[ 'line_num' ] + 1 column = request_data[ 'column_num' ] + 1 return getattr( self._completer, goto_function )( ToUtf8IfNeeded( filename ), line, column, files, flags ) def _GoToDefinition( self, request_data ): location = self._LocationForGoTo( 'GetDefinitionLocation', request_data ) if not location or not location.IsValid(): raise RuntimeError( 'Can\'t jump to definition.' ) return responses.BuildGoToResponse( location.filename_, location.line_number_ - 1, location.column_number_ - 1) def _GoToDeclaration( self, request_data ): location = self._LocationForGoTo( 'GetDeclarationLocation', request_data ) if not location or not location.IsValid(): raise RuntimeError( 'Can\'t jump to declaration.' ) return responses.BuildGoToResponse( location.filename_, location.line_number_ - 1, location.column_number_ - 1) def _GoToDefinitionElseDeclaration( self, request_data ): location = self._LocationForGoTo( 'GetDefinitionLocation', request_data ) if not location or not location.IsValid(): location = self._LocationForGoTo( 'GetDeclarationLocation', request_data ) if not location or not location.IsValid(): raise RuntimeError( 'Can\'t jump to definition or declaration.' ) return responses.BuildGoToResponse( location.filename_, location.line_number_ - 1, location.column_number_ - 1) def _ClearCompilationFlagCache( self ): self._flags.Clear() def OnFileReadyToParse( self, request_data ): filename = request_data[ 'filepath' ] contents = request_data[ 'file_data' ][ filename ][ 'contents' ] if contents.count( '\n' ) < MIN_LINES_IN_FILE_TO_PARSE: raise ValueError( FILE_TOO_SHORT_MESSAGE ) if not filename: raise ValueError( INVALID_FILE_MESSAGE ) flags = self._FlagsForRequest( request_data ) if not flags: raise ValueError( NO_COMPILE_FLAGS_MESSAGE ) diagnostics = self._completer.UpdateTranslationUnit( ToUtf8IfNeeded( filename ), self.GetUnsavedFilesVector( request_data ), flags ) diagnostics = _FilterDiagnostics( diagnostics ) self._diagnostic_store = DiagnosticsToDiagStructure( diagnostics ) return [ responses.BuildDiagnosticData( x ) for x in diagnostics[ : self._max_diagnostics_to_display ] ] def OnBufferUnload( self, request_data ): self._completer.DeleteCachesForFile( ToUtf8IfNeeded( request_data[ 'unloaded_buffer' ] ) ) def GetDetailedDiagnostic( self, request_data ): current_line = request_data[ 'line_num' ] + 1 current_column = request_data[ 'column_num' ] + 1 current_file = request_data[ 'filepath' ] if not self._diagnostic_store: raise ValueError( NO_DIAGNOSTIC_MESSAGE ) diagnostics = self._diagnostic_store[ current_file ][ current_line ] if not diagnostics: raise ValueError( NO_DIAGNOSTIC_MESSAGE ) closest_diagnostic = None distance_to_closest_diagnostic = 999 for diagnostic in diagnostics: distance = abs( current_column - diagnostic.location_.column_number_ ) if distance < distance_to_closest_diagnostic: distance_to_closest_diagnostic = distance closest_diagnostic = diagnostic return responses.BuildDisplayMessageResponse( closest_diagnostic.long_formatted_text_ ) def DebugInfo( self, request_data ): filename = request_data[ 'filepath' ] if not filename: return '' flags = self._FlagsForRequest( request_data ) or [] source = extra_conf_store.ModuleFileForSourceFile( filename ) return 'Flags for {0} loaded from {1}:\n{2}'.format( filename, source, list( flags ) ) def _FlagsForRequest( self, request_data ): filename = ToUtf8IfNeeded( request_data[ 'filepath' ] ) if 'compilation_flags' in request_data: return PrepareFlagsForClang( request_data[ 'compilation_flags' ], filename ) client_data = request_data.get( 'extra_conf_data', None ) return self._flags.FlagsForFile( filename, client_data = client_data ) def ConvertCompletionData( completion_data ): return responses.BuildCompletionData( insertion_text = completion_data.TextToInsertInBuffer(), menu_text = completion_data.MainCompletionText(), extra_menu_info = completion_data.ExtraMenuInfo(), kind = completion_data.kind_, detailed_info = completion_data.DetailedInfoForPreviewWindow() ) def DiagnosticsToDiagStructure( diagnostics ): structure = defaultdict( lambda : defaultdict( list ) ) for diagnostic in diagnostics: structure[ diagnostic.location_.filename_ ][ diagnostic.location_.line_number_ ].append( diagnostic ) return structure def ClangAvailableForFiletypes( filetypes ): return any( [ filetype in CLANG_FILETYPES for filetype in filetypes ] ) def InCFamilyFile( filetypes ): return ClangAvailableForFiletypes( filetypes ) def _FilterDiagnostics( diagnostics ): # Clang has an annoying warning that shows up when we try to compile header # files if the header has "#pragma once" inside it. The error is not # legitimate because it shows up because libclang thinks we are compiling a # source file instead of a header file. # # See our issue #216 and upstream bug: # http://llvm.org/bugs/show_bug.cgi?id=16686 # # The second thing we want to filter out are those incredibly annoying "too # many errors emitted" diagnostics that are utterly useless. return [ x for x in diagnostics if x.text_ != PRAGMA_DIAG_TEXT_TO_IGNORE and x.text_ != TOO_MANY_ERRORS_DIAG_TEXT_TO_IGNORE ] vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/clang_helpers.py000066400000000000000000000020151227567565400276100ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . def PrepareClangFlags( flags, filename ): # When flags come from the compile_commands.json file, the first flag is # usually the path to the compiler that should be invoked. We want to strip # that. if flags and not flags[ 0 ].startswith( '-' ): return flags[ 1: ] return flags vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/flags.py000066400000000000000000000144741227567565400261120ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import ycm_core import os import inspect from ycm import extra_conf_store from ycm.utils import ToUtf8IfNeeded from ycm.server.responses import NoExtraConfDetected INCLUDE_FLAGS = [ '-isystem', '-I', '-iquote', '--sysroot=', '-isysroot', '-include' ] class Flags( object ): """Keeps track of the flags necessary to compile a file. The flags are loaded from user-created python files (hereafter referred to as 'modules') that contain a method FlagsForFile( filename ).""" def __init__( self ): # It's caches all the way down... self.flags_for_file = {} self.special_clang_flags = _SpecialClangIncludes() self.no_extra_conf_file_warning_posted = False def FlagsForFile( self, filename, add_special_clang_flags = True, client_data = None ): try: return self.flags_for_file[ filename ] except KeyError: module = extra_conf_store.ModuleForSourceFile( filename ) if not module: if not self.no_extra_conf_file_warning_posted: self.no_extra_conf_file_warning_posted = True raise NoExtraConfDetected return None results = _CallExtraConfFlagsForFile( module, filename, client_data ) if not results or not results.get( 'flags_ready', True ): return None flags = list( results[ 'flags' ] ) if not flags: return None if add_special_clang_flags: flags += self.special_clang_flags sanitized_flags = PrepareFlagsForClang( flags, filename ) if results[ 'do_cache' ]: self.flags_for_file[ filename ] = sanitized_flags return sanitized_flags def UserIncludePaths( self, filename ): flags = self.FlagsForFile( filename, False ) if not flags: return [] include_paths = [] path_flags = [ '-isystem', '-I', '-iquote' ] next_flag_is_include_path = False for flag in flags: if next_flag_is_include_path: next_flag_is_include_path = False include_paths.append( flag ) for path_flag in path_flags: if flag == path_flag: next_flag_is_include_path = True break if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] include_paths.append( path ) return [ x for x in include_paths if x ] def Clear( self ): self.flags_for_file.clear() def _CallExtraConfFlagsForFile( module, filename, client_data ): filename = ToUtf8IfNeeded( filename ) # For the sake of backwards compatibility, we need to first check whether the # FlagsForFile function in the extra conf module even allows keyword args. if inspect.getargspec( module.FlagsForFile ).keywords: return module.FlagsForFile( filename, client_data = client_data ) else: return module.FlagsForFile( filename ) def PrepareFlagsForClang( flags, filename ): flags = _RemoveUnusedFlags( flags, filename ) flags = _SanitizeFlags( flags ) return flags def _SanitizeFlags( flags ): """Drops unsafe flags. Currently these are only -arch flags; they tend to crash libclang.""" sanitized_flags = [] saw_arch = False for i, flag in enumerate( flags ): if flag == '-arch': saw_arch = True continue elif flag.startswith( '-arch' ): continue elif saw_arch: saw_arch = False continue sanitized_flags.append( flag ) vector = ycm_core.StringVec() for flag in sanitized_flags: vector.append( ToUtf8IfNeeded( flag ) ) return vector def _RemoveUnusedFlags( flags, filename ): """Given an iterable object that produces strings (flags for Clang), removes the '-c' and '-o' options that Clang does not like to see when it's producing completions for a file. Also removes the first flag in the list if it does not start with a '-' (it's highly likely to be the compiler name/path). We also try to remove any stray filenames in the flags that aren't include dirs.""" new_flags = [] # When flags come from the compile_commands.json file, the first flag is # usually the path to the compiler that should be invoked. We want to strip # that. if not flags[ 0 ].startswith( '-' ): flags = flags[ 1: ] skip_next = False previous_flag_is_include = False previous_flag_starts_with_dash = False current_flag_starts_with_dash = False for flag in flags: previous_flag_starts_with_dash = current_flag_starts_with_dash current_flag_starts_with_dash = flag.startswith( '-' ) if skip_next: skip_next = False continue if flag == '-c': continue if flag == '-o': skip_next = True; continue if flag == filename or os.path.realpath( flag ) == filename: continue # We want to make sure that we don't have any stray filenames in our flags; # filenames that are part of include flags are ok, but others are not. This # solves the case where we ask the compilation database for flags for # "foo.cpp" when we are compiling "foo.h" because the comp db doesn't have # flags for headers. The returned flags include "foo.cpp" and we need to # remove that. if ( not current_flag_starts_with_dash and ( not previous_flag_starts_with_dash or ( not previous_flag_is_include and '/' in flag ) ) ): continue new_flags.append( flag ) previous_flag_is_include = flag in INCLUDE_FLAGS return new_flags def _SpecialClangIncludes(): libclang_dir = os.path.dirname( ycm_core.__file__ ) path_to_includes = os.path.join( libclang_dir, 'clang_includes' ) return [ '-isystem', path_to_includes ] vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/hook.py000066400000000000000000000016751227567565400257550ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import ycm_core from ycm.completers.cpp.clang_completer import ClangCompleter def GetCompleter( user_options ): if ycm_core.HasClangSupport(): return ClangCompleter( user_options ) else: return None vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/tests/000077500000000000000000000000001227567565400255745ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/tests/__init__.py000066400000000000000000000000001227567565400276730ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cpp/tests/flags_test.py000066400000000000000000000075221227567565400303070ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from nose.tools import eq_ from .. import flags def SanitizeFlags_Passthrough_test(): eq_( [ '-foo', '-bar' ], list( flags._SanitizeFlags( [ '-foo', '-bar' ] ) ) ) def SanitizeFlags_ArchRemoved_test(): expected = [ '-foo', '-bar' ] to_remove = [ '-arch', 'arch_of_evil' ] eq_( expected, list( flags._SanitizeFlags( expected + to_remove ) ) ) eq_( expected, list( flags._SanitizeFlags( to_remove + expected ) ) ) eq_( expected, list( flags._SanitizeFlags( expected[ :1 ] + to_remove + expected[ -1: ] ) ) ) def RemoveUnusedFlags_Passthrough_test(): eq_( [ '-foo', '-bar' ], flags._RemoveUnusedFlags( [ '-foo', '-bar' ], 'file' ) ) def RemoveUnusedFlags_RemoveCompilerPathIfFirst_test(): def tester( path ): eq_( expected, flags._RemoveUnusedFlags( [ path ] + expected, filename ) ) compiler_paths = [ 'c++', 'c', 'gcc', 'g++', 'clang', 'clang++', '/usr/bin/c++', '/some/other/path', 'some_command' ] expected = [ '-foo', '-bar' ] filename = 'file' for compiler in compiler_paths: yield tester, compiler def RemoveUnusedFlags_RemoveDashC_test(): expected = [ '-foo', '-bar' ] to_remove = [ '-c' ] filename = 'file' eq_( expected, flags._RemoveUnusedFlags( expected + to_remove, filename ) ) eq_( expected, flags._RemoveUnusedFlags( to_remove + expected, filename ) ) eq_( expected, flags._RemoveUnusedFlags( expected[ :1 ] + to_remove + expected[ -1: ], filename ) ) def RemoveUnusedFlags_RemoveDashO_test(): expected = [ '-foo', '-bar' ] to_remove = [ '-o', 'output_name' ] filename = 'file' eq_( expected, flags._RemoveUnusedFlags( expected + to_remove, filename ) ) eq_( expected, flags._RemoveUnusedFlags( to_remove + expected, filename ) ) eq_( expected, flags._RemoveUnusedFlags( expected[ :1 ] + to_remove + expected[ -1: ], filename ) ) def RemoveUnusedFlags_RemoveFilename_test(): expected = [ '-foo', '-bar' ] to_remove = [ 'file' ] filename = 'file' eq_( expected, flags._RemoveUnusedFlags( expected + to_remove, filename ) ) eq_( expected, flags._RemoveUnusedFlags( to_remove + expected, filename ) ) eq_( expected, flags._RemoveUnusedFlags( expected[ :1 ] + to_remove + expected[ -1: ], filename ) ) def RemoveUnusedFlags_RemoveFlagWithoutPrecedingDashFlag_test(): expected = [ '-foo', '-x', 'c++', '-bar', 'include_dir' ] to_remove = [ 'unrelated_file' ] filename = 'file' eq_( expected, flags._RemoveUnusedFlags( expected + to_remove, filename ) ) eq_( expected, flags._RemoveUnusedFlags( to_remove + expected, filename ) ) def RemoveUnusedFlags_RemoveFilenameWithoutPrecedingInclude_test(): expected = [ '-I', '/foo/bar', '-isystem/zoo/goo' ] to_remove = [ '/moo/boo' ] filename = 'file' eq_( expected, flags._RemoveUnusedFlags( expected + to_remove, filename ) ) eq_( expected, flags._RemoveUnusedFlags( to_remove + expected, filename ) ) eq_( expected + expected, flags._RemoveUnusedFlags( expected + to_remove + expected, filename ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cs/000077500000000000000000000000001227567565400242555ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cs/__init__.py000066400000000000000000000000001227567565400263540ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cs/cs_completer.py000077500000000000000000000217311227567565400273150ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (C) 2011, 2012 Chiel ten Brinke # 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 . import os import glob from ycm.completers.completer import Completer from ycm.server import responses from ycm import utils import urllib2 import urllib import urlparse import json import logging SERVER_NOT_FOUND_MSG = ( 'OmniSharp server binary not found at {0}. ' + 'Did you compile it? You can do so by running ' + '"./install.sh --omnisharp-completer".' ) class CsharpCompleter( Completer ): """ A Completer that uses the Omnisharp server as completion engine. """ def __init__( self, user_options ): super( CsharpCompleter, self ).__init__( user_options ) self._omnisharp_port = None self._logger = logging.getLogger( __name__ ) def Shutdown( self ): if ( self.user_options[ 'auto_stop_csharp_server' ] and self._ServerIsRunning() ): self._StopServer() def SupportedFiletypes( self ): """ Just csharp """ return [ 'cs' ] def ComputeCandidatesInner( self, request_data ): return [ responses.BuildCompletionData( completion[ 'CompletionText' ], completion[ 'DisplayText' ], completion[ 'Description' ] ) for completion in self._GetCompletions( request_data ) ] def DefinedSubcommands( self ): return [ 'StartServer', 'StopServer', 'RestartServer', 'ServerRunning', 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration' ] def OnFileReadyToParse( self, request_data ): if ( not self._omnisharp_port and self.user_options[ 'auto_start_csharp_server' ] ): self._StartServer( request_data ) def OnUserCommand( self, arguments, request_data ): if not arguments: raise ValueError( self.UserCommandsHelpMessage() ) command = arguments[ 0 ] if command == 'StartServer': return self._StartServer( request_data ) elif command == 'StopServer': return self._StopServer() elif command == 'RestartServer': if self._ServerIsRunning(): self._StopServer() return self._StartServer( request_data ) elif command == 'ServerRunning': return self._ServerIsRunning() elif command in [ 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration' ]: return self._GoToDefinition( request_data ) raise ValueError( self.UserCommandsHelpMessage() ) def DebugInfo( self ): if self._ServerIsRunning(): return 'Server running at: {0}\nLogfiles:\n{1}\n{2}'.format( self._ServerLocation(), self._filename_stdout, self._filename_stderr ) else: return 'Server is not running' def _StartServer( self, request_data ): """ Start the OmniSharp server """ self._logger.info( 'startup' ) self._omnisharp_port = utils.GetUnusedLocalhostPort() solution_files, folder = _FindSolutionFiles( request_data[ 'filepath' ] ) if len( solution_files ) == 0: raise RuntimeError( 'Error starting OmniSharp server: no solutionfile found' ) elif len( solution_files ) == 1: solutionfile = solution_files[ 0 ] else: # multiple solutions found : if there is one whose name is the same # as the folder containing the file we edit, use this one # (e.g. if we have bla/Project.sln and we are editing # bla/Project/Folder/File.cs, use bla/Project.sln) filepath_components = _PathComponents( request_data[ 'filepath' ] ) solutionpath = _PathComponents( folder ) foldername = '' if len( filepath_components ) > len( solutionpath ): foldername = filepath_components[ len( solutionpath ) ] solution_file_candidates = [ solutionfile for solutionfile in solution_files if _GetFilenameWithoutExtension( solutionfile ) == foldername ] if len( solution_file_candidates ) == 1: solutionfile = solution_file_candidates[ 0 ] else: raise RuntimeError( 'Found multiple solution files instead of one!\n{0}'.format( solution_files ) ) omnisharp = os.path.join( os.path.abspath( os.path.dirname( __file__ ) ), 'OmniSharpServer/OmniSharp/bin/Debug/OmniSharp.exe' ) if not os.path.isfile( omnisharp ): raise RuntimeError( SERVER_NOT_FOUND_MSG.format( omnisharp ) ) path_to_solutionfile = os.path.join( folder, solutionfile ) # we need to pass the command to Popen as a string since we're passing # shell=True (as recommended by Python's doc) command = ( omnisharp + ' -p ' + str( self._omnisharp_port ) + ' -s ' + path_to_solutionfile ) if not utils.OnWindows(): command = 'mono ' + command filename_format = os.path.join( utils.PathToTempDir(), 'omnisharp_{port}_{sln}_{std}.log' ) self._filename_stdout = filename_format.format( port=self._omnisharp_port, sln=solutionfile, std='stdout' ) self._filename_stderr = filename_format.format( port=self._omnisharp_port, sln=solutionfile, std='stderr' ) with open( self._filename_stderr, 'w' ) as fstderr: with open( self._filename_stdout, 'w' ) as fstdout: # shell=True is needed for Windows so OmniSharp does not spawn # in a new visible window utils.SafePopen( command, stdout=fstdout, stderr=fstderr, shell=True ) self._logger.info( 'Starting OmniSharp server' ) def _StopServer( self ): """ Stop the OmniSharp server """ self._GetResponse( '/stopserver' ) self._omnisharp_port = None self._logger.info( 'Stopping OmniSharp server' ) def _GetCompletions( self, request_data ): """ Ask server for completions """ completions = self._GetResponse( '/autocomplete', self._DefaultParameters( request_data ) ) return completions if completions != None else [] def _GoToDefinition( self, request_data ): """ Jump to definition of identifier under cursor """ definition = self._GetResponse( '/gotodefinition', self._DefaultParameters( request_data ) ) if definition[ 'FileName' ] != None: return responses.BuildGoToResponse( definition[ 'FileName' ], definition[ 'Line' ], definition[ 'Column' ] ) else: raise RuntimeError( 'Can\'t jump to definition' ) def _DefaultParameters( self, request_data ): """ Some very common request parameters """ parameters = {} parameters[ 'line' ] = request_data[ 'line_num' ] + 1 parameters[ 'column' ] = request_data[ 'column_num' ] + 1 filepath = request_data[ 'filepath' ] parameters[ 'buffer' ] = request_data[ 'file_data' ][ filepath ][ 'contents' ] parameters[ 'filename' ] = filepath return parameters def _ServerIsRunning( self ): """ Check if our OmniSharp server is running """ try: return bool( self._omnisharp_port and self._GetResponse( '/checkalivestatus', silent = True ) ) except: return False def _ServerLocation( self ): return 'http://localhost:' + str( self._omnisharp_port ) def _GetResponse( self, handler, parameters = {}, silent = False ): """ Handle communication with server """ # TODO: Replace usage of urllib with Requests target = urlparse.urljoin( self._ServerLocation(), handler ) parameters = urllib.urlencode( parameters ) response = urllib2.urlopen( target, parameters ) return json.loads( response.read() ) def _FindSolutionFiles( filepath ): """ Find solution files by searching upwards in the file tree """ folder = os.path.dirname( filepath ) solutionfiles = glob.glob1( folder, '*.sln' ) while not solutionfiles: lastfolder = folder folder = os.path.dirname( folder ) if folder == lastfolder: break solutionfiles = glob.glob1( folder, '*.sln' ) return solutionfiles, folder def _PathComponents( path ): path_components = [] while True: path, folder = os.path.split( path ) if folder: path_components.append( folder ) else: if path: path_components.append( path ) break path_components.reverse() return path_components def _GetFilenameWithoutExtension( path ): return os.path.splitext( os.path.basename ( path ) )[ 0 ] vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/cs/hook.py000066400000000000000000000015631227567565400255740ustar00rootroot00000000000000# Copyright (C) 2011, 2012 Chiel ten Brinke # # 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 . from ycm.completers.cs.cs_completer import CsharpCompleter def GetCompleter( user_options ): return CsharpCompleter( user_options ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/000077500000000000000000000000001227567565400252655ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/__init__.py000066400000000000000000000000001227567565400273640ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/filename_completer.py000066400000000000000000000122371227567565400314760ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (C) 2013 Stanislav Golovanov # Google Inc. # # 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 . import os import re from ycm.completers.completer import Completer from ycm.completers.cpp.clang_completer import InCFamilyFile from ycm.completers.cpp.flags import Flags from ycm.utils import ToUtf8IfNeeded from ycm.server import responses class FilenameCompleter( Completer ): """ General completer that provides filename and filepath completions. """ def __init__( self, user_options ): super( FilenameCompleter, self ).__init__( user_options ) self._flags = Flags() self._path_regex = re.compile( """ # 1 or more 'D:/'-like token or '/' or '~' or './' or '../' (?:[A-z]+:/|[/~]|\./|\.+/)+ # any alphanumeric symbal and space literal (?:[ /a-zA-Z0-9()$+_~.\x80-\xff-\[\]]| # skip any special symbols [^\x20-\x7E]| # backslash and 1 char after it. + matches 1 or more of whole group \\.)*$ """, re.X ) include_regex_common = '^\s*#(?:include|import)\s*(?:"|<)' self._include_start_regex = re.compile( include_regex_common + '$' ) self._include_regex = re.compile( include_regex_common ) def AtIncludeStatementStart( self, request_data ): start_column = request_data[ 'start_column' ] current_line = request_data[ 'line_value' ] filepath = ToUtf8IfNeeded( request_data[ 'filepath' ] ) filetypes = request_data[ 'file_data' ][ filepath ][ 'filetypes' ] return ( InCFamilyFile( filetypes ) and self._include_start_regex.match( current_line[ :start_column ] ) ) def ShouldUseNowInner( self, request_data ): start_column = request_data[ 'start_column' ] current_line = request_data[ 'line_value' ] return ( start_column and ( current_line[ start_column - 1 ] == '/' or self.AtIncludeStatementStart( request_data ) ) ) def SupportedFiletypes( self ): return [] def ComputeCandidatesInner( self, request_data ): current_line = request_data[ 'line_value' ] start_column = request_data[ 'start_column' ] filepath = ToUtf8IfNeeded( request_data[ 'filepath' ] ) filetypes = request_data[ 'file_data' ][ filepath ][ 'filetypes' ] line = current_line[ :start_column ] if InCFamilyFile( filetypes ): include_match = self._include_regex.search( line ) if include_match: path_dir = line[ include_match.end(): ] # We do what GCC does for <> versus "": # http://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html include_current_file_dir = '<' not in include_match.group() return _GenerateCandidatesForPaths( self.GetPathsIncludeCase( path_dir, include_current_file_dir, filepath ) ) path_match = self._path_regex.search( line ) path_dir = os.path.expanduser( path_match.group() ) if path_match else '' return _GenerateCandidatesForPaths( _GetPathsStandardCase( path_dir, self.user_options[ 'filepath_completion_use_working_dir' ], filepath ) ) def GetPathsIncludeCase( self, path_dir, include_current_file_dir, filepath ): paths = [] include_paths = self._flags.UserIncludePaths( filepath ) if include_current_file_dir: include_paths.append( os.path.dirname( filepath ) ) for include_path in include_paths: try: relative_paths = os.listdir( os.path.join( include_path, path_dir ) ) except: relative_paths = [] paths.extend( os.path.join( include_path, path_dir, relative_path ) for relative_path in relative_paths ) return sorted( set( paths ) ) def _GetPathsStandardCase( path_dir, use_working_dir, filepath ): if not use_working_dir and not path_dir.startswith( '/' ): path_dir = os.path.join( os.path.dirname( filepath ), path_dir ) try: relative_paths = os.listdir( path_dir ) except: relative_paths = [] return ( os.path.join( path_dir, relative_path ) for relative_path in relative_paths ) def _GenerateCandidatesForPaths( absolute_paths ): seen_basenames = set() completion_dicts = [] for absolute_path in absolute_paths: basename = os.path.basename( absolute_path ) if basename in seen_basenames: continue seen_basenames.add( basename ) is_dir = os.path.isdir( absolute_path ) completion_dicts.append( responses.BuildCompletionData( basename, '[Dir]' if is_dir else '[File]' ) ) return completion_dicts vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/general_completer_store.py000066400000000000000000000075411227567565400325510ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (C) 2013 Stanislav Golovanov # 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 . from ycm.completers.completer import Completer from ycm.completers.all.identifier_completer import IdentifierCompleter from ycm.completers.general.filename_completer import FilenameCompleter from ycm.completers.general.ultisnips_completer import UltiSnipsCompleter class GeneralCompleterStore( Completer ): """ Holds a list of completers that can be used in all filetypes. It overrides all Competer API methods so that specific calls to GeneralCompleterStore are passed to all general completers. """ def __init__( self, user_options ): super( GeneralCompleterStore, self ).__init__( user_options ) self._identifier_completer = IdentifierCompleter( user_options ) self._filename_completer = FilenameCompleter( user_options ) self._ultisnips_completer = UltiSnipsCompleter( user_options ) self._non_filename_completers = [ self._identifier_completer ] if user_options.get( 'use_ultisnips_completer', True ): self._non_filename_completers.append( self._ultisnips_completer ) self._all_completers = [ self._identifier_completer, self._filename_completer, self._ultisnips_completer ] self._current_query_completers = [] def SupportedFiletypes( self ): return set() def GetIdentifierCompleter( self ): return self._identifier_completer def ShouldUseNow( self, request_data ): self._current_query_completers = [] if self._filename_completer.ShouldUseNow( request_data ): self._current_query_completers = [ self._filename_completer ] return True should_use_now = False for completer in self._non_filename_completers: should_use_this_completer = completer.ShouldUseNow( request_data ) should_use_now = should_use_now or should_use_this_completer if should_use_this_completer: self._current_query_completers.append( completer ) return should_use_now def ComputeCandidates( self, request_data ): if not self.ShouldUseNow( request_data ): return [] candidates = [] for completer in self._current_query_completers: candidates += completer.ComputeCandidates( request_data ) return candidates def OnFileReadyToParse( self, request_data ): for completer in self._all_completers: completer.OnFileReadyToParse( request_data ) def OnBufferVisit( self, request_data ): for completer in self._all_completers: completer.OnBufferVisit( request_data ) def OnBufferUnload( self, request_data ): for completer in self._all_completers: completer.OnBufferUnload( request_data ) def OnInsertLeave( self, request_data ): for completer in self._all_completers: completer.OnInsertLeave( request_data ) def OnCurrentIdentifierFinished( self, request_data ): for completer in self._all_completers: completer.OnCurrentIdentifierFinished( request_data ) def GettingCompletions( self ): for completer in self._all_completers: completer.GettingCompletions() def Shutdown( self ): for completer in self._all_completers: completer.Shutdown() vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/syntax_parse.py000066400000000000000000000125541227567565400303660ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import re import vim from ycm import vimsupport SYNTAX_GROUP_REGEX = re.compile( r"""^ (?P\w+) \s+ xxx \s+ (?P.+?) $""", 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', ]) # These are the parent groups from which we want to extract keywords ROOT_GROUPS = set([ 'Statement', 'Boolean', 'Include', 'Type', ]) 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.GetVariableValue( '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' ) # 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' ) } 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 ) 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 group_name_to_group.itervalues(): 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: 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 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/000077500000000000000000000000001227567565400264275ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/__init__.py000066400000000000000000000000001227567565400305260ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/syntax_parse_test.py000066400000000000000000000224761227567565400325730ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import os from nose.tools import eq_ from ycm.test_utils import MockVimModule vim_mock = MockVimModule() from ycm.completers.general import syntax_parse 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 open( full_path_to_test_file ).read() def KeywordsFromSyntaxListOutput_PythonSyntax_test(): eq_( set(['and', 'IndexError', 'elif', 'BytesWarning', 'ZeroDivisionError', 'ImportError', 'is', 'global', 'UnicodeTranslateError', 'GeneratorExit', 'BufferError', 'StopIteration', 'as', 'SystemError', 'UnicodeError', 'EnvironmentError', 'in', 'EOFError', 'LookupError', 'Exception', 'PendingDeprecationWarning', 'if', 'OSError', 'DeprecationWarning', 'raise', 'for', 'FloatingPointError', 'UnicodeWarning', 'VMSError', 'except', 'nonlocal', 'ReferenceError', 'NameError', 'pass', 'finally', 'Warning', 'UnboundLocalError', 'print', 'IOError', 'IndentationError', 'True', 'RuntimeError', 'FutureWarning', 'ImportWarning', 'SystemExit', 'None', 'return', 'StandardError', 'exec', 'ValueError', 'TabError', 'else', 'break', 'SyntaxError', 'UnicodeEncodeError', 'WindowsError', 'not', 'UnicodeDecodeError', 'with', 'class', 'KeyError', 'AssertionError', 'assert', 'TypeError', 'False', 'RuntimeWarning', 'KeyboardInterrupt', 'UserWarning', 'SyntaxWarning', 'yield', 'OverflowError', 'try', 'ArithmeticError', 'while', 'continue', 'del', 'MemoryError', 'NotImplementedError', 'BaseException', 'AttributeError', 'or', 'def', 'lambda', 'from', 'import']), 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(['false', 'synchronized', 'int', 'abstract', 'float', 'private', 'char', 'catch', 'boolean', 'static', 'native', 'for', 'super', 'while', 'long', 'throw', 'strictfp', 'finally', 'continue', 'extends', 'volatile', 'if', 'public', 'match', 'do', 'return', 'void', 'enum', 'else', 'break', 'transient', 'new', 'interface', 'instanceof', 'byte', 'true', 'serializable', 'implements', 'assert', 'short', 'package', 'this', 'double', 'final', 'try', 'default', 'switch', 'protected', 'throws']), syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'java_syntax' ) ) ) def KeywordsFromSyntaxListOutput_Basic_test(): eq_( set([ 'foo', 'bar', 'zoo', 'goo' ]), syntax_parse._KeywordsFromSyntaxListOutput( """ foogroup xxx foo bar zoo goo links to Statement""" ) ) 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', ] ) ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/testdata/000077500000000000000000000000001227567565400302405ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/testdata/cpp_syntax000066400000000000000000000332061227567565400323570ustar00rootroot00000000000000--- 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*]?/ 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 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/testdata/java_syntax000066400000000000000000000372501227567565400325210ustar00rootroot00000000000000--- 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 /#\|=\(\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*\/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*\/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=/\/ 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 =]/ 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 /\/ 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 contains=htmlCommentPart,htmlCommentError,@Spell start=// contained keepend links to Comment htmlPreStmt xxx match // 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=/\_[^>]*\/ end=++me=e-4 contained contains=@Spell,htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,htmlLeadingSpace,javaScript,@htmlPreproc links to Underlined htmlBoldUnderline xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic htmlBoldItalic xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlBoldItalicUnderline start=// end=++me=e-5 contained contains=@htmlTop,htmlBoldItalicUnderline htmlBold xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic start=// end=++me=e-9 contained contains=@htmlTop,htmlBoldUnderline,htmlBoldItalic htmlBoldUnderlineItalic xxx start=// end=++me=e-4 contained contains=@htmlTop start=// end=++me=e-5 contained contains=@htmlTop htmlBoldItalicUnderline xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlBoldUnderlineItalic links to htmlBoldUnderlineItalic htmlUnderlineBold xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlUnderlineBoldItalic start=// end=++me=e-9 contained contains=@htmlTop,htmlUnderlineBoldItalic links to htmlBoldUnderline htmlUnderlineItalic xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlUnderlineItalicBold start=// end=++me=e-5 contained contains=@htmlTop,htmlUnderlineItalicBold htmlUnderline xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlUnderlineBold,htmlUnderlineItalic htmlUnderlineBoldItalic xxx start=// end=++me=e-4 contained contains=@htmlTop start=// end=++me=e-5 contained contains=@htmlTop links to htmlBoldUnderlineItalic htmlUnderlineItalicBold xxx start=// end=++me=e-4 contained contains=@htmlTop start=// end=++me=e-9 contained contains=@htmlTop links to htmlBoldUnderlineItalic htmlItalicBold xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlItalicBoldUnderline start=// end=++me=e-9 contained contains=@htmlTop,htmlItalicBoldUnderline links to htmlBoldItalic htmlItalicUnderline xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlItalicUnderlineBold links to htmlUnderlineItalic htmlItalic xxx start=// end=++me=e-4 contained contains=@htmlTop,htmlItalicBold,htmlItalicUnderline start=// end=++me=e-5 contained contains=@htmlTop htmlItalicBoldUnderline xxx start=// end=++me=e-4 contained contains=@htmlTop links to htmlBoldUnderlineItalic htmlItalicUnderlineBold xxx start=// end=++me=e-4 contained contains=@htmlTop start=// end=++me=e-9 contained contains=@htmlTop links to htmlBoldUnderlineItalic htmlLeadingSpace xxx match /^\s\+/ contained links to None htmlH1 xxx start=// end=++me=e-5 contained contains=@htmlTop links to Title htmlH2 xxx start=// end=++me=e-5 contained contains=@htmlTop links to htmlH1 htmlH3 xxx start=// end=++me=e-5 contained contains=@htmlTop links to htmlH2 htmlH4 xxx start=// end=++me=e-5 contained contains=@htmlTop links to htmlH3 htmlH5 xxx start=// end=++me=e-5 contained contains=@htmlTop links to htmlH4 htmlH6 xxx start=// end=++me=e-5 contained contains=@htmlTop links to htmlH5 htmlTitle xxx start=// end=++me=e-8 contained contains=htmlTag,htmlEndTag,htmlSpecialChar,htmlPreProc,htmlComment,javaScript,@htmlPreproc links to Title htmlHead xxx start=// end=//me=e-3 end=//me=e-5 end=++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 @"\_[^"]\+"\|\|\(\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 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/tests/testdata/python_syntax000066400000000000000000000105301227567565400331110ustar00rootroot00000000000000--- 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 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general/ultisnips_completer.py000066400000000000000000000034451227567565400317510ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (C) 2013 Stanislav Golovanov # 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 . from ycm.completers.general_completer import GeneralCompleter from ycm.server import responses class UltiSnipsCompleter( GeneralCompleter ): """ General completer that provides UltiSnips snippet names in completions. """ def __init__( self, user_options ): super( UltiSnipsCompleter, self ).__init__( user_options ) self._candidates = None self._filtered_candidates = None def ShouldUseNow( self, request_data ): return self.QueryLengthAboveMinThreshold( request_data ) def ComputeCandidates( self, request_data ): if not self.ShouldUseNow( request_data ): return [] return self.FilterAndSortCandidates( self._candidates, request_data[ 'query' ] ) def OnBufferVisit( self, request_data ): raw_candidates = request_data.get( 'ultisnips_snippets', [] ) self._candidates = [ responses.BuildCompletionData( str( snip[ 'trigger' ] ), str( ' ' + snip[ 'description' ].encode( 'utf-8' ) ) ) for snip in raw_candidates ] vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/general_completer.py000066400000000000000000000023711227567565400277140ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ycm.completers.completer import Completer class GeneralCompleter( Completer ): """ A base class for General completers in YCM. A general completer is used in all filetypes. Because this is a subclass of Completer class, you should refer to the Completer class documentation. Do NOT use this class for semantic completers! Subclass Completer directly. """ def __init__( self, user_options ): super( GeneralCompleter, self ).__init__( user_options ) def SupportedFiletypes( self ): return set() vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/objc/000077500000000000000000000000001227567565400245655ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/objc/hook.py000066400000000000000000000016741227567565400261070ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import ycm_core from ycm.completers.cpp.clang_completer import ClangCompleter def GetCompleter( user_options ): if ycm_core.HasClangSupport(): return ClangCompleter( user_options ) else: return None vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/objcpp/000077500000000000000000000000001227567565400251255ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/objcpp/hook.py000066400000000000000000000016751227567565400264500ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import ycm_core from ycm.completers.cpp.clang_completer import ClangCompleter def GetCompleter( user_options ): if ycm_core.HasClangSupport(): return ClangCompleter( user_options ) else: return None vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/python/000077500000000000000000000000001227567565400251715ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/python/__init__.py000066400000000000000000000000001227567565400272700ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/python/hook.py000066400000000000000000000015631227567565400265100ustar00rootroot00000000000000# Copyright (C) 2011, 2012 Stephen Sugden # # 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 . from ycm.completers.python.jedi_completer import JediCompleter def GetCompleter( user_options ): return JediCompleter( user_options ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/completers/python/jedi_completer.py000066400000000000000000000123251227567565400305330ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (C) 2011, 2012 Stephen Sugden # Google Inc. # Stanislav Golovanov # # 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 . from ycm.completers.completer import Completer from ycm.server import responses try: import jedi except ImportError: raise ImportError( 'Error importing jedi. Make sure the jedi submodule has been checked out. ' 'In the YouCompleteMe folder, run "git submodule update --init --recursive"') class JediCompleter( Completer ): """ A Completer that uses the Jedi completion engine. https://jedi.readthedocs.org/en/latest/ """ def __init__( self, user_options ): super( JediCompleter, self ).__init__( user_options ) def SupportedFiletypes( self ): """ Just python """ return [ 'python' ] def _GetJediScript( self, request_data ): filename = request_data[ 'filepath' ] contents = request_data[ 'file_data' ][ filename ][ 'contents' ] # Jedi expects lines to start at 1, not 0 line = request_data[ 'line_num' ] + 1 column = request_data[ 'column_num' ] return jedi.Script( contents, line, column, filename ) def ComputeCandidatesInner( self, request_data ): script = self._GetJediScript( request_data ) return [ responses.BuildCompletionData( str( completion.name ), str( completion.description ), str( completion.doc ) ) for completion in script.completions() ] def DefinedSubcommands( self ): return [ 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration' ] def OnUserCommand( self, arguments, request_data ): if not arguments: raise ValueError( self.UserCommandsHelpMessage() ) command = arguments[ 0 ] if command == 'GoToDefinition': return self._GoToDefinition( request_data ) elif command == 'GoToDeclaration': return self._GoToDeclaration( request_data ) elif command == 'GoToDefinitionElseDeclaration': return self._GoToDefinitionElseDeclaration( request_data ) raise ValueError( self.UserCommandsHelpMessage() ) def _GoToDefinition( self, request_data ): definitions = self._GetDefinitionsList( request_data ) if definitions: return self._BuildGoToResponse( definitions ) else: raise RuntimeError( 'Can\'t jump to definition.' ) def _GoToDeclaration( self, request_data ): definitions = self._GetDefinitionsList( request_data, declaration = True ) if definitions: return self._BuildGoToResponse( definitions ) else: raise RuntimeError( 'Can\'t jump to declaration.' ) def _GoToDefinitionElseDeclaration( self, request_data ): definitions = ( self._GetDefinitionsList( request_data ) or self._GetDefinitionsList( request_data, declaration = True ) ) if definitions: return self._BuildGoToResponse( definitions ) else: raise RuntimeError( 'Can\'t jump to definition or declaration.' ) def _GetDefinitionsList( self, request_data, declaration = False ): definitions = [] script = self._GetJediScript( request_data ) try: if declaration: definitions = script.goto_definitions() else: definitions = script.goto_assignments() except jedi.NotFoundError: raise RuntimeError( 'Cannot follow nothing. Put your cursor on a valid name.' ) return definitions def _BuildGoToResponse( self, definition_list ): if len( definition_list ) == 1: definition = definition_list[ 0 ] if definition.in_builtin_module(): if definition.is_keyword: raise RuntimeError( 'Cannot get the definition of Python keywords.' ) else: raise RuntimeError( 'Builtin modules cannot be displayed.' ) else: return responses.BuildGoToResponse( definition.module_path, definition.line - 1, definition.column ) else: # multiple definitions defs = [] for definition in definition_list: if definition.in_builtin_module(): defs.append( responses.BuildDescriptionOnlyGoToResponse( 'Builtin ' + definition.description ) ) else: defs.append( responses.BuildGoToResponse( definition.module_path, definition.line - 1, definition.column, definition.description ) ) return defs vim-youcompleteme-0+20140207+git18be5c2/python/ycm/diagnostic_interface.py000066400000000000000000000122261227567565400262140ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from collections import defaultdict 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 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 UpdateWithNewDiagnostics( self, diags ): self._buffer_number_to_line_to_diags = _ConvertDiagListToDict( diags ) if self._user_options[ 'enable_diagnostic_signs' ]: self._next_sign_id = _UpdateSigns( 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' ]: vimsupport.SetLocationList( vimsupport.ConvertDiagnosticsToQfList( 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 vimsupport.EchoTextVimWidth( diags[ 0 ][ 'text' ] ) self._diag_message_needs_clearing = True 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 line_to_diags.itervalues(): 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' ] + 1, location[ 'column_num' ] + 1 ) else: vimsupport.AddDiagnosticSyntaxMatch( location_extent[ 'start' ][ 'line_num' ] + 1, location_extent[ 'start' ][ 'column_num' ] + 1, location_extent[ 'end' ][ 'line_num' ] + 1, location_extent[ 'end' ][ 'column_num' ] + 1, is_error = is_error ) for diag_range in diag[ 'ranges' ]: vimsupport.AddDiagnosticSyntaxMatch( diag_range[ 'start' ][ 'line_num' ] + 1, diag_range[ 'start' ][ 'column_num' ] + 1, diag_range[ 'end' ][ 'line_num' ] + 1, diag_range[ 'end' ][ 'column_num' ] + 1, is_error = is_error ) def _UpdateSigns( buffer_number_to_line_to_diags, next_sign_id ): vimsupport.UnplaceAllSignsInBuffer( vim.current.buffer.number ) for buffer_number, line_to_diags in buffer_number_to_line_to_diags.iteritems(): if not vimsupport.BufferIsVisible( buffer_number ): continue vimsupport.UnplaceAllSignsInBuffer( buffer_number ) for line, diags in line_to_diags.iteritems(): for diag in diags: vimsupport.PlaceSign( next_sign_id, line, buffer_number, _DiagnosticIsError( diag ) ) next_sign_id += 1 return next_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' ] + 1 buffer_to_line_to_diags[ buffer_number ][ line_number ].append( diag ) for line_to_diags in buffer_to_line_to_diags.itervalues(): for diags in line_to_diags.itervalues(): # 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' ] == 'E' vim-youcompleteme-0+20140207+git18be5c2/python/ycm/extra_conf_store.py000066400000000000000000000162401227567565400254140ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . # NOTE: This module is used as a Singleton import os import imp import random import string import sys import logging from threading import Lock from ycm import user_options_store from ycm.server.responses import UnknownExtraConf, YCM_EXTRA_CONF_FILENAME from fnmatch import fnmatch # Singleton variables _module_for_module_file = {} _module_for_module_file_lock = Lock() _module_file_for_source_file = {} _module_file_for_source_file_lock = Lock() def Reset(): global _module_for_module_file, _module_file_for_source_file _module_for_module_file = {} _module_file_for_source_file = {} def ModuleForSourceFile( filename ): return Load( ModuleFileForSourceFile( filename ) ) def ModuleFileForSourceFile( filename ): """This will try all files returned by _ExtraConfModuleSourceFilesForFile in order and return the filename of the first module that was allowed to load. If no module was found or allowed to load, None is returned.""" with _module_file_for_source_file_lock: if not filename in _module_file_for_source_file: for module_file in _ExtraConfModuleSourceFilesForFile( filename ): if Load( module_file ): _module_file_for_source_file[ filename ] = module_file break return _module_file_for_source_file.setdefault( filename ) def CallGlobalExtraConfYcmCorePreloadIfExists(): _CallGlobalExtraConfMethod( 'YcmCorePreload' ) def Shutdown(): # VimClose is for the sake of backwards compatibility; it's a no-op when it # doesn't exist. _CallGlobalExtraConfMethod( 'VimClose' ) _CallGlobalExtraConfMethod( 'Shutdown' ) def _CallGlobalExtraConfMethod( function_name ): logger = _Logger() global_ycm_extra_conf = _GlobalYcmExtraConfFileLocation() if not ( global_ycm_extra_conf and os.path.exists( global_ycm_extra_conf ) ): logger.debug( 'No global extra conf, not calling method ' + function_name ) return module = Load( global_ycm_extra_conf, force = True ) if not module or not hasattr( module, function_name ): logger.debug( 'Global extra conf not loaded or no function ' + function_name ) return logger.info( 'Calling global extra conf method {0} on conf file {1}'.format( function_name, global_ycm_extra_conf ) ) getattr( module, function_name )() def Disable( module_file ): """Disables the loading of a module for the current session.""" with _module_for_module_file_lock: _module_for_module_file[ module_file ] = None def _ShouldLoad( module_file ): """Checks if a module is safe to be loaded. By default this will try to decide using a white-/blacklist and ask the user for confirmation as a fallback.""" if ( module_file == _GlobalYcmExtraConfFileLocation() or not user_options_store.Value( 'confirm_extra_conf' ) ): return True globlist = user_options_store.Value( 'extra_conf_globlist' ) for glob in globlist: is_blacklisted = glob[0] == '!' if _MatchesGlobPattern( module_file, glob.lstrip('!') ): return not is_blacklisted raise UnknownExtraConf( module_file ) def Load( module_file, force = False ): """Load and return the module contained in a file. Using force = True the module will be loaded regardless of the criteria in _ShouldLoad. This will return None if the module was not allowed to be loaded.""" if not module_file: return None if not force: with _module_for_module_file_lock: if module_file in _module_for_module_file: return _module_for_module_file[ module_file ] if not _ShouldLoad( module_file ): Disable( module_file ) return None # This has to be here because a long time ago, the ycm_extra_conf.py files # used to import clang_helpers.py from the cpp folder. This is not needed # anymore, but there are a lot of old ycm_extra_conf.py files that we don't # want to break. sys.path.insert( 0, _PathToCppCompleterFolder() ) module = imp.load_source( _RandomName(), module_file ) del sys.path[ 0 ] with _module_for_module_file_lock: _module_for_module_file[ module_file ] = module return module def _MatchesGlobPattern( filename, glob ): """Returns true if a filename matches a given pattern. A '~' in glob will be expanded to the home directory and checking will be performed using absolute paths. See the documentation of fnmatch for the supported patterns.""" abspath = os.path.abspath( filename ) return fnmatch( abspath, os.path.abspath( os.path.expanduser( glob ) ) ) def _ExtraConfModuleSourceFilesForFile( filename ): """For a given filename, search all parent folders for YCM_EXTRA_CONF_FILENAME files that will compute the flags necessary to compile the file. If _GlobalYcmExtraConfFileLocation() exists it is returned as a fallback.""" for folder in _PathsToAllParentFolders( filename ): candidate = os.path.join( folder, YCM_EXTRA_CONF_FILENAME ) if os.path.exists( candidate ): yield candidate global_ycm_extra_conf = _GlobalYcmExtraConfFileLocation() if ( global_ycm_extra_conf and os.path.exists( global_ycm_extra_conf ) ): yield global_ycm_extra_conf def _PathsToAllParentFolders( filename ): """Build a list of all parent folders of a file. The nearest folders will be returned first. Example: _PathsToAllParentFolders( '/home/user/projects/test.c' ) [ '/home/user/projects', '/home/user', '/home', '/' ]""" def PathFolderComponents( filename ): folders = [] path = os.path.dirname( filename ) while True: path, folder = os.path.split( path ) if folder: folders.append( folder ) else: if path: folders.append( path ) break return list( reversed( folders ) ) parent_folders = PathFolderComponents( filename ) parent_folders = [ os.path.join( *parent_folders[:i + 1] ) for i in xrange( len( parent_folders ) ) ] return reversed( parent_folders ) def _PathToCppCompleterFolder(): """Returns the path to the 'cpp' completer folder. This is necessary because ycm_extra_conf files need it on the path.""" return os.path.join( _DirectoryOfThisScript(), 'completers', 'cpp' ) def _DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def _RandomName(): """Generates a random module name.""" return ''.join( random.choice( string.ascii_lowercase ) for x in range( 15 ) ) def _GlobalYcmExtraConfFileLocation(): return os.path.expanduser( user_options_store.Value( 'global_ycm_extra_conf' ) ) def _Logger(): return logging.getLogger( __name__ ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/000077500000000000000000000000001227567565400230015ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/__init__.py000066400000000000000000000000001227567565400251000ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/default_settings.json000066400000000000000000000015761227567565400272510ustar00rootroot00000000000000{ "filepath_completion_use_working_dir": 0, "auto_trigger": 1, "min_num_of_chars_for_completion": 2, "min_num_identifier_candidate_chars": 0, "semantic_triggers": {}, "filetype_specific_completion_to_disable": { "gitcommit": 1 }, "seed_identifiers_with_syntax": 0, "collect_identifiers_from_comments_and_strings": 0, "collect_identifiers_from_tags_files": 0, "extra_conf_globlist": [], "global_ycm_extra_conf": "", "confirm_extra_conf": 1, "complete_in_comments": 0, "complete_in_strings": 1, "max_diagnostics_to_display": 30, "filetype_whitelist": { "*": 1 }, "filetype_blacklist": { "tagbar": 1, "qf": 1, "notes": 1, "markdown": 1, "unite": 1, "text": 1, "vimwiki": 1, "pandoc": 1 }, "auto_start_csharp_server": 1, "auto_stop_csharp_server": 1, "use_ultisnips_completer": 1, "csharp_server_port": 2000 } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/handlers.py000066400000000000000000000154231227567565400251600ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from os import path try: import ycm_core except ImportError as e: raise RuntimeError( 'Error importing ycm_core. Are you sure you have placed a ' 'version 3.2+ libclang.[so|dll|dylib] in folder "{0}"? ' 'See the Installation Guide in the docs. Full error: {1}'.format( path.realpath( path.join( path.abspath( __file__ ), '../../..' ) ), str( e ) ) ) import atexit import logging import json import bottle import httplib from bottle import request, response import server_state from ycm import user_options_store from ycm.server.responses import BuildExceptionResponse from ycm import extra_conf_store # num bytes for the request body buffer; request.json only works if the request # size is less than this bottle.Request.MEMFILE_MAX = 1000 * 1024 # TODO: rename these to _lower_case SERVER_STATE = None LOGGER = logging.getLogger( __name__ ) app = bottle.Bottle() @app.post( '/event_notification' ) def EventNotification(): LOGGER.info( 'Received event notification' ) request_data = request.json event_name = request_data[ 'event_name' ] LOGGER.debug( 'Event name: %s', event_name ) event_handler = 'On' + event_name getattr( SERVER_STATE.GetGeneralCompleter(), event_handler )( request_data ) filetypes = request_data[ 'filetypes' ] response_data = None if SERVER_STATE.FiletypeCompletionUsable( filetypes ): response_data = getattr( SERVER_STATE.GetFiletypeCompleter( filetypes ), event_handler )( request_data ) if response_data: return _JsonResponse( response_data ) @app.post( '/run_completer_command' ) def RunCompleterCommand(): LOGGER.info( 'Received command request' ) request_data = request.json completer = _GetCompleterForRequestData( request_data ) return _JsonResponse( completer.OnUserCommand( request_data[ 'command_arguments' ], request_data ) ) @app.post( '/completions' ) def GetCompletions(): LOGGER.info( 'Received completion request' ) request_data = request.json do_filetype_completion = SERVER_STATE.ShouldUseFiletypeCompleter( request_data ) LOGGER.debug( 'Using filetype completion: %s', do_filetype_completion ) filetypes = request_data[ 'filetypes' ] completer = ( SERVER_STATE.GetFiletypeCompleter( filetypes ) if do_filetype_completion else SERVER_STATE.GetGeneralCompleter() ) return _JsonResponse( completer.ComputeCandidates( request_data ) ) @app.get( '/user_options' ) def GetUserOptions(): LOGGER.info( 'Received user options GET request' ) return _JsonResponse( dict( SERVER_STATE.user_options ) ) @app.get( '/healthy' ) def GetHealthy(): LOGGER.info( 'Received health request' ) return _JsonResponse( True ) @app.post( '/user_options' ) def SetUserOptions(): LOGGER.info( 'Received user options POST request' ) UpdateUserOptions( request.json ) @app.post( '/semantic_completion_available' ) def FiletypeCompletionAvailable(): LOGGER.info( 'Received filetype completion available request' ) return _JsonResponse( SERVER_STATE.FiletypeCompletionAvailable( request.json[ 'filetypes' ] ) ) @app.post( '/defined_subcommands' ) def DefinedSubcommands(): LOGGER.info( 'Received defined subcommands request' ) completer = _GetCompleterForRequestData( request.json ) return _JsonResponse( completer.DefinedSubcommands() ) @app.post( '/detailed_diagnostic' ) def GetDetailedDiagnostic(): LOGGER.info( 'Received detailed diagnostic request' ) request_data = request.json completer = _GetCompleterForRequestData( request_data ) return _JsonResponse( completer.GetDetailedDiagnostic( request_data ) ) @app.post( '/load_extra_conf_file' ) def LoadExtraConfFile(): LOGGER.info( 'Received extra conf load request' ) request_data = request.json extra_conf_store.Load( request_data[ 'filepath' ], force = True ) @app.post( '/ignore_extra_conf_file' ) def IgnoreExtraConfFile(): LOGGER.info( 'Received extra conf ignore request' ) request_data = request.json extra_conf_store.Disable( request_data[ 'filepath' ] ) @app.post( '/debug_info' ) def DebugInfo(): LOGGER.info( 'Received debug info request' ) output = [] has_clang_support = ycm_core.HasClangSupport() output.append( 'Server has Clang support compiled in: {0}'.format( has_clang_support ) ) if has_clang_support: output.append( 'Clang version: ' + ycm_core.ClangVersion() ) request_data = request.json try: output.append( _GetCompleterForRequestData( request_data ).DebugInfo( request_data) ) except: pass return _JsonResponse( '\n'.join( output ) ) # The type of the param is Bottle.HTTPError @app.error( httplib.INTERNAL_SERVER_ERROR ) def ErrorHandler( httperror ): return _JsonResponse( BuildExceptionResponse( httperror.exception, httperror.traceback ) ) def _JsonResponse( data ): response.set_header( 'Content-Type', 'application/json' ) return json.dumps( data, default = _UniversalSerialize ) def _UniversalSerialize( obj ): serialized = obj.__dict__.copy() serialized[ 'TYPE' ] = type( obj ).__name__ return serialized def _GetCompleterForRequestData( request_data ): completer_target = request_data.get( 'completer_target', None ) if completer_target == 'identifier': return SERVER_STATE.GetGeneralCompleter().GetIdentifierCompleter() elif completer_target == 'filetype_default' or not completer_target: return SERVER_STATE.GetFiletypeCompleter( request_data[ 'filetypes' ] ) else: return SERVER_STATE.GetFiletypeCompleter( [ completer_target ] ) @atexit.register def ServerShutdown(): LOGGER.info( 'Server shutting down' ) if SERVER_STATE: SERVER_STATE.Shutdown() extra_conf_store.Shutdown() def UpdateUserOptions( options ): global SERVER_STATE if not options: return user_options_store.SetAll( options ) SERVER_STATE = server_state.ServerState( options ) def SetServerStateToDefaults(): global SERVER_STATE, LOGGER LOGGER = logging.getLogger( __name__ ) user_options_store.LoadDefaults() SERVER_STATE = server_state.ServerState( user_options_store.GetAll() ) extra_conf_store.Reset() vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/responses.py000066400000000000000000000075301227567565400254010ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import os YCM_EXTRA_CONF_FILENAME = '.ycm_extra_conf.py' CONFIRM_CONF_FILE_MESSAGE = ('Found {0}. Load? \n\n(Question can be turned ' 'off with options, see YCM docs)') NO_EXTRA_CONF_FILENAME_MESSAGE = ( 'No {0} file detected, so no compile flags ' 'are available. Thus no semantic support for C/C++/ObjC/ObjC++. Go READ THE ' 'DOCS *NOW*, DON\'T file a bug report.' ).format( YCM_EXTRA_CONF_FILENAME ) NO_DIAGNOSTIC_SUPPORT_MESSAGE = ( 'YCM has no diagnostics support for this ' 'filetype; refer to Syntastic docs if using Syntastic.') class ServerError( Exception ): def __init__( self, message ): super( ServerError, self ).__init__( message ) class UnknownExtraConf( ServerError ): def __init__( self, extra_conf_file ): message = CONFIRM_CONF_FILE_MESSAGE.format( extra_conf_file ) super( UnknownExtraConf, self ).__init__( message ) self.extra_conf_file = extra_conf_file class NoExtraConfDetected( ServerError ): def __init__( self ): super( NoExtraConfDetected, self ).__init__( NO_EXTRA_CONF_FILENAME_MESSAGE ) class NoDiagnosticSupport( ServerError ): def __init__( self ): super( NoDiagnosticSupport, self ).__init__( NO_DIAGNOSTIC_SUPPORT_MESSAGE ) def BuildGoToResponse( filepath, line_num, column_num, description = None ): response = { 'filepath': os.path.realpath( filepath ), 'line_num': line_num, 'column_num': column_num } if description: response[ 'description' ] = description return response def BuildDescriptionOnlyGoToResponse( text ): return { 'description': text, } # TODO: Look at all the callers and ensure they are not using this instead of an # exception. def BuildDisplayMessageResponse( text ): return { 'message': text } def BuildCompletionData( insertion_text, extra_menu_info = None, detailed_info = None, menu_text = None, kind = None ): completion_data = { 'insertion_text': insertion_text } if extra_menu_info: completion_data[ 'extra_menu_info' ] = extra_menu_info if menu_text: completion_data[ 'menu_text' ] = menu_text if detailed_info: completion_data[ 'detailed_info' ] = detailed_info if kind: completion_data[ 'kind' ] = kind return completion_data def BuildDiagnosticData( diagnostic ): def BuildRangeData( source_range ): return { 'start': BuildLocationData( source_range.start_ ), 'end': BuildLocationData( source_range.end_ ), } def BuildLocationData( location ): return { 'line_num': location.line_number_ - 1, 'column_num': location.column_number_ - 1, 'filepath': location.filename_, } return { 'ranges': [ BuildRangeData( x ) for x in diagnostic.ranges_ ], 'location': BuildLocationData( diagnostic.location_ ), 'location_extent': BuildRangeData( diagnostic.location_extent_ ), 'text': diagnostic.text_, 'kind': diagnostic.kind_ } def BuildExceptionResponse( exception, traceback ): return { 'exception': exception, 'message': str( exception ), 'traceback': traceback } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/server_state.py000066400000000000000000000067111227567565400260660ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import imp import os from ycm.utils import ForceSemanticCompletion from ycm.completers.general.general_completer_store import GeneralCompleterStore from ycm.completers.completer_utils import PathToFiletypeCompleterPluginLoader class ServerState( object ): def __init__( self, user_options ): self._user_options = user_options self._filetype_completers = {} self._gencomp = GeneralCompleterStore( self._user_options ) @property def user_options( self ): return self._user_options def Shutdown( self ): for completer in self._filetype_completers.itervalues(): if completer: completer.Shutdown() self._gencomp.Shutdown() def _GetFiletypeCompleterForFiletype( self, filetype ): try: return self._filetype_completers[ filetype ] except KeyError: pass module_path = PathToFiletypeCompleterPluginLoader( filetype ) completer = None supported_filetypes = [ filetype ] if os.path.exists( module_path ): module = imp.load_source( filetype, module_path ) completer = module.GetCompleter( self._user_options ) if completer: supported_filetypes.extend( completer.SupportedFiletypes() ) for supported_filetype in supported_filetypes: self._filetype_completers[ supported_filetype ] = completer return completer def GetFiletypeCompleter( self, current_filetypes ): completers = [ self._GetFiletypeCompleterForFiletype( filetype ) for filetype in current_filetypes ] for completer in completers: if completer: return completer raise ValueError( 'No semantic completer exists for filetypes: {0}'.format( current_filetypes ) ) def FiletypeCompletionAvailable( self, filetypes ): try: self.GetFiletypeCompleter( filetypes ) return True except: return False def FiletypeCompletionUsable( self, filetypes ): return ( self.CurrentFiletypeCompletionEnabled( filetypes ) and self.FiletypeCompletionAvailable( filetypes ) ) def ShouldUseGeneralCompleter( self, request_data ): return self._gencomp.ShouldUseNow( request_data ) def ShouldUseFiletypeCompleter( self, request_data ): filetypes = request_data[ 'filetypes' ] if self.FiletypeCompletionUsable( filetypes ): return ( ForceSemanticCompletion( request_data ) or self.GetFiletypeCompleter( filetypes ).ShouldUseNow( request_data ) ) return False def GetGeneralCompleter( self ): return self._gencomp def CurrentFiletypeCompletionEnabled( self, current_filetypes ): filetype_to_disable = self._user_options[ 'filetype_specific_completion_to_disable' ] return not all([ x in filetype_to_disable for x in current_filetypes ]) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/server_utils.py000066400000000000000000000024231227567565400261020ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import sys import os def SetUpPythonPath(): # We want to have the YouCompleteMe/python directory on the Python PATH # because all the code already assumes that it's there. This is a relic from # before the client/server architecture. # TODO: Fix things so that this is not needed anymore when we split ycmd into # a separate repository. sys.path.insert( 0, os.path.join( os.path.dirname( os.path.abspath( __file__ ) ), '../..' ) ) from ycm import utils utils.AddThirdPartyFoldersToSysPath() vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/000077500000000000000000000000001227567565400241435ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/__init__.py000066400000000000000000000000001227567565400262420ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/diagnostics_test.py000066400000000000000000000130501227567565400300620ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ..server_utils import SetUpPythonPath SetUpPythonPath() from .test_utils import Setup, BuildRequest from webtest import TestApp from nose.tools import with_setup, eq_ from hamcrest import ( assert_that, contains, contains_string, has_entries, has_entry, empty ) from ..responses import NoDiagnosticSupport from .. import handlers import bottle import httplib bottle.debug( True ) @with_setup( Setup ) def Diagnostics_ClangCompleter_ZeroBasedLineAndColumn_test(): app = TestApp( handlers.app ) contents = """ void foo() { double baz = "foo"; } // Padding to 5 lines // Padding to 5 lines """ event_data = BuildRequest( compilation_flags = ['-x', 'c++'], event_name = 'FileReadyToParse', contents = contents, filetype = 'cpp' ) results = app.post_json( '/event_notification', event_data ).json assert_that( results, contains( has_entries( { 'text': contains_string( 'cannot initialize' ), 'ranges': contains( has_entries( { 'start': has_entries( { 'line_num': 2, 'column_num': 15, } ), 'end': has_entries( { 'line_num': 2, 'column_num': 20, } ), } ) ), 'location': has_entries( { 'line_num': 2, 'column_num': 9 } ), 'location_extent': has_entries( { 'start': has_entries( { 'line_num': 2, 'column_num': 9, } ), 'end': has_entries( { 'line_num': 2, 'column_num': 12, } ), } ) } ) ) ) @with_setup( Setup ) def Diagnostics_ClangCompleter_SimpleLocationExtent_test(): app = TestApp( handlers.app ) contents = """ void foo() { baz = 5; } // Padding to 5 lines // Padding to 5 lines """ event_data = BuildRequest( compilation_flags = ['-x', 'c++'], event_name = 'FileReadyToParse', contents = contents, filetype = 'cpp' ) results = app.post_json( '/event_notification', event_data ).json assert_that( results, contains( has_entries( { 'location_extent': has_entries( { 'start': has_entries( { 'line_num': 2, 'column_num': 2, } ), 'end': has_entries( { 'line_num': 2, 'column_num': 5, } ), } ) } ) ) ) @with_setup( Setup ) def Diagnostics_ClangCompleter_PragmaOnceWarningIgnored_test(): app = TestApp( handlers.app ) contents = """ #pragma once struct Foo { int x; int y; int c; int d; }; """ event_data = BuildRequest( compilation_flags = ['-x', 'c++'], event_name = 'FileReadyToParse', contents = contents, filepath = '/foo.h', filetype = 'cpp' ) response = app.post_json( '/event_notification', event_data ) assert_that( response.body, empty() ) @with_setup( Setup ) def GetDetailedDiagnostic_ClangCompleter_Works_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x // semicolon missing here! int y; int c; int d; }; """ diag_data = BuildRequest( compilation_flags = ['-x', 'c++'], line_num = 2, contents = contents, filetype = 'cpp' ) event_data = diag_data.copy() event_data.update( { 'event_name': 'FileReadyToParse', } ) app.post_json( '/event_notification', event_data ) results = app.post_json( '/detailed_diagnostic', diag_data ).json assert_that( results, has_entry( 'message', contains_string( "expected ';'" ) ) ) @with_setup( Setup ) def GetDetailedDiagnostic_JediCompleter_DoesntWork_test(): app = TestApp( handlers.app ) diag_data = BuildRequest( contents = "foo = 5", line_num = 1, filetype = 'python' ) response = app.post_json( '/detailed_diagnostic', diag_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', NoDiagnosticSupport.__name__ ) ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/get_completions_test.py000066400000000000000000000402001227567565400307430ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ..server_utils import SetUpPythonPath SetUpPythonPath() import time import httplib from .test_utils import ( Setup, BuildRequest, PathToTestFile, ChangeSpecificOptions ) from webtest import TestApp, AppError from nose.tools import eq_, with_setup from hamcrest import ( assert_that, has_item, has_items, has_entry, contains_inanyorder, empty ) from ..responses import ( BuildCompletionData, UnknownExtraConf, NoExtraConfDetected ) from .. import handlers import bottle bottle.debug( True ) # TODO: Make the other tests use this helper too instead of BuildCompletionData def CompletionEntryMatcher( insertion_text ): return has_entry( 'insertion_text', insertion_text ) @with_setup( Setup ) def GetCompletions_IdentifierCompleter_Works_test(): app = TestApp( handlers.app ) event_data = BuildRequest( contents = 'foo foogoo ba', event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) completion_data = BuildRequest( contents = 'oo foo foogoo ba', query = 'oo', column_num = 2 ) eq_( [ BuildCompletionData( 'foo' ), BuildCompletionData( 'foogoo' ) ], app.post_json( '/completions', completion_data ).json ) @with_setup( Setup ) def GetCompletions_CsCompleter_Works_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'testy/Program.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) # We need to wait until the server has started up. while True: result = app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['ServerRunning'], filetype = 'cs' ) ).json if result: break time.sleep( 0.2 ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 8, column_num = 11, start_column = 11 ) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_items( CompletionEntryMatcher( 'CursorLeft' ), CompletionEntryMatcher( 'CursorSize' ) ) ) # We need to turn off the CS server so that it doesn't stick around app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['StopServer'], filetype = 'cs' ) ) @with_setup( Setup ) def GetCompletions_CsCompleter_StartsWithUnambiguousMultipleSolutions_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( ('testy-multiple-solutions/' 'solution-named-like-folder/' 'testy/Program.cs') ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) # Here the server will raise an exception if it can't start app.post_json( '/event_notification', event_data ) # Now for some cleanup: wait for the server to start then shut it down while True: result = app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['ServerRunning'], filetype = 'cs' ) ).json if result: break time.sleep( 0.2 ) # We need to turn off the CS server so that it doesn't stick around app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['StopServer'], filetype = 'cs' ) ) @with_setup( Setup ) def GetCompletions_CsCompleter_DoesntStartWithAmbiguousMultipleSolutions_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( ('testy-multiple-solutions/' 'solution-not-named-like-folder/' 'testy/Program.cs') ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) exception_caught = False try: app.post_json( '/event_notification', event_data ) except AppError as e: if 'Found multiple solution files' in str(e): exception_caught = True # the test passes if we caught an exception when trying to start it, # so raise one if it managed to start if not exception_caught: # Now for some cleanup: wait for the server to start then shut it down while True: result = app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['ServerRunning'], filetype = 'cs' ) ).json if result: break time.sleep( 0.2 ) # We need to turn off the CS server so that it doesn't stick around app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['StopServer'], filetype = 'cs' ) ) raise Exception( ('The Omnisharp server started, despite us not being able ' 'to find a suitable solution file to feed it. Did you ' 'fiddle with the solution finding code in ' 'cs_completer.py? Hopefully you\'ve enhanced it: you need' 'to update this test then :)') ) @with_setup( Setup ) def GetCompletions_ClangCompleter_WorksWithExplicitFlags_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ # 0-based line and column! completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', contents = contents, line_num = 10, column_num = 6, start_column = 6, compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_items( CompletionEntryMatcher( 'c' ), CompletionEntryMatcher( 'x' ), CompletionEntryMatcher( 'y' ) ) ) @with_setup( Setup ) def GetCompletions_ClangCompleter_NoCompletionsWhenAutoTriggerOff_test(): ChangeSpecificOptions( { 'auto_trigger': False } ) app = TestApp( handlers.app ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ # 0-based line and column! completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', contents = contents, line_num = 10, column_num = 6, start_column = 6, compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json assert_that( results, empty() ) @with_setup( Setup ) def GetCompletions_ClangCompleter_UnknownExtraConfException_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'basic.cpp' ) completion_data = BuildRequest( filepath = filepath, filetype = 'cpp', contents = open( filepath ).read(), line_num = 10, column_num = 6, start_column = 6, force_semantic = True ) response = app.post_json( '/completions', completion_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', UnknownExtraConf.__name__ ) ) ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) response = app.post_json( '/completions', completion_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', NoExtraConfDetected.__name__ ) ) ) @with_setup( Setup ) def GetCompletions_ClangCompleter_WorksWhenExtraConfExplicitlyAllowed_test(): app = TestApp( handlers.app ) app.post_json( '/load_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'basic.cpp' ) completion_data = BuildRequest( filepath = filepath, filetype = 'cpp', contents = open( filepath ).read(), line_num = 10, column_num = 6, start_column = 6 ) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_items( CompletionEntryMatcher( 'c' ), CompletionEntryMatcher( 'x' ), CompletionEntryMatcher( 'y' ) ) ) @with_setup( Setup ) def GetCompletions_ClangCompleter_ExceptionWhenNoFlagsFromExtraConf_test(): app = TestApp( handlers.app ) app.post_json( '/load_extra_conf_file', { 'filepath': PathToTestFile( 'noflags/.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'noflags/basic.cpp' ) completion_data = BuildRequest( filepath = filepath, filetype = 'cpp', contents = open( filepath ).read(), line_num = 10, column_num = 6, start_column = 6 ) response = app.post_json( '/completions', completion_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', RuntimeError.__name__ ) ) ) @with_setup( Setup ) def GetCompletions_ClangCompleter_ForceSemantic_OnlyFileteredCompletions_test(): app = TestApp( handlers.app ) contents = """ int main() { int foobar; int floozar; int gooboo; int bleble; fooar } """ # 0-based line and column! completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', force_semantic = True, contents = contents, line_num = 8, column_num = 7, start_column = 7, query = 'fooar', compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json assert_that( results, contains_inanyorder( CompletionEntryMatcher( 'foobar' ), CompletionEntryMatcher( 'floozar' ) ) ) @with_setup( Setup ) def GetCompletions_ForceSemantic_Works_test(): app = TestApp( handlers.app ) completion_data = BuildRequest( filetype = 'python', force_semantic = True ) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_items( CompletionEntryMatcher( 'abs' ), CompletionEntryMatcher( 'open' ), CompletionEntryMatcher( 'bool' ) ) ) @with_setup( Setup ) def GetCompletions_ClangCompleter_ClientDataGivenToExtraConf_test(): app = TestApp( handlers.app ) app.post_json( '/load_extra_conf_file', { 'filepath': PathToTestFile( 'client_data/.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'client_data/main.cpp' ) completion_data = BuildRequest( filepath = filepath, filetype = 'cpp', contents = open( filepath ).read(), line_num = 8, column_num = 6, start_column = 6, extra_conf_data = { 'flags': ['-x', 'c++'] }) results = app.post_json( '/completions', completion_data ).json assert_that( results, has_item( CompletionEntryMatcher( 'x' ) ) ) @with_setup( Setup ) def GetCompletions_IdentifierCompleter_SyntaxKeywordsAdded_test(): app = TestApp( handlers.app ) event_data = BuildRequest( event_name = 'FileReadyToParse', syntax_keywords = ['foo', 'bar', 'zoo'] ) app.post_json( '/event_notification', event_data ) completion_data = BuildRequest( contents = 'oo ', query = 'oo', column_num = 2 ) eq_( [ BuildCompletionData( 'foo' ), BuildCompletionData( 'zoo' ) ], app.post_json( '/completions', completion_data ).json ) @with_setup( Setup ) def GetCompletions_UltiSnipsCompleter_Works_test(): app = TestApp( handlers.app ) event_data = BuildRequest( event_name = 'BufferVisit', ultisnips_snippets = [ {'trigger': 'foo', 'description': 'bar'}, {'trigger': 'zoo', 'description': 'goo'}, ] ) app.post_json( '/event_notification', event_data ) completion_data = BuildRequest( contents = 'oo ', query = 'oo', column_num = 2 ) eq_( [ BuildCompletionData( 'foo', ' bar' ), BuildCompletionData( 'zoo', ' goo' ) ], app.post_json( '/completions', completion_data ).json ) @with_setup( Setup ) def GetCompletions_UltiSnipsCompleter_UnusedWhenOffWithOption_test(): ChangeSpecificOptions( { 'use_ultisnips_completer': False } ) app = TestApp( handlers.app ) event_data = BuildRequest( event_name = 'BufferVisit', ultisnips_snippets = [ {'trigger': 'foo', 'description': 'bar'}, {'trigger': 'zoo', 'description': 'goo'}, ] ) app.post_json( '/event_notification', event_data ) completion_data = BuildRequest( contents = 'oo ', query = 'oo', column_num = 2 ) eq_( [], app.post_json( '/completions', completion_data ).json ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/misc_handlers_test.py000066400000000000000000000027261227567565400303760ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ..server_utils import SetUpPythonPath SetUpPythonPath() from webtest import TestApp from .. import handlers from nose.tools import ok_, eq_, with_setup from .test_utils import Setup import bottle bottle.debug( True ) @with_setup( Setup ) def SemanticCompletionAvailable_Works_test(): app = TestApp( handlers.app ) request_data = { 'filetypes': ['python'] } ok_( app.post_json( '/semantic_completion_available', request_data ).json ) @with_setup( Setup ) def UserOptions_Works_test(): app = TestApp( handlers.app ) options = app.get( '/user_options' ).json ok_( len( options ) ) options[ 'foobar' ] = 'zoo' app.post_json( '/user_options', options ) eq_( options, app.get( '/user_options' ).json ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/subcommands_test.py000066400000000000000000000061101227567565400300650ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from ..server_utils import SetUpPythonPath SetUpPythonPath() from .test_utils import Setup, BuildRequest from webtest import TestApp from nose.tools import eq_, with_setup from .. import handlers import bottle bottle.debug( True ) @with_setup( Setup ) def RunCompleterCommand_GoTo_Jedi_ZeroBasedLineAndColumn_test(): app = TestApp( handlers.app ) contents = """ def foo(): pass foo() """ goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToDefinition'], line_num = 4, contents = contents, filetype = 'python', filepath = '/foo.py' ) # 0-based line and column! eq_( { 'filepath': '/foo.py', 'line_num': 1, 'column_num': 4 }, app.post_json( '/run_completer_command', goto_data ).json ) @with_setup( Setup ) def RunCompleterCommand_GoTo_Clang_ZeroBasedLineAndColumn_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; return 0; } """ goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToDefinition'], compilation_flags = ['-x', 'c++'], line_num = 9, column_num = 2, contents = contents, filetype = 'cpp' ) # 0-based line and column! eq_( { 'filepath': '/foo', 'line_num': 1, 'column_num': 7 }, app.post_json( '/run_completer_command', goto_data ).json ) @with_setup( Setup ) def DefinedSubcommands_Works_test(): app = TestApp( handlers.app ) subcommands_data = BuildRequest( completer_target = 'python' ) eq_( [ 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration' ], app.post_json( '/defined_subcommands', subcommands_data ).json ) @with_setup( Setup ) def DefinedSubcommands_WorksWhenNoExplicitCompleterTargetSpecified_test(): app = TestApp( handlers.app ) subcommands_data = BuildRequest( filetype = 'python' ) eq_( [ 'GoToDefinition', 'GoToDeclaration', 'GoToDefinitionElseDeclaration' ], app.post_json( '/defined_subcommands', subcommands_data ).json ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/test_utils.py000066400000000000000000000041721227567565400267200ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import os from .. import handlers from ycm import user_options_store def BuildRequest( **kwargs ): filepath = kwargs[ 'filepath' ] if 'filepath' in kwargs else '/foo' contents = kwargs[ 'contents' ] if 'contents' in kwargs else '' filetype = kwargs[ 'filetype' ] if 'filetype' in kwargs else 'foo' request = { 'query': '', 'line_num': 0, 'column_num': 0, 'start_column': 0, 'filetypes': [ filetype ], 'filepath': filepath, 'line_value': contents, 'file_data': { filepath: { 'contents': contents, 'filetypes': [ filetype ] } } } for key, value in kwargs.iteritems(): if key in [ 'contents', 'filetype', 'filepath' ]: continue request[ key ] = value if key == 'line_num': lines = contents.splitlines() if len( lines ) > 1: # NOTE: assumes 0-based line_num request[ 'line_value' ] = lines[ value ] return request def Setup(): handlers.SetServerStateToDefaults() def ChangeSpecificOptions( options ): current_options = dict( user_options_store.GetAll() ) current_options.update( options ) handlers.UpdateUserOptions( current_options ) def PathToTestDataDir(): dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) ) return os.path.join( dir_of_current_script, 'testdata' ) def PathToTestFile( test_basename ): return os.path.join( PathToTestDataDir(), test_basename ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/000077500000000000000000000000001227567565400257545ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/.ycm_extra_conf.py000066400000000000000000000001361227567565400314040ustar00rootroot00000000000000def FlagsForFile( filename ): return { 'flags': ['-x', 'c++'], 'do_cache': True } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/basic.cpp000066400000000000000000000002011227567565400275320ustar00rootroot00000000000000struct Foo { int x; int y; char c; }; int main() { Foo foo; // The location after the dot is line 11, col 7 foo. } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/client_data/000077500000000000000000000000001227567565400302235ustar00rootroot00000000000000.ycm_extra_conf.py000066400000000000000000000001711227567565400335730ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/client_datadef FlagsForFile( filename, **kwargs ): return { 'flags': kwargs['client_data']['flags'], 'do_cache': True } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/client_data/main.cpp000066400000000000000000000001551227567565400316540ustar00rootroot00000000000000struct Foo { int x; }; int main() { Foo foo; // The location after the dot is line 9, col 7 foo. } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/noflags/000077500000000000000000000000001227567565400274055ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/noflags/.ycm_extra_conf.py000066400000000000000000000001241227567565400330320ustar00rootroot00000000000000def FlagsForFile( filename ): return { 'flags': [], 'do_cache': True } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/noflags/basic.cpp000066400000000000000000000002011227567565400311630ustar00rootroot00000000000000struct Foo { int x; int y; char c; }; int main() { Foo foo; // The location after the dot is line 11, col 7 foo. } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/000077500000000000000000000000001227567565400330125ustar00rootroot00000000000000solution-named-like-folder/000077500000000000000000000000001227567565400400645ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutionstesty.sln000066400000000000000000000015201227567565400417500ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testy", "testy/testy.csproj", "{0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.ActiveCfg = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.Build.0 = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.ActiveCfg = Release|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = testy/testy.csproj EndGlobalSection EndGlobal testy/000077500000000000000000000000001227567565400412345ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folderProgram.cs000066400000000000000000000001701227567565400431700ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder/testyusing System; namespace testy { class MainClass { public static void Main (string[] args) { Console. } } } Properties/000077500000000000000000000000001227567565400433705ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder/testyAssemblyInfo.cs000066400000000000000000000017271227567565400463210ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder/testy/Propertiesusing System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("testy")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("valloric")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] testy.csproj000066400000000000000000000031711227567565400436300ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder/testy Debug x86 10.0.0 2.0 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F} Exe testy testy true full false bin\Debug DEBUG; prompt 4 true x86 full true bin\Release prompt 4 true x86 testy2.sln000066400000000000000000000015201227567565400420320ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-named-like-folder Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testy", "testy/testy.csproj", "{0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.ActiveCfg = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.Build.0 = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.ActiveCfg = Release|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = testy/testy.csproj EndGlobalSection EndGlobal solution-not-named-like-folder/000077500000000000000000000000001227567565400406625ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutionstesty/000077500000000000000000000000001227567565400420325ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folderProgram.cs000066400000000000000000000001701227567565400437660ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder/testyusing System; namespace testy { class MainClass { public static void Main (string[] args) { Console. } } } Properties/000077500000000000000000000000001227567565400441665ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder/testyAssemblyInfo.cs000066400000000000000000000017271227567565400471170ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder/testy/Propertiesusing System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("testy")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("valloric")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] testy.csproj000066400000000000000000000031711227567565400444260ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder/testy Debug x86 10.0.0 2.0 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F} Exe testy testy true full false bin\Debug DEBUG; prompt 4 true x86 full true bin\Release prompt 4 true x86 testy1.sln000066400000000000000000000015201227567565400426270ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testy", "testy/testy.csproj", "{0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.ActiveCfg = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.Build.0 = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.ActiveCfg = Release|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = testy/testy.csproj EndGlobalSection EndGlobal testy2.sln000066400000000000000000000015201227567565400426300ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy-multiple-solutions/solution-not-named-like-folder Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testy", "testy/testy.csproj", "{0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.ActiveCfg = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.Build.0 = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.ActiveCfg = Release|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = testy/testy.csproj EndGlobalSection EndGlobal vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/000077500000000000000000000000001227567565400271245ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/Program.cs000066400000000000000000000001701227567565400310600ustar00rootroot00000000000000using System; namespace testy { class MainClass { public static void Main (string[] args) { Console. } } } vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/Properties/000077500000000000000000000000001227567565400312605ustar00rootroot00000000000000AssemblyInfo.cs000066400000000000000000000017271227567565400341320ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/Propertiesusing System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("testy")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("valloric")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/testy.csproj000066400000000000000000000031711227567565400315200ustar00rootroot00000000000000 Debug x86 10.0.0 2.0 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F} Exe testy testy true full false bin\Debug DEBUG; prompt 4 true x86 full true bin\Release prompt 4 true x86 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/testy.sln000066400000000000000000000015041227567565400310120ustar00rootroot00000000000000 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "testy", "testy.csproj", "{0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.ActiveCfg = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Debug|x86.Build.0 = Debug|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.ActiveCfg = Release|x86 {0C99F719-E00E-4CCD-AB9F-FEFBCD97C51F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = testy.csproj EndGlobalSection EndGlobal vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/tests/testdata/testy/testy.userprefs000066400000000000000000000010021227567565400322250ustar00rootroot00000000000000 vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/watchdog_plugin.py000066400000000000000000000050731227567565400265360ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import time import os import copy from ycm import utils from threading import Thread, Lock # This class implements the Bottle plugin API: # http://bottlepy.org/docs/dev/plugindev.html # # The idea here is to decorate every route handler automatically so that on # every request, we log when the request was made. Then a watchdog thread checks # every check_interval_seconds whether the server has been idle for a time # greater that the passed-in idle_suicide_seconds. If it has, we kill the # server. # # We want to do this so that if something goes bonkers in Vim and the server # never gets killed by the client, we don't end up with lots of zombie servers. class WatchdogPlugin( object ): name = 'watchdog' api = 2 def __init__( self, idle_suicide_seconds, check_interval_seconds = 60 * 10 ): self._check_interval_seconds = check_interval_seconds self._idle_suicide_seconds = idle_suicide_seconds self._last_request_time = time.time() self._last_request_time_lock = Lock() if idle_suicide_seconds <= 0: return self._watchdog_thread = Thread( target = self._WatchdogMain ) self._watchdog_thread.daemon = True self._watchdog_thread.start() def _GetLastRequestTime( self ): with self._last_request_time_lock: return copy.deepcopy( self._last_request_time ) def _SetLastRequestTime( self, new_value ): with self._last_request_time_lock: self._last_request_time = new_value def _WatchdogMain( self ): while True: time.sleep( self._check_interval_seconds ) if time.time() - self._GetLastRequestTime() > self._idle_suicide_seconds: utils.TerminateProcess( os.getpid() ) def __call__( self, callback ): def wrapper( *args, **kwargs ): self._SetLastRequestTime( time.time() ) return callback( *args, **kwargs ) return wrapper vim-youcompleteme-0+20140207+git18be5c2/python/ycm/server/ycmd.py000077500000000000000000000066101227567565400243150ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from server_utils import SetUpPythonPath SetUpPythonPath() import sys import logging import json import argparse import waitress import signal from ycm import user_options_store from ycm import extra_conf_store from ycm.server.watchdog_plugin import WatchdogPlugin def YcmCoreSanityCheck(): if 'ycm_core' in sys.modules: raise RuntimeError( 'ycm_core already imported, ycmd has a bug!' ) # We manually call sys.exit() on SIGTERM and SIGINT so that atexit handlers are # properly executed. def SetUpSignalHandler(): def SignalHandler( signum, frame ): sys.exit() for sig in [ signal.SIGTERM, signal.SIGINT ]: signal.signal( sig, SignalHandler ) def Main(): parser = argparse.ArgumentParser() parser.add_argument( '--host', type = str, default = 'localhost', help = 'server hostname') # Default of 0 will make the OS pick a free port for us parser.add_argument( '--port', type = int, default = 0, help = 'server port') parser.add_argument( '--log', type = str, default = 'info', help = 'log level, one of ' '[debug|info|warning|error|critical]' ) parser.add_argument( '--idle_suicide_seconds', type = int, default = 0, help = 'num idle seconds before server shuts down') parser.add_argument( '--options_file', type = str, default = '', help = 'file with user options, in JSON format' ) args = parser.parse_args() numeric_level = getattr( logging, args.log.upper(), None ) if not isinstance( numeric_level, int ): raise ValueError( 'Invalid log level: %s' % args.log ) # Has to be called before any call to logging.getLogger() logging.basicConfig( format = '%(asctime)s - %(levelname)s - %(message)s', level = numeric_level ) options = ( json.load( open( args.options_file, 'r' ) ) if args.options_file else user_options_store.DefaultOptions() ) user_options_store.SetAll( options ) # This ensures that ycm_core is not loaded before extra conf # preload was run. YcmCoreSanityCheck() extra_conf_store.CallGlobalExtraConfYcmCorePreloadIfExists() # This can't be a top-level import because it transitively imports # ycm_core which we want to be imported ONLY after extra conf # preload has executed. from ycm.server import handlers handlers.UpdateUserOptions( options ) SetUpSignalHandler() handlers.app.install( WatchdogPlugin( args.idle_suicide_seconds ) ) waitress.serve( handlers.app, host = args.host, port = args.port, threads = 30 ) if __name__ == "__main__": Main() vim-youcompleteme-0+20140207+git18be5c2/python/ycm/test_utils.py000066400000000000000000000022621227567565400242460ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from mock import MagicMock import sys 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. """ def VimEval( value ): if value == "g:ycm_min_num_of_chars_for_completion": return 0 return '' vim_mock = MagicMock() vim_mock.eval = MagicMock( side_effect = VimEval ) sys.modules[ 'vim' ] = vim_mock return vim_mock vim-youcompleteme-0+20140207+git18be5c2/python/ycm/tests/000077500000000000000000000000001227567565400226355ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/python/ycm/tests/base_test.py000066400000000000000000000113001227567565400251530ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from nose.tools import eq_ from mock import MagicMock from ycm.test_utils import MockVimModule vim_mock = MockVimModule() from ycm import base from ycm import vimsupport def AdjustCandidateInsertionText_Basic_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar' ) eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) def AdjustCandidateInsertionText_ParenInTextAfterCursor_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar(zoo' ) eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) def AdjustCandidateInsertionText_PlusInTextAfterCursor_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar+zoo' ) eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) def AdjustCandidateInsertionText_WhitespaceInTextAfterCursor_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar zoo' ) eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar' ] ) ) def AdjustCandidateInsertionText_MoreThanWordMatchingAfterCursor_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar.h' ) eq_( [ { 'abbr': 'foobar.h', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar.h' ] ) ) vimsupport.TextAfterCursor = MagicMock( return_value = 'bar(zoo' ) eq_( [ { 'abbr': 'foobar(zoo', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ 'foobar(zoo' ] ) ) def AdjustCandidateInsertionText_NotSuffix_test(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar' ) eq_( [ { 'abbr': 'foofoo', 'word': 'foofoo' } ], base.AdjustCandidateInsertionText( [ 'foofoo' ] ) ) def AdjustCandidateInsertionText_NothingAfterCursor_test(): vimsupport.TextAfterCursor = MagicMock( return_value = '' ) eq_( [ 'foofoo', 'zobar' ], base.AdjustCandidateInsertionText( [ 'foofoo', 'zobar' ] ) ) def AdjustCandidateInsertionText_MultipleStrings_test(): vimsupport.TextAfterCursor = MagicMock( return_value = '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(): vimsupport.TextAfterCursor = MagicMock( return_value = 'bar' ) eq_( [ { 'abbr': 'foobar', 'word': 'foo' } ], base.AdjustCandidateInsertionText( [ { 'word': 'foobar' } ] ) ) def AdjustCandidateInsertionText_DontTouchAbbr_test(): vimsupport.TextAfterCursor = MagicMock( return_value = '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_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' ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/tests/extra_conf_store_test.py000066400000000000000000000026771227567565400276260ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . from nose.tools import eq_ from ycm.test_utils import MockVimModule vim_mock = MockVimModule() from ycm.extra_conf_store import _PathsToAllParentFolders def PathsToAllParentFolders_Basic_test(): eq_( [ '/home/user/projects', '/home/user', '/home', '/' ], list( _PathsToAllParentFolders( '/home/user/projects/test.c' ) ) ) def PathsToAllParentFolders_FileAtRoot_test(): eq_( [ '/' ], list( _PathsToAllParentFolders( '/test.c' ) ) ) # We can't use backwards slashes in the paths because then the test would fail # on Unix machines def PathsToAllParentFolders_WindowsPath_test(): eq_( [ r'C:/foo/goo/zoo', r'C:/foo/goo', r'C:/foo', 'C:' ], list( _PathsToAllParentFolders( r'C:/foo/goo/zoo/test.c' ) ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/unsafe_thread_pool_executor.py000066400000000000000000000075651227567565400276410ustar00rootroot00000000000000# 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__ vim-youcompleteme-0+20140207+git18be5c2/python/ycm/user_options_store.py000066400000000000000000000023641227567565400260170ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import json import os from frozendict import frozendict _USER_OPTIONS = {} def SetAll( new_options ): global _USER_OPTIONS _USER_OPTIONS = frozendict( new_options ) def GetAll(): return _USER_OPTIONS def Value( key ): return _USER_OPTIONS[ key ] def LoadDefaults(): SetAll( DefaultOptions() ) def DefaultOptions(): settings_path = os.path.join( os.path.dirname( os.path.abspath( __file__ ) ), 'server/default_settings.json' ) with open( settings_path ) as f: return json.loads( f.read() ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/utils.py000066400000000000000000000122001227567565400232000ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import tempfile import os import sys import signal import functools import socket import stat from distutils.spawn import find_executable import subprocess WIN_PYTHON27_PATH = 'C:\python27\pythonw.exe' WIN_PYTHON26_PATH = 'C:\python26\pythonw.exe' def IsIdentifierChar( char ): return char.isalnum() or char == '_' def SanitizeQuery( query ): return query.strip() def ToUtf8IfNeeded( value ): if isinstance( value, unicode ): return value.encode( 'utf8' ) if isinstance( value, str ): return value return str( value ) def PathToTempDir(): tempdir = os.path.join( tempfile.gettempdir(), 'ycm_temp' ) if not os.path.exists( tempdir ): os.makedirs( tempdir ) # Needed to support multiple users working on the same machine; # see issue 606. MakeFolderAccessibleToAll( tempdir ) return tempdir def MakeFolderAccessibleToAll( path_to_folder ): current_stat = os.stat( path_to_folder ) # readable, writable and executable by everyone flags = ( current_stat.st_mode | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP ) os.chmod( path_to_folder, flags ) def RunningInsideVim(): try: import vim # NOQA return True except ImportError: return False def GetUnusedLocalhostPort(): sock = socket.socket() # This tells the OS to give us any free port in the range [1024 - 65535] sock.bind( ( '', 0 ) ) port = sock.getsockname()[ 1 ] sock.close() return port def RemoveIfExists( filename ): try: os.remove( filename ) except OSError: pass 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(): if not RunningInsideVim(): return sys.executable import vim # NOQA user_path_to_python = vim.eval( 'g:ycm_path_to_python_interpreter' ) if user_path_to_python: return user_path_to_python # We check for 'python2' before 'python' because some OS's (I'm looking at you # Arch Linux) have made the... interesting decision to point /usr/bin/python # to python3. python_names = [ 'python2', 'python' ] if OnWindows(): # On Windows, 'pythonw' doesn't pop-up a console window like running # 'python' does. python_names.insert( 0, 'pythonw' ) path_to_python = PathToFirstExistingExecutable( python_names ) if path_to_python: return path_to_python # On Windows, Python may not be on the PATH at all, so we check some common # install locations. if OnWindows(): if os.path.exists( WIN_PYTHON27_PATH ): return WIN_PYTHON27_PATH elif os.path.exists( WIN_PYTHON26_PATH ): return WIN_PYTHON26_PATH raise RuntimeError( 'Python 2.7/2.6 not installed!' ) def PathToFirstExistingExecutable( executable_name_list ): for executable_name in executable_name_list: path = find_executable( executable_name ) if path: return path return None def OnWindows(): return sys.platform == 'win32' # From here: http://stackoverflow.com/a/8536476/1672783 def TerminateProcess( pid ): if OnWindows(): import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess( PROCESS_TERMINATE, False, pid ) ctypes.windll.kernel32.TerminateProcess( handle, -1 ) ctypes.windll.kernel32.CloseHandle( handle ) else: os.kill( pid, signal.SIGTERM ) def AddThirdPartyFoldersToSysPath(): path_to_third_party = os.path.join( os.path.dirname( os.path.abspath( __file__ ) ), '../../third_party' ) for folder in os.listdir( path_to_third_party ): sys.path.insert( 0, os.path.realpath( os.path.join( path_to_third_party, folder ) ) ) def ForceSemanticCompletion( request_data ): return ( 'force_semantic' in request_data and bool( request_data[ 'force_semantic' ] ) ) # A wrapper for subprocess.Popen that works around a Popen bug on Windows. def SafePopen( *args, **kwargs ): if kwargs.get( 'stdin' ) is None: # We need this on Windows otherwise bad things happen. See issue #637. kwargs[ 'stdin' ] = subprocess.PIPE if OnWindows() else None return subprocess.Popen( *args, **kwargs ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/vimsupport.py000066400000000000000000000276651227567565400243150ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import vim import os import json from ycm.utils import ToUtf8IfNeeded 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 TextAfterCursor(): """Returns the text after CurrentColumn.""" return vim.current.line[ CurrentColumn(): ] # 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 GetUnsavedAndCurrentBufferData(): def BufferModified( buffer_object ): return bool( int( GetBufferOption( buffer_object, 'mod' ) ) ) 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 ) ] = { 'contents': '\n'.join( buffer_object ), 'filetypes': FiletypesForBuffer( buffer_object ) } return buffers_data def GetBufferNumberForFilename( filename, open_file_if_needed = True ): return GetIntValue( "bufnr('{0}', {1})".format( 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. return os.path.join( os.getcwd(), str( buffer_object.number ) ) # NOTE: This unplaces *all* signs in a buffer, not just the ones we placed. We # used to track which signs we ended up placing and would then only unplace # ours, but that causes flickering Vim since we have to call # sign unplace buffer= # in a loop. So we're forced to unplace all signs, which might conflict with # other Vim plugins. def UnplaceAllSignsInBuffer( buffer_number ): if buffer_number < 0: return vim.command( 'sign unplace * buffer={0}'.format( buffer_number ) ) def PlaceSign( sign_id, line_num, buffer_num, is_error = True ): 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 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. 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 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. location = diagnostic[ 'location' ] return { 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ), 'lnum' : location[ 'line_num' ] + 1, 'col' : location[ 'column_num' ] + 1, 'text' : ToUtf8IfNeeded( diagnostic[ 'text' ] ), 'type' : diagnostic[ 'kind' ], 'valid' : 1 } return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ] # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1' # When |overwrite| is True, overwrites the existing value in Vim. def LoadDictIntoVimGlobals( new_globals, overwrite = True ): extend_option = '"force"' if overwrite else '"keep"' # We need to use json.dumps because that won't use the 'u' prefix on strings # which Vim would bork on. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ), extend_option ) ) # Changing the returned dict will NOT change the value in Vim. def GetReadOnlyVimGlobals( force_python_objects = False ): if force_python_objects: return vim.eval( 'g:' ) try: # vim.vars is fairly new so it might not exist return vim.vars except: return vim.eval( 'g:' ) def VimExpressionToPythonType( vim_expression ): result = vim.eval( vim_expression ) if not isinstance( result, basestring ): return result try: return int( result ) except ValueError: return result # 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. vim.command( 'keepjumps edit {0}'.format( filename ) ) 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). def PostVimMessage( message ): vim.command( "echohl WarningMsg | echom '{0}' | echohl None" .format( EscapeForVim( str( 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( str( 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 . Use -1 for no default. PresentDialog will return a 0-based index into the list or -1 if the dialog was dismissed by using , 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( message ), EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 ) return int( vim.eval( to_eval ) ) - 1 def Confirm( message ): 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 str( 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 = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ] truncated_text.replace( '\n', ' ' ) old_ruler = GetIntValue( '&ruler' ) old_showcmd = GetIntValue( '&showcmd' ) vim.command( 'set noruler noshowcmd' ) EchoText( truncated_text, False ) vim.command( 'let &ruler = {0}'.format( old_ruler ) ) vim.command( 'let &showcmd = {0}'.format( old_showcmd ) ) def EscapeForVim( text ): return text.replace( "'", "''" ) def CurrentFiletypes(): return vim.eval( "&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 GetVariableValue( variable ): return vim.eval( variable ) def GetBoolValue( variable ): return bool( int( vim.eval( variable ) ) ) def GetIntValue( variable ): return int( vim.eval( variable ) ) vim-youcompleteme-0+20140207+git18be5c2/python/ycm/youcompleteme.py000066400000000000000000000327731227567565400247500ustar00rootroot00000000000000#!/usr/bin/env python # # 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 . import os import vim import tempfile import json import signal from ycm import vimsupport from ycm import utils from ycm.diagnostic_interface import DiagnosticInterface from ycm.completers.all.omni_completer import OmniCompleter from ycm.completers.general import syntax_parse from ycm.completers.completer_utils import FiletypeCompleterExistsForFiletype from ycm.client.ycmd_keepalive import YcmdKeepalive from ycm.client.base_request import BaseRequest, BuildRequestData from ycm.client.command_request import SendCommandRequest from ycm.client.completion_request import CompletionRequest from ycm.client.omni_completion_request import OmniCompletionRequest from ycm.client.event_notification import ( SendEventNotificationAsync, EventNotification ) from ycm.server.responses import ServerError try: from UltiSnips import UltiSnips_Manager USE_ULTISNIPS_DATA = True except ImportError: USE_ULTISNIPS_DATA = False # 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 os.environ['no_proxy'] = '127.0.0.1,localhost' # 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 ) NUM_YCMD_STDERR_LINES_ON_CRASH = 30 SERVER_CRASH_MESSAGE_STDERR_FILE = ( 'The ycmd server SHUT DOWN (restart with :YcmRestartServer). ' + 'Stderr (last {0} lines):\n\n'.format( NUM_YCMD_STDERR_LINES_ON_CRASH ) ) SERVER_CRASH_MESSAGE_SAME_STDERR = ( 'The ycmd server SHUT DOWN (restart with :YcmRestartServer). ' ' check console output for logs!' ) SERVER_IDLE_SUICIDE_SECONDS = 10800 # 3 hours 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_completion_request = None self._latest_file_parse_request = None self._server_stdout = None self._server_stderr = None self._server_popen = None self._filetypes_with_keywords_loaded = set() self._temp_options_filename = None self._ycmd_keepalive = YcmdKeepalive() self._SetupServer() self._ycmd_keepalive.Start() def _SetupServer( self ): server_port = utils.GetUnusedLocalhostPort() with tempfile.NamedTemporaryFile( delete = False ) as options_file: self._temp_options_filename = options_file.name json.dump( dict( self._user_options ), options_file ) options_file.flush() args = [ utils.PathToPythonInterpreter(), _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 ) ] BaseRequest.server_location = 'http://localhost:' + str( server_port ) if self._user_options[ 'server_use_vim_stdout' ]: self._server_popen = utils.SafePopen( args ) else: filename_format = os.path.join( utils.PathToTempDir(), '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' ) with open( self._server_stderr, 'w' ) as fstderr: with open( self._server_stdout, 'w' ) as fstdout: self._server_popen = utils.SafePopen( args, stdout = fstdout, stderr = fstderr ) 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 if self._server_stderr: with open( self._server_stderr, 'r' ) as server_stderr_file: error_output = ''.join( server_stderr_file.readlines()[ : - NUM_YCMD_STDERR_LINES_ON_CRASH ] ) vimsupport.PostMultiLineNotice( SERVER_CRASH_MESSAGE_STDERR_FILE + error_output ) else: vimsupport.PostVimMessage( SERVER_CRASH_MESSAGE_SAME_STDERR ) 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() utils.RemoveIfExists( self._temp_options_filename ) if not self._user_options[ 'server_keep_logfiles' ]: if self._server_stderr: utils.RemoveIfExists( self._server_stderr ) if self._server_stdout: utils.RemoveIfExists( self._server_stdout ) def RestartServer( self ): vimsupport.PostVimMessage( 'Restarting ycmd server...' ) self._user_notified_about_crash = False self._ServerCleanup() self._SetupServer() def CreateCompletionRequest( self, force_semantic = False ): # We have to store a reference to the newly created CompletionRequest # because VimScript can't store a reference to a Python object across # function calls... Thus we need to keep this request somewhere. if ( not self.NativeFiletypeCompletionAvailable() and self.CurrentFiletypeCompletionEnabled() and self._omnicomp.ShouldUseNow() ): self._latest_completion_request = OmniCompletionRequest( self._omnicomp ) else: extra_data = {} self._AddExtraConfDataIfNeeded( extra_data ) if force_semantic: extra_data[ 'force_semantic' ] = True self._latest_completion_request = ( CompletionRequest( extra_data ) if self._IsServerAlive() else None ) return self._latest_completion_request def SendCommandRequest( self, arguments, completer ): if self._IsServerAlive(): return SendCommandRequest( arguments, completer ) def GetDefinedSubcommands( self ): if self._IsServerAlive(): return BaseRequest.PostDataToHandler( BuildRequestData(), 'defined_subcommands' ) else: return [] def GetCurrentCompletionRequest( self ): return self._latest_completion_request def GetOmniCompleter( self ): return self._omnicomp def NativeFiletypeCompletionAvailable( self ): return any( [ FiletypeCompleterExistsForFiletype( x ) for x in vimsupport.CurrentFiletypes() ] ) def NativeFiletypeCompletionUsable( self ): return ( self.CurrentFiletypeCompletionEnabled() and self.NativeFiletypeCompletionAvailable() ) def OnFileReadyToParse( self ): self._omnicomp.OnFileReadyToParse( None ) if not self._IsServerAlive(): self._NotifyUserIfServerCrashed() 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 DiagnosticsForCurrentFileReady( self ): return bool( self._latest_file_parse_request and self._latest_file_parse_request.Done() ) def GetDiagnosticsFromStoredRequest( self, qflist_format = False ): if self.DiagnosticsForCurrentFileReady(): diagnostics = self._latest_file_parse_request.Response() # We set the diagnostics request to None because we want to prevent # Syntastic from repeatedly refreshing the buffer with the same diags. # Setting this to None makes DiagnosticsForCurrentFileReady return False # until the next request is created. self._latest_file_parse_request = None if qflist_format: return vimsupport.ConvertDiagnosticsToQfList( diagnostics ) else: return diagnostics return [] def UpdateDiagnosticInterface( self ): if not self.DiagnosticsForCurrentFileReady(): return self._diag_interface.UpdateWithNewDiagnostics( self.GetDiagnosticsFromStoredRequest() ) 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 CurrentFiletypeCompletionEnabled( self ): filetypes = vimsupport.CurrentFiletypes() filetype_to_disable = self._user_options[ 'filetype_specific_completion_to_disable' ] return not all([ 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()' ) current_working_directory = os.getcwd() 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 _PathToServerScript(): dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) ) return os.path.join( dir_of_current_script, 'server/ycmd.py' ) def _AddUltiSnipsDataIfNeeded( extra_data ): if not USE_ULTISNIPS_DATA: return try: rawsnips = UltiSnips_Manager._snips( '', 1 ) 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 ] vim-youcompleteme-0+20140207+git18be5c2/run_tests.sh000077500000000000000000000015451227567565400217540ustar00rootroot00000000000000#!/usr/bin/env bash set -e function usage { echo "Usage: $0 [--no-clang-completer]" exit 0 } flake8 --select=F,C9 --max-complexity=10 python use_clang_completer=true for flag in $@; do case "$flag" in --no-clang-completer) use_clang_completer=false ;; *) usage ;; esac done if [ -n "$USE_CLANG_COMPLETER" ]; then use_clang_completer=$USE_CLANG_COMPLETER fi if $use_clang_completer; then extra_cmake_args="-DUSE_CLANG_COMPLETER=ON -DUSE_DEV_FLAGS=ON" else extra_cmake_args="-DUSE_DEV_FLAGS=ON" fi EXTRA_CMAKE_ARGS=$extra_cmake_args YCM_TESTRUN=1 ./install.sh --omnisharp-completer for directory in third_party/*; do if [ -d "${directory}" ]; then export PYTHONPATH=$PWD/${directory}:$PYTHONPATH fi done if $use_clang_completer; then nosetests -v python else nosetests -v --exclude=".*Clang.*" python fi vim-youcompleteme-0+20140207+git18be5c2/style_format.sh000077500000000000000000000010401227567565400224240ustar00rootroot00000000000000#!/bin/bash astyle \ --style=attach \ --indent=spaces=2 \ --indent-switches \ --indent-col1-comments \ --indent-preprocessor \ --max-instatement-indent=80 \ --break-blocks \ --pad-oper \ --pad-paren-in \ --pad-header \ --keep-one-line-blocks \ --convert-tabs \ --align-pointer=name \ --align-reference=name \ --suffix=none \ --lineend=linux \ --recursive \ --exclude=gmock \ --exclude=testdata \ --exclude=ycm_client_support.cpp \ --exclude=ycm_core.cpp \ --exclude=CustomAssert.h \ --exclude=CustomAssert.cpp \ "cpp/ycm/*.cpp" \ "cpp/ycm/*.h" vim-youcompleteme-0+20140207+git18be5c2/third_party/000077500000000000000000000000001227567565400217135ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/000077500000000000000000000000001227567565400240625ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/LICENSE.txt000066400000000000000000000020431227567565400257040ustar00rootroot00000000000000Copyright (c) 2012 Santiago Lezica 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. vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/MANIFEST.in000066400000000000000000000000161227567565400256150ustar00rootroot00000000000000include *.txt vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/README.md000066400000000000000000000020241227567565400253370ustar00rootroot00000000000000frozendict ========== `frozendict` is an immutable wrapper around dictionaries that implements the complete mapping interface. It can be used as a drop-in replacement for dictionaries where immutability is desired. Of course, this is `python`, and you can still poke around the object's internals if you want. The `frozendict` constructor mimics `dict`, and all of the expected interfaces (`iter`, `len`, `repr`, `hash`, `getitem`) are provided. Note that a `frozendict` does not guarantee the immutability of its values, so the utility of `hash` method is restricted by usage. The only difference is that the `copy()` method of `frozendict` takes variable keyword arguments, which will be present as key/value pairs in the new, immutable copy. Example shell usage: from frozendict import frozendict fd = frozendict({ 'hello': 'World' }) print fd # print fd['hello'] # 'World' print fd.copy(another='key/value') # vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/README.txt000066400000000000000000000020721227567565400255610ustar00rootroot00000000000000========== frozendict ========== ``frozendict`` is an immutable wrapper around dictionaries that implements the complete mapping interface. It can be used as a drop-in replacement for dictionaries where immutability is desired. Of course, this is ``python``, and you can still poke around the object's internals if you want. The ``frozendict`` constructor mimics ``dict``, and all of the expected interfaces (``iter``, ``len``, ``repr``, ``hash``, ``getitem``) are provided. Note that a ``frozendict`` does not guarantee the immutability of its values, so the utility of ``hash`` method is restricted by usage. The only difference is that the ``copy()`` method of ``frozendict`` takes variable keyword arguments, which will be present as key/value pairs in the new, immutable copy. Example shell usage:: from frozendict import frozendict fd = frozendict({ 'hello': 'World' }) print fd # print fd['hello'] # 'World' print fd.copy(another='key/value') # vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/frozendict/000077500000000000000000000000001227567565400262315ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/frozendict/__init__.py000066400000000000000000000013641227567565400303460ustar00rootroot00000000000000import collections, operator class frozendict(collections.Mapping): def __init__(self, *args, **kwargs): self.__dict = dict(*args, **kwargs) self.__hash = None def __getitem__(self, key): return self.__dict[key] def copy(self, **add_or_replace): new = frozendict(self) new.__dict.update(add_or_replace) # Feels like cheating return new def __iter__(self): return iter(self.__dict) def __len__(self): return len(self.__dict) def __repr__(self): return '' % repr(self.__dict) def __hash__(self): if self.__hash is None: self.__hash = reduce(operator.xor, map(hash, self.iteritems()), 0) return self.__hash vim-youcompleteme-0+20140207+git18be5c2/third_party/frozendict/setup.py000066400000000000000000000006201227567565400255720ustar00rootroot00000000000000from distutils.core import setup setup( name = 'frozendict', version = '0.3', url = 'https://github.com/slezica/python-frozendict', author = 'Santiago Lezica', author_email = 'slezica89@gmail.com', packages = ['frozendict'], license = 'MIT License', description = 'An immutable dictionary', long_description = open('README.txt').read() ) vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/000077500000000000000000000000001227567565400252615ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/LICENSE000066400000000000000000000011061227567565400262640ustar00rootroot00000000000000Copyright 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. vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/MANIFEST.in000066400000000000000000000001541227567565400270170ustar00rootroot00000000000000include README.rst LICENSE test_requests_futures.py requirements-python-2.7.txt requirements-python-3.2.txt vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/README.rst000066400000000000000000000100301227567565400267420ustar00rootroot00000000000000Asynchronous 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 vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/requests_futures/000077500000000000000000000000001227567565400307115ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/requests_futures/__init__.py000066400000000000000000000011151227567565400330200ustar00rootroot00000000000000# -*- 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()) vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/requests_futures/sessions.py000066400000000000000000000040531227567565400331330ustar00rootroot00000000000000# -*- 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 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) 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) vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/requirements-python-2.7.txt000066400000000000000000000000301227567565400323610ustar00rootroot00000000000000futures requests>=1.2.0 vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/requirements-python-3.2.txt000066400000000000000000000000201227567565400323540ustar00rootroot00000000000000requests>=1.2.0 vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/setup.py000066400000000000000000000027701227567565400270010ustar00rootroot00000000000000#!/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', ), ) vim-youcompleteme-0+20140207+git18be5c2/third_party/requests-futures/test_requests_futures.py000066400000000000000000000055171227567565400323320ustar00rootroot00000000000000#!/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() vim-youcompleteme-0+20140207+git18be5c2/third_party/retries/000077500000000000000000000000001227567565400233705ustar00rootroot00000000000000vim-youcompleteme-0+20140207+git18be5c2/third_party/retries/retries.py000066400000000000000000000065251227567565400254270ustar00rootroot00000000000000#!/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 = range(max_tries) tries.reverse() 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 vim-youcompleteme-0+20140207+git18be5c2/update_boost.sh000077500000000000000000000026031227567565400224120ustar00rootroot00000000000000#!/usr/bin/env bash # This script is used to update cpp/BoostParts to the latest boost version # Give it the full path to the boost_1_XX_X folder # Exit if error set -e if [ -z "$1" ]; then echo "Usage: $0 /path/to/boost_1_XX_X" exit 0 fi pushd $1 ./bootstrap.sh b2 tools/bcp boost_part_dir=`mktemp -d -t boost_parts.XXXXXX` dist/bin/bcp boost/utility.hpp boost/python.hpp boost/bind.hpp boost/lambda/lambda.hpp boost/exception/all.hpp boost/tuple/tuple_io.hpp boost/tuple/tuple_comparison.hpp boost/regex.hpp boost/foreach.hpp boost/smart_ptr.hpp boost/algorithm/string_regex.hpp boost/thread.hpp boost/unordered_map.hpp boost/unordered_set.hpp boost/format.hpp boost/ptr_container/ptr_container.hpp boost/filesystem.hpp boost/filesystem/fstream.hpp boost/utility.hpp boost/algorithm/cxx11/any_of.hpp atomic lockfree assign $boost_part_dir pushd $boost_part_dir # DON'T exit if error set +e find libs \( -name assign -o -name mpi -o -name config -o -name lockfree \) -exec rm -rf '{}' \; find libs \( -name doc -o -name test -o -name examples -o -name build \) -exec rm -rf '{}' \; find libs -not \( -name "*.hpp" -o -name "*.cpp" -o -name "*.ipp" -o -name "*.inl" \) -type f -delete # Exit if error set -e popd popd rm -rf cpp/BoostParts/libs rm -rf cpp/BoostParts/boost cp -R $boost_part_dir/libs cpp/BoostParts/libs cp -R $boost_part_dir/boost cpp/BoostParts/boost rm -rf $boost_part_dir