Repository: ycm-core/YouCompleteMe Branch: master Commit: 6a52780a22df Files: 141 Total size: 1.4 MB Directory structure: gitextract_tkvf_s5t/ ├── .coveragerc ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── config.yml │ │ └── issue.md │ ├── PULL_REQUEST_TEMPLATE.md │ └── workflows/ │ ├── ci.yml │ ├── lock_old_issues.yaml │ └── update_vim_docs.yaml ├── .gitignore ├── .gitmodules ├── .mergify.yml ├── .readme.utf-8.add ├── .vimspector.json ├── .ycm_extra_conf.py ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYING.txt ├── README.md ├── autoload/ │ ├── youcompleteme/ │ │ ├── filetypes.vim │ │ ├── finder.vim │ │ ├── hierarchy.vim │ │ └── symbol.vim │ └── youcompleteme.vim ├── codecov.yml ├── doc/ │ └── youcompleteme.txt ├── install.py ├── install.sh ├── plugin/ │ └── youcompleteme.vim ├── print_todos.sh ├── python/ │ ├── test_requirements.txt │ └── ycm/ │ ├── __init__.py │ ├── base.py │ ├── buffer.py │ ├── client/ │ │ ├── __init__.py │ │ ├── base_request.py │ │ ├── command_request.py │ │ ├── completer_available_request.py │ │ ├── completion_request.py │ │ ├── debug_info_request.py │ │ ├── event_notification.py │ │ ├── inlay_hints_request.py │ │ ├── messages_request.py │ │ ├── omni_completion_request.py │ │ ├── resolve_completion_request.py │ │ ├── semantic_tokens_request.py │ │ ├── shutdown_request.py │ │ ├── signature_help_request.py │ │ └── ycmd_keepalive.py │ ├── diagnostic_filter.py │ ├── diagnostic_interface.py │ ├── hierarchy_tree.py │ ├── inlay_hints.py │ ├── omni_completer.py │ ├── paths.py │ ├── scrolling_range.py │ ├── semantic_highlighting.py │ ├── signature_help.py │ ├── syntax_parse.py │ ├── tests/ │ │ ├── __init__.py │ │ ├── base_test.py │ │ ├── client/ │ │ │ ├── __init__.py │ │ │ ├── base_request_test.py │ │ │ ├── command_request_test.py │ │ │ ├── completion_request_test.py │ │ │ ├── debug_info_request_test.py │ │ │ ├── messages_request_test.py │ │ │ └── omni_completion_request_test.py │ │ ├── command_test.py │ │ ├── completion_test.py │ │ ├── diagnostic_filter_test.py │ │ ├── diagnostic_interface_test.py │ │ ├── event_notification_test.py │ │ ├── mock_utils.py │ │ ├── omni_completer_test.py │ │ ├── paths_test.py │ │ ├── postcomplete_test.py │ │ ├── signature_help_test.py │ │ ├── syntax_parse_test.py │ │ ├── test_utils.py │ │ ├── testdata/ │ │ │ ├── .ycm_extra_conf.py │ │ │ ├── cpp_syntax │ │ │ ├── java_syntax │ │ │ ├── php_syntax │ │ │ ├── python_syntax │ │ │ └── uni¢od€/ │ │ │ └── tags │ │ ├── vimsupport_test.py │ │ └── youcompleteme_test.py │ ├── text_properties.py │ ├── unsafe_thread_pool_executor.py │ ├── vimsupport.py │ └── youcompleteme.py ├── run_tests.py ├── test/ │ ├── .gitignore │ ├── .vimspector.json │ ├── Makefile │ ├── README.md │ ├── commands.test.vim │ ├── completion.common.vim │ ├── completion.test.vim │ ├── completion_info.test.vim │ ├── completion_noresolve.test.vim │ ├── diagnostics.test.vim │ ├── docker/ │ │ ├── ci/ │ │ │ ├── image/ │ │ │ │ └── Dockerfile │ │ │ ├── push │ │ │ └── rebuild │ │ ├── manual/ │ │ │ ├── image/ │ │ │ │ ├── .vim/ │ │ │ │ │ └── vimrc │ │ │ │ └── Dockerfile │ │ │ ├── push │ │ │ ├── rebuild │ │ │ └── run │ │ └── rebuild_all │ ├── filesize.test.vim │ ├── finder.test.vim │ ├── fixit.test.vim │ ├── hierarchies.test.vim │ ├── hover.test.vim │ ├── lib/ │ │ ├── autoload/ │ │ │ └── youcompleteme/ │ │ │ └── test/ │ │ │ ├── commands.vim │ │ │ ├── popup.vim │ │ │ └── setup.vim │ │ ├── plugin/ │ │ │ ├── completion.vim │ │ │ ├── shared.vim │ │ │ └── util.vim │ │ └── run_test.vim │ ├── run_vim_tests │ ├── signature_help.test.vim │ ├── testdata/ │ │ ├── cpp/ │ │ │ ├── auto_include.cc │ │ │ ├── auto_include.h │ │ │ ├── auto_include_workaround.cc │ │ │ ├── complete_with_sig_help.cc │ │ │ ├── completion.cc │ │ │ ├── finder_test.cc │ │ │ ├── fixit.cpp │ │ │ └── hierarchies.cc │ │ ├── diagnostics/ │ │ │ ├── foo.cpp │ │ │ └── foo.xml │ │ ├── python/ │ │ │ ├── doc.py │ │ │ └── test.py │ │ └── vim/ │ │ └── mixed_filetype.vim │ └── vimrc ├── tox.ini ├── update-vim-docs └── vimrc_ycm_minimal ================================================ FILE CONTENTS ================================================ ================================================ FILE: .coveragerc ================================================ [run] plugins = covimerage [report] omit = */tests/* */test/* */third_party/* ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Questions and support url: 'https://github.com/ycm-core/YouCompleteMe/tree/master?tab=readme-ov-file#help-advice-support' about: Please ask and answer questions here. ================================================ FILE: .github/ISSUE_TEMPLATE/issue.md ================================================ --- name: Issue about: Report a bug or suggest an enhancement --- # Issue Prelude **Please complete these steps and check these boxes (by putting an `x` inside the brackets) _before_ filing your issue:** - [ ] I have read and understood YCM's [CONTRIBUTING][cont] document. - [ ] I have read and understood YCM's [CODE_OF_CONDUCT][code] document. - [ ] I have read and understood YCM's [README][readme], **especially the [Frequently Asked Questions][faq] section.** - [ ] I have searched YCM's issue tracker to find issues similar to the one I'm about to report and couldn't find an answer to my problem. ([Example Google search.][search]) - [ ] If filing a bug report, I have included the output of `vim --version`. - [ ] If filing a bug report, I have included the output of `:YcmDebugInfo`. - [ ] If filing a bug report, I have attached the contents of the logfiles using the `:YcmToggleLogs` command. - [ ] If filing a bug report, I have included which OS (including specific OS version) I am using. - [ ] If filing a bug report, I have included a minimal test case that reproduces my issue, using `vim -Nu /path/to/YCM/vimrc_ycm_minimal`, including what I expected to happen and what actually happened. - [ ] If filing a installation failure report, I have included the entire output of `install.py` (or `cmake`/`make`/`ninja`) including its invocation - [ ] **I understand this is an open-source project staffed by volunteers and that any help I receive is a selfless, heartfelt _gift_ of their free time. I know I am not entitled to anything and will be polite and courteous.** - [ ] **I understand my issue may be closed if it becomes obvious I didn't actually perform all of these steps.** Thank you for adhering to this process! It ensures your issue is resolved quickly and that neither your nor our time is needlessly wasted. # Issue Details > Provide a clear description of the problem, including the following key > questions: * What did you do? > Include steps to reproduce here. 1. `vim -Nu /path/to/YCM/ycm_vimrc_minimal` 2. `:edit test.py` 3. Enter insert mode and type `.....` > Include description of a minimal test case, including any actual code required > to reproduce the issue. > If you made changes to `vimrc_ycm_minimal`, pase them here: ``` ``` * What did you expect to happen? > Include description of the expected behaviour. * What actually happened? > Include description of the observed behaviour, including actual output, > screenshots, etc. # Diagnostic data ## Output of `vim --version` ``` Paste output here ``` ## Output of `YcmDebugInfo` ``` Paste output here ``` ## Output of `YcmDiags` ``` Paste output here ``` ## Output of `git rev-parse HEAD` in YouCompleteMe installation directory ``` paste output here ``` ## Contents of YCM, ycmd and completion engine logfiles > Reproduce the issue with `vim -Nu /path/to/YCM/vimrc_ycm_minimal`, which > enabled debug logging and other useful diagnostics. Include a link to a > [gist][] containing all of the log files listed by `:YcmToggleLogs`. ## OS version, distribution, etc. > Include system information here. ## Output of build/install commands > Include link to a [gist][] containing the invocation and entire output of > `install.py` if reporting an installation issue. [cont]: https://github.com/ycm-core/YouCompleteMe/blob/master/CONTRIBUTING.md [code]: https://github.com/ycm-core/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md [readme]: https://github.com/ycm-core/YouCompleteMe/blob/master/README.md [faq]: https://github.com/ycm-core/YouCompleteMe/wiki/FAQ [search]: https://www.google.com/search?q=site%3Ahttps%3A%2F%2Fgithub.com%2Fycm-core%2FYouCompleteMe%2Fissues%20python%20mac [gist]: https://gist.github.com/ ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ # PR Prelude Thank you for working on YCM! :) **Please complete these steps and check these boxes (by putting an `x` inside the brackets) _before_ filing your PR:** - [ ] I have read and understood YCM's [CONTRIBUTING][cont] document. - [ ] I have read and understood YCM's [CODE_OF_CONDUCT][code] document. - [ ] I have included tests for the changes in my PR. If not, I have included a rationale for why I haven't. - [ ] **I understand my PR may be closed if it becomes obvious I didn't actually perform all of these steps.** # Why this change is necessary and useful [Please explain **in detail** why the changes in this PR are needed.] [cont]: https://github.com/ycm-core/YouCompleteMe/blob/master/CONTRIBUTING.md [code]: https://github.com/ycm-core/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: workflow_dispatch: pull_request: push: branches: - master jobs: python-tests: strategy: fail-fast: false matrix: runs-on: [ ubuntu-24.04, macos-14 ] python-arch: [ 'x64' ] include: - runs-on: macos-14 python-arch: 'arm64' exclude: - runs-on: macos-14 python-arch: "x64" env: COVERAGE: true name: "${{ matrix.runs-on }} - Python 3.12 ${{ matrix.python-arch }}" runs-on: ${{ matrix.runs-on }} steps: - uses: actions/checkout@v4 with: submodules: recursive fetch-depth: 0 - name: Install Python uses: actions/setup-python@v5 with: python-version: "3.12" architecture: ${{ matrix.python-arch }} - name: Run pip run: python3 -m pip install -r python/test_requirements.txt - name: Run tests run: python3 run_tests.py --quiet python/ycm/tests - name: summarise coverage run: coverage xml - name: Upload coverage data uses: codecov/codecov-action@v4 with: name: "${{ runner.os }}-3.12-${{ matrix.python-arch }}" token: ${{ secrets.CODECOV_TOKEN }} vim-tests: strategy: fail-fast: false matrix: vim: [ 'new', 'old' ] arch: [ 'x86_64' ] runs-on: ubuntu-24.04 container: 'youcompleteme/ycm-vim-${{ matrix.arch }}-py3:test' env: COVERAGE: true YCM_TEST_STDOUT: true name: "Vim tests - ${{ matrix.vim }}" steps: - uses: actions/checkout@v4 with: submodules: recursive fetch-depth: 0 - name: Install dependencies run: sudo -H pip3 install --break-system-packages -r python/test_requirements.txt - name: Install Java uses: actions/setup-java@v4 with: java-version: 21 distribution: 'temurin' - name: Build ycmd run: python3 ./install.py --force-sudo --ts-completer --clangd-completer --java-completer - name: Run tests in old vim # System vim should be oldest supported. if: matrix.vim == 'old' run: ./test/run_vim_tests --vim /usr/bin/vim - name: Run tests in new vim if: matrix.vim == 'new' run: ./test/run_vim_tests - name: Combine and summarise coverage run: coverage combine && coverage xml - name: Upload coverage data uses: codecov/codecov-action@v4 with: name: "vim-tests-${{ matrix.vim }}" token: ${{ secrets.CODECOV_TOKEN }} ================================================ FILE: .github/workflows/lock_old_issues.yaml ================================================ name: "Lock Old Issues" on: schedule: - cron: '0 0 * * *' workflow_dispatch: jobs: lock: runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@v2 with: github-token: ${{ github.token }} issue-lock-inactive-days: '60' # issue-exclude-created-before: '' # issue-exclude-labels: '' # issue-lock-labels: '' # issue-lock-comment: '' # issue-lock-reason: 'resolved' # pr-lock-inactive-days: '365' # pr-exclude-created-before: '' # pr-exclude-labels: '' # pr-lock-labels: '' # pr-lock-comment: '' # pr-lock-reason: 'resolved' process-only: 'issues' ================================================ FILE: .github/workflows/update_vim_docs.yaml ================================================ name: "Update vim docs" on: push: branches: - master paths: - 'README.md' workflow_dispatch: jobs: update-vim-docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: 'Update local repo' run: './update-vim-docs' - name: 'Check diffs' run: 'git diff' - name: 'Create pull request' uses: peter-evans/create-pull-request@v4 id: cpr with: token: ${{ secrets.VIMSPECTOR_UPDATE_BOT_PAT }} push-to-fork: VimspectorUpdateBot/YouCompleteMe commit-message: "Update vim docs" branch: 'auto/update-vim-docs' delete-branch: true title: "[Auto] Update vim docs" body: "Update the vim docs after recent changes" labels: "auto" - name: Check outputs run: | echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}" echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}" ================================================ FILE: .gitignore ================================================ # Compiled Object files *.slo *.lo *.o # Compiled Dynamic libraries *.dll *.so *.dylib # Compiled Static libraries *.lai *.la *.a # Python *.py[cod] # Installer logs pip-log.txt # Unit test / coverage reports .coverage cover/ .tox nosetests.xml .noseids #Translations *.mo #Mr Developer .mr.developer.cfg # custom ycm_core_tests # When we use the bcp tool to copy over the parts of boost we care about, it # also copies some cruft files we don't need; this ignores them cpp/BoostParts/libs/*/build cpp/BoostParts/libs/*/test # These folders in cpp/llvm contain lots of upstream cruft we don't care # about and would rather not have in our tree... cpp/llvm/docs/* cpp/llvm/tools/clang/www/* # ... but excluding these LLVMBuild.txt files breaks the build so we need to # explicitely include them !LLVMBuild.txt # Exclude auto generated vim doc tags. doc/tags # Coverage files .coverage .coverage.* coverage.xml .readme.utf-8.add.spl ================================================ FILE: .gitmodules ================================================ [submodule "third_party/ycmd"] path = third_party/ycmd url = https://github.com/ycm-core/ycmd ================================================ FILE: .mergify.yml ================================================ # https://blog.mergify.com/strict-mode-deprecation/ queue_rules: - name: duplicated default from Automatic merge on Azure Pipelines and Reviewable successes queue_conditions: - base=master - "#approved-reviews-by>=2" - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 # - status-success=windows-2019 - Python 3.9 x64 # - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - status-success=code-review/reviewable merge_conditions: - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old merge_method: merge - name: duplicated default from Manual merge on Azure Pipelines and Maintainer Override queue_conditions: - base=master - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - "#approved-reviews-by>=1" - "#changes-requested-reviews-by=0" - label="Ship It!" merge_conditions: - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old merge_method: merge - name: duplicated default from Manual merge on Pipelines and Maintainer Override from owner PR queue_conditions: - base=master - author=puremourning - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - "#changes-requested-reviews-by=0" - label="Ship It!" merge_conditions: - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old merge_method: merge - name: duplicated default from Merge auto pr when approved queue_conditions: - author=VimspectorUpdateBot - label=auto - base=master - status-success=code-review/reviewable - "#approved-reviews-by>=1" - "#changes-requested-reviews-by=0" merge_conditions: - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 - status-success=windows-2019 - Python 3.9 x64 - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old merge_method: merge pull_request_rules: - name: Automatic merge on Azure Pipelines and Reviewable successes conditions: - base=master - "#approved-reviews-by>=2" - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 # - status-success=windows-2019 - Python 3.9 x64 # - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - status-success=code-review/reviewable actions: &merge-actions comment: message: Thanks for sending a PR! - name: Manual merge on Azure Pipelines and Maintainer Override conditions: - base=master - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 # - status-success=windows-2019 - Python 3.9 x64 # - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - "#approved-reviews-by>=1" - "#changes-requested-reviews-by=0" - label="Ship It!" actions: <<: *merge-actions - name: Manual merge on Pipelines and Maintainer Override from owner PR conditions: - base=master - author=puremourning - status-success=ubuntu-24.04 - Python 3.9 x64 - status-success=macos-14 - Python 3.9 arm64 # - status-success=windows-2019 - Python 3.9 x64 # - status-success=windows-2019 - Python 3.9 x86 - status-success=Vim tests - new - status-success=Vim tests - old - "#changes-requested-reviews-by=0" - label="Ship It!" actions: <<: *merge-actions - name: Merge auto pr when approved conditions: - author=VimspectorUpdateBot - label=auto - base=master # Review - status-success=code-review/reviewable - "#approved-reviews-by>=1" - "#changes-requested-reviews-by=0" actions: <<: *merge-actions - name: Automatic merge on Azure Pipelines and Reviewable successes + Manual merge on Azure Pipelines and Maintainer Override + Manual merge on Pipelines and Maintainer Override from owner PR + Merge auto pr when approved conditions: [] actions: queue: ================================================ FILE: .readme.utf-8.add ================================================ AST Autocommands CMake CUDA Completers Ctags Ctrl CursorHold Doxygen Eclim Eclim's FixIt Freenode Gitter GoTo Gopls Homebrew Homebrew ICCF JDK JSON Kotlin LLVM LSP LTS ListToggle MSVC MacVim Neovim OmniSharp Omnisharp Syntastic TSServer TypeScript UltiSnips VimScript Vimspector Vundle WB YCM YCM's YcmCompleter YouCompleteMe asciicast async autocommand clangd clangd's classpath coc compiledb completeopt completers conf config configuration csharp ctags docstrings echo'd filepath filesystem filetype filetypes freenode globbing gopls gradle gvim javadoc jdt js keypress lagginess libclang lightline lsp macOS md npm omnicomplete omnicompletion omnifunc omnifuncs onType popup precompiled py quickfix realtime rls statusline sys toolchain unicode unsetting v3 vimrc whitelist whitelisted whitespace xbuild xml ycm ycmd ycmd's ================================================ FILE: .vimspector.json ================================================ { "$schema": "https://puremourning.github.io/vimspector/schema/vimspector.schema.json", "configurations": { "Python: Attach To Vim": { "variables": { "port": "5678", "host": "localhost" }, "adapter": "multi-session", "configuration": { "request": "attach" } }, "python - launch pytest": { "adapter": "debugpy", "variables": [ { "python": { "shell": "/bin/bash -c 'if [ -z \"${dollar}VIRTUAL_ENV\" ]; then echo $$(which python3); else echo \"${dollar}VIRTUAL_ENV/bin/python\"; fi'" } }, { "python_path": { "shell": [ "${python}", "${workspaceRoot}/run_tests.py", "--dump-path" ] } } ], "configuration": { "name": "Python run test", "type": "debugpy", "request": "launch", "cwd": "${workspaceRoot}", "stopOnEntry": false, "console": "integratedTerminal", "justMyCode": true, "logToFile": true, "showReturnValue": true, "debugOptions": [], "module": "unittest", "python": "${python}", "args": [ "-v", "${Test}" ], "env": { "PYTHONPATH": "${python_path}", "LD_LIBRARY_PATH": "${workspaceRoot}/third_party/ycmd/third_party/clang/lib", "YCM_TEST_NO_RETRY": "1" } } } } } ================================================ FILE: .ycm_extra_conf.py ================================================ # 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.path as p import subprocess DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) ) DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) def GetStandardLibraryIndexInSysPath( sys_path ): for index, path in enumerate( sys_path ): if p.isfile( p.join( path, 'os.py' ) ): return index raise RuntimeError( 'Could not find standard library path in Python path.' ) def PythonSysPath( **kwargs ): sys_path = kwargs[ 'sys_path' ] dependencies = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ), p.join( DIR_OF_THIRD_PARTY, 'requests-futures' ), p.join( DIR_OF_THIRD_PARTY, 'ycmd' ), p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'idna' ), p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'chardet' ), p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'urllib3', 'src' ), p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'certifi' ), p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'requests' ) ] # The concurrent.futures module is part of the standard library on Python 3. interpreter_path = kwargs[ 'interpreter_path' ] major_version = int( subprocess.check_output( [ interpreter_path, '-c', 'import sys; print( sys.version_info[ 0 ] )' ] ).rstrip().decode( 'utf8' ) ) if major_version == 2: dependencies.append( p.join( DIR_OF_THIRD_PARTY, 'pythonfutures' ) ) sys_path[ 0:0 ] = dependencies sys_path.insert( GetStandardLibraryIndexInSysPath( sys_path ) + 1, p.join( DIR_OF_THIRD_PARTY, 'python-future', 'src' ) ) return sys_path ================================================ FILE: CODE_OF_CONDUCT.md ================================================ We, the maintainers, pledge to treat all contributors with respect and require that contributors reciprocate. The maintainers will not tolerate unwelcome, impolite, abusive or unprofessional behaviour. At the discretion of the maintainers, users who persist in behaving in a way that is unwelcome may be subject to a ban. This applies to all interactions related to this project and any associated projects. ================================================ FILE: CONTRIBUTING.md ================================================ Writing issue reports ===================== ### Bugs and features only 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. ### Where to go for help **A good place to ask questions is the [Gitter room][gitter] or the [ycm-users][] Google group**. Rule of thumb: if you're not sure whether your problem is a real bug, ask on the room or the group. Don't go to `#vim` on freenode for support. See the [readme][help-advice-support] for further help. ### Installation problem - read the docs **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. For installation problems, make sure that any issue report includes the entire output of any build or installation commands, including **the command used to run them**. For common issues such as "the ycmd server SHUT DOWN", please check the GitHub Wiki. ### Other problems - check the issue tracker 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. However, if the issue you found is **closed as resolved** (e.g. with a PR or the original user's problem was resolved), raise a **new issue**, because you've found a new problem. Reference the original issue if you think that's useful information. Please note: Closed issues which have been inactive for 60 days will be locked, this helps to keep discussions focussed. If you believe you are still experiencing an issue which has been closed, please raise a new issue, completing the issue template. If you do find a similar _open_ issue, **don't just post 'me too' or similar** responses. This almost never helps resolve the issue, and just causes noise for the maintainers. Only post if it will aid the maintainers in solving the issue; if there are existing diagnostics requested in the thread, perform them and post the results. When replying, follow the instructions for getting the required diagnostics for posting a new issue (see below), and add them to your response. This is likely to help the maintainers find a fix for you, rather than have them spend time requesting them again. To be clear, the maintainers *always* need the diagnostics (debug info, log files, versions, etc.) even for responses on existing issues. You should also **search the archives of the [ycm-users][] mailing list**. ### Check your YCM version Lastly, **make sure you are running the latest version of YCM**. The issue you have encountered may have already been fixed. **Don't forget to recompile ycm_core.so too** (usually by just running `install.py` again). ## Creating an issue 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. Most importantly, **read and complete the issue template**. The maintainers rely on the style and structure of the issue template to quickly resolve your issue. If you don't complete it in full, then the maintainers may elect to ignore or simply close your issue. This isn't personal, it's just that they are busy too. 2. **Check that your issue reproduces with a minimal configuration**. Run `vim -Nu /path/to/YCM/vimrc_ycm_minimal` and reproduce this issue. If it doesn't repro, then copy your ycm-specific settings into this file and try again. If it still doesn't repro, the issue is likely with another plugin. 3. **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. 4. Explain **what you expected to happen**, and **what actually happened**. This helps us understand if it is a bug, or just a misunderstanding of the behavior. 5. Add the output of [the `:YcmDebugInfo` command][ycm-debug-info-command]. Make sure that when you run this, your cursor is in the file that is experiencing the issue. 6. Reproduce your issue using `vim -Nu /path/to/YCM/vimrc_ycm_minimal` and attach the contents of the logfiles. Use [the `:YcmToggleLogs` command][ycm-toggle-logs-command] to directly open them in Vim. 7. **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. 8. **Include your OS and OS version.** 9. **Include the output of `vim --version`.** Creating good pull requests =========================== 1. **Follow the code style of the existing codebase.** - The Python code **DOES NOT** follow PEP 8. This is not an oversight, this is by choice. You can dislike this as much as you want, but you still need to follow the existing style. Look at other Python files to see what the style is. - The C++ code has an automated formatter (`style_format.sh` that runs `astyle`) but it's not perfect. Again, look at the other C++ files and match the code style you see. - Same thing for VimScript. Match the style of the existing code. 2. **Your code needs to be well written and easy to maintain**. This is of the _utmost_ importance. Other people will have to maintain your code so don't just throw stuff against the wall until things kinda work. 3. **Split your pull request into several smaller ones if possible.** This makes it easier to review your changes, which means they will be merged faster. 4. **Write tests for your code**. If you're changing the VimScript code then you don't have to since it's hard to test that code. This is also why you should strive to implement your change in Python if at all possible (and if it makes sense to do so). Python is also _much_ faster than VimScript. 5. **Explain in detail why your pull request makes sense.** Ask yourself, would this feature be helpful to others? Not just a few people, but a lot of YCM’s users? See, good features are useful to many. If your feature is only useful to you and _maybe_ a couple of others, then that’s not a good feature. There is such a thing as “feature overload”. When software accumulates so many features of which most are only useful to a handful, then that software has become “bloated”. We don’t want that. Requests for features that are obscure or are helpful to but a few, or are not part of YCM's "vision" will be rejected. Yes, even if you provide a patch that completely implements it. Please include details on exactly what you would like to see, and why. The why is important - it's not always clear why a feature is really useful. And sometimes what you want can be done in a different way if the reason for the change is known. _What goal is your change trying to accomplish?_ [build-bots]: https://dev.azure.com/YouCompleteMe/YCM/_build/latest?definitionId=1&branchName=master [ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users [gitter]: https://gitter.im/Valloric/YouCompleteMe [help-advice-support]: https://github.com/ycm-core/YouCompleteMe#help-advice-support [ycm-debug-info-command]: https://github.com/ycm-core/YouCompleteMe#the-ycmdebuginfo-command [ycm-toggle-logs-command]: https://github.com/ycm-core/YouCompleteMe#the-ycmtogglelogs-command ================================================ FILE: COPYING.txt ================================================ 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 . ================================================ FILE: README.md ================================================ YouCompleteMe: a code-completion engine for Vim =============================================== [![Gitter room](https://img.shields.io/gitter/room/Valloric/YouCompleteMe.svg)](https://gitter.im/Valloric/YouCompleteMe) [![Build status](https://dev.azure.com/YouCompleteMe/YCM/_apis/build/status/ycm-core.YouCompleteMe?branchName=master)](https://dev.azure.com/YouCompleteMe/YCM/_build?definitionId=3&branchName=master) [![Coverage status](https://img.shields.io/codecov/c/github/ycm-core/YouCompleteMe/master.svg)](https://codecov.io/gh/ycm-core/YouCompleteMe) Help, Advice, Support --------------------- Looking for help, advice, or support? Having problems getting YCM to work? First carefully read the [installation instructions](#installation) for your OS. We recommend you use the supplied `install.py` - the "full" installation guide is for rare, advanced use cases and most users should use `install.py`. If the server isn't starting and you're getting a "YouCompleteMe unavailable" error, check the [Troubleshooting][wiki-troubleshooting] guide. Next, check the [User Guide](#user-guide) section on the semantic completer that you are using. For C/C++/Objective-C/Objective-C++/CUDA, you _must_ read [this section](#c-family-semantic-completion). Finally, check the [FAQ][wiki-faq]. If, after reading the installation and user guides, and checking the FAQ, you're still having trouble, check the [contacts](#contact) section below for how to get in touch. Please do **NOT** go to #vim on Freenode for support. Please contact the YouCompleteMe maintainers directly using the [contact details](#contact) below. # Vundle Please note that the below instructions suggest using Vundle. Currently there are problems with Vundle, so here are some [alternative instructions](https://github.com/ycm-core/YouCompleteMe/issues/4134#issuecomment-1446235584) using Vim packages. Contents -------- - [Intro](#intro) - [Installation](#installation) - [Requirements](#requirements) - [macOS](#macos) - [Linux 64-bit](#linux-64-bit) - [Windows](#windows) - [Full Installation Guide](#full-installation-guide) - [Quick Feature Summary](#quick-feature-summary) - [User Guide](#user-guide) - [General Usage](#general-usage) - [Client-Server Architecture](#client-server-architecture) - [Completion String Ranking](#completion-string-ranking) - [General Semantic Completion](#general-semantic-completion) - [Signature Help](#signature-help) - [Semantic Highlighting](#semantic-highlighting) - [Inlay Hints](#inlay-hints) - [C-family Semantic Completion](#c-family-semantic-completion) - [Java Semantic Completion](#java-semantic-completion) - [C# Semantic Completion](#c-semantic-completion) - [Python Semantic Completion](#python-semantic-completion) - [Rust Semantic Completion](#rust-semantic-completion) - [Go Semantic Completion](#go-semantic-completion) - [JavaScript and TypeScript Semantic Completion](#javascript-and-typescript-semantic-completion) - [Semantic Completion for Other Languages](#semantic-completion-for-other-languages) - [LSP Configuration](#lsp-configuration) - [Writing New Semantic Completers](#writing-new-semantic-completers) - [Diagnostic Display](#diagnostic-display) - [Diagnostic Highlighting Groups](#diagnostic-highlighting-groups) - [Symbol Search](#symbol-search) - [Type/Call Hierarchy](#typecall-hierarchy) - [Commands](#commands) - [YcmCompleter subcommands](#ycmcompleter-subcommands) - [GoTo Commands](#goto-commands) - [Semantic Information Commands](#semantic-information-commands) - [Refactoring Commands](#refactoring-commands) - [Miscellaneous Commands](#miscellaneous-commands) - [Functions](#functions) - [Autocommands](#autocommands) - [Options](#options) - [FAQ](#faq) - [Contributor Code of Conduct](#contributor-code-of-conduct) - [Contact](#contact) - [License](#license) - [Sponsorship](#sponsorship) Intro ----- YouCompleteMe is a fast, as-you-type, fuzzy-search code completion, comprehension and refactoring engine for [Vim][]. It has several completion engines built-in and supports any protocol-compliant Language Server, so can work with practically any language. YouCompleteMe contains: - an identifier-based engine that works with every programming language, - a powerful [clangd][]-based engine that provides native semantic code completion for C/C++/Objective-C/Objective-C++/CUDA (from now on referred to as "the C-family languages"), - a [Jedi][]-based completion engine for Python 2 and 3, - an [OmniSharp-Roslyn][]-based completion engine for C#, - a [Gopls][]-based completion engine for Go, - a [TSServer][]-based completion engine for JavaScript and TypeScript, - a [rust-analyzer][]-based completion engine for Rust, - a [jdt.ls][]-based completion engine for Java. - a [generic Language Server Protocol implementation for any language](#plugging-an-arbitrary-lsp-server) - 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 completion demo](https://i.imgur.com/0OP4ood.gif) Here's an explanation of what happened in the last 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 the completer engine 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. **And that's not all...** YCM might be the only Vim completion engine with the correct Unicode support. Though we do assume UTF-8 everywhere. ![YouCompleteMe GIF unicode demo](https://user-images.githubusercontent.com/10026824/34471853-af9cf32a-ef53-11e7-8229-de534058ddc4.gif) YCM also provides [semantic IDE-like features](#quick-feature-summary) in a number of languages, including: - displaying signature help (argument hints) when entering the arguments to a function call (Vim only) - [finding declarations, definitions, usages](#goto-commands), etc. of identifiers, and an [interactive symbol finder](#symbol-search) - [displaying type information](#the-gettype-subcommand) for classes, variables, functions etc., - displaying documentation for methods, members, etc. in the [preview window](#the-getdoc-subcommand), or in a [popup next to the cursor](#the-gycm_auto_hover-option) (Vim only) - [fixing common coding errors](#the-fixit-subcommand), like missing semi-colons, typos, etc., - [semantic renaming](#the-refactorrename-subcommand) of variables across files, - formatting code, - removing unused imports, sorting imports, etc. For example, here's a demo of signature help: ![Signature Help Early Demo](https://user-images.githubusercontent.com/10584846/58738348-5060da80-83fd-11e9-9537-d07fdbf4554c.gif) Below we can see YCM being able to do a few things: - Retrieve references across files - Go to declaration/definition - Expand `auto` in C++ - Fix some common errors, and provide refactorings, with `FixIt` - Not shown in the GIF are `GoToImplementation` and `GoToType` for servers that support it. ![YouCompleteMe GIF subcommands demo](https://i.imgur.com/nmUUbdl.gif) And here's some documentation being shown in a hover popup, automatically and manually: ![hover demo](https://user-images.githubusercontent.com/10584846/80312146-91af6500-87db-11ea-996b-7396f3134d1f.gif) Features vary by file type, so make sure to check out the [file type feature summary](#quick-feature-summary) and the [full list of completer subcommands](#ycmcompleter-subcommands) to find out what's available for your favourite languages. You'll also find that YCM has filepath completers (try typing `./` in a file) and a completer that integrates with [UltiSnips][]. Installation ------------ ### Requirements | Runtime | Min Version | Recommended Version (full support) | Python | |---------|-------------|------------------------------------|--------| | Vim | 9.1.0016 | 9.1.0016 | 3.12 | | Neovim | 0.5 | Vim 9.1.0016 | 3.12 | #### Supported Vim Versions Our policy is to support the Vim version that's in the latest LTS of Ubuntu. Vim must have a [working Python 3 runtime](#supported-python-runtime). For Neovim users, our policy is to require the latest released version. Currently, Neovim 0.5.0 is required. Please note that some features are not available in Neovim, and Neovim is not officially supported. #### Supported Python runtime YCM has two components: A server and a client. Both the server and client require Python 3.12 or later 3.x release. For the Vim client, Vim must be, compiled with `--enable-shared` (or `--enable-framework` on macOS). You can check if this is working with `:py3 import sys; print( sys.version)`. It should say something like `3.12.0 (...)`. For Neovim, you must have a python 3.12 runtime and the Neovim python extensions. See Neovim's `:help provider-python` for how to set that up. For the server, you must run the `install.py` script with a python 3.12 (or later) runtime. Anaconda etc. are not supported. YCM will remember the runtime you used to run `install.py` and will use that when launching the server, so if you usually use anaconda, then make sure to use the full path to a real cpython3, e.g. `/usr/bin/python3 install.py --all` etc. Our policy is to support the python3 version that's available in the latest Ubuntu LTS (similar to our Vim version policy). We don't increase the Python runtime version without a reason, though. Typically, we do this when the current python version we're using goes out of support. At that time we will typically pick a version that will be supported for a number of years. #### Supported Compilers In order to provide the best possible performance and stability, ycmd has updated its code to C++17. This requires a version bump of the minimum supported compilers. The new requirements are: | Compiler | Current Min | |----------|----------------| | GCC | 8 | | Clang | 7 | | MSVC | 15.7 (VS 2017) | YCM requires CMake 3.13 or greater. If your CMake is too old, you may be able to simply `pip install --user cmake` to get a really new version. #### Individual completer requirements When enabling language support for a particular language, there may be runtime requirements, such as needing a very recent Java Development Kit for Java support. In general, YCM is not in control of the required versions for the downstream compilers, though we do our best to signal where we know them. ### macOS #### Quick start, installing all completers - Install YCM plugin via [Vundle][] - Install CMake, MacVim and Python 3; Note that the pre-installed *macOS system* Vim is not supported (due to it having broken Python integration). ``` $ brew install cmake python go nodejs ``` - Install mono from [Mono Project](mono-install-macos) (NOTE: on Intel Macs you can also `brew install mono`. On arm Macs, you may require Rosetta) - For Java support you must install a JDK, one way to do this is with Homebrew: ``` $ brew install java $ sudo ln -sfn $(brew --prefix java)/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk ``` - Pre-installed macOS *system* Vim does not support Python 3. So you need to install either a Vim that supports Python 3 OR [MacVim][] with [Homebrew][brew]: - Option 1: Installing a Vim that supports Python 3 ``` brew install vim ``` - Option 2: Installing [MacVim][] ``` brew install macvim ``` - Compile YCM. - For Intel and arm64 Macs, the bundled libclang/clangd work: ``` cd ~/.vim/bundle/YouCompleteMe python3 install.py --all ``` - If you have troubles with finding system frameworks or C++ standard library, try using the homebrew llvm: ``` brew install llvm cd ~/.vim/bundle/YouCompleteMe python3 install.py --system-libclang --all ``` And edit your vimrc to add the following line to use the Homebrew llvm's clangd: ```viml " Use homebrew's clangd let g:ycm_clangd_binary_path = trim(system('brew --prefix llvm')).'/bin/clangd' ``` - For using an arbitrary LSP server, check [the relevant section](#plugging-an-arbitrary-lsp-server) #### Explanation for the quick start These instructions (using `install.py`) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the [full installation guide](#full-installation-guide). A supported Vim version with Python 3 is required. [MacVim][] is a good option, even if you only use the terminal. YCM won't work with the pre-installed Vim from Apple as its Python support is broken. If you don't already use a Vim that supports Python 3 or [MacVim][], install it with [Homebrew][brew]. Install CMake as well: brew install vim cmake OR brew install macvim cmake Install YouCompleteMe with [Vundle][]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the `ycm_core` library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. **NOTE:** If you want C-family completion, you MUST have the latest Xcode installed along with the latest Command Line Tools (they are installed automatically when you run `clang` for the first time, or manually by running `xcode-select --install`) Compiling YCM **with** semantic support for C-family languages through **clangd**: ``` cd ~/.vim/bundle/YouCompleteMe ./install.py --clangd-completer ``` Compiling YCM **without** semantic support for C-family languages: ``` cd ~/.vim/bundle/YouCompleteMe ./install.py ``` The following additional language support options are available: - C# support: install by downloading the [Mono macOS package][mono-install-macos] and add `--cs-completer` when calling `install.py`. - Go support: install [Go][go-install] and add `--go-completer` when calling `install.py`. - JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and add `--ts-completer` when calling `install.py`. - Rust support: add `--rust-completer` when calling `install.py`. - Java support: install [JDK 17][jdk-install] and add `--java-completer` when calling `install.py`. To simply compile with everything enabled, there's a `--all` flag. So, to install with all language features, ensure `xbuild`, `go`, `node` and `npm` tools are installed and in your `PATH`, then simply run: ``` cd ~/.vim/bundle/YouCompleteMe ./install.py --all ``` That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ### Linux 64-bit The following assume you're using Ubuntu 24.04. #### Quick start, installing all completers - Install YCM plugin via [Vundle][] - Install CMake, Vim and Python ``` apt install build-essential cmake vim-nox python3-dev ``` - Install mono-complete, go, node, java, and npm ``` apt install mono-complete golang nodejs openjdk-17-jdk openjdk-17-jre npm ``` - Compile YCM ``` cd ~/.vim/bundle/YouCompleteMe python3 install.py --all ``` - For plugging an arbitrary LSP server, check [the relevant section](#plugging-an-arbitrary-lsp-server) #### Explanation for the quick start These instructions (using `install.py`) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the [full installation guide](#full-installation-guide). Make sure you have a supported version of Vim with Python 3 support and a supported compiler. The latest LTS of Ubuntu is the minimum platform for simple installation. For earlier releases or other distributions, you may have to do some work to acquire the dependencies. If your Vim version is too old, you may need to [compile Vim from source][vim-build] (don't worry, it's easy). Install YouCompleteMe with [Vundle][]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the `ycm_core` library APIs have changed (which happens rarely), YCM will notify you to recompile it. You should then rerun the installation process. Install development tools, CMake, and Python headers: - Fedora-like distributions: ``` sudo dnf install cmake gcc-c++ make python3-devel ``` - Ubuntu LTS: ``` sudo apt install build-essential cmake3 python3-dev ``` Compiling YCM **with** semantic support for C-family languages through **clangd**: ``` cd ~/.vim/bundle/YouCompleteMe python3 install.py --clangd-completer ``` Compiling YCM **without** semantic support for C-family languages: ``` cd ~/.vim/bundle/YouCompleteMe python3 install.py ``` The following additional language support options are available: - C# support: install [Mono][mono-install-linux] and add `--cs-completer` when calling `install.py`. - Go support: install [Go][go-install] and add `--go-completer` when calling `install.py`. - JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and add `--ts-completer` when calling `install.py`. - Rust support: add `--rust-completer` when calling `install.py`. - Java support: install [JDK 17][jdk-install] and add `--java-completer` when calling `install.py`. To simply compile with everything enabled, there's a `--all` flag. So, to install with all language features, ensure `xbuild`, `go`, `node`, and `npm` tools are installed and in your `PATH`, then simply run: ``` cd ~/.vim/bundle/YouCompleteMe python3 install.py --all ``` That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ### Windows ***NOTE***: Windows support is *deprecated* and *unmaintained*. We will do our best to keep it working, but we no longer test it in CI and there is a high likelihood of breakages. #### Quick start, installing all completers - Install YCM plugin via [Vundle][] - Install [Visual Studio Build Tools 2019][visual-studio-download] - Install CMake, Vim and Python - Install go, node and npm - Compile YCM ``` cd YouCompleteMe python3 install.py --all ``` - Add `set encoding=utf-8` to your [vimrc][] - For plugging an arbitrary LSP server, check [the relevant section](#plugging-an-arbitrary-lsp-server) #### Explanation for the quick start These instructions (using `install.py`) are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the [full installation guide](#full-installation-guide). **Important:** we assume that you are using the `cmd.exe` command prompt and that you know how to add an executable to the PATH environment variable. Make sure you have a supported Vim version with Python 3 support. You can check the version and which Python is supported by typing `:version` inside Vim. Look at the features included: `+python3/dyn` for Python 3. Take note of the Vim architecture, i.e. 32 or 64-bit. It will be important when choosing the Python installer. We recommend using a 64-bit client. [Daily updated installers of 32-bit and 64-bit Vim with Python 3 support][vim-win-download] are available. Add the following line to your [vimrc][] if not already present.: ```viml set encoding=utf-8 ``` This option is required by YCM. Note that it does not prevent you from editing a file in another encoding than UTF-8. You can do that by specifying [the `++enc` argument][++enc] to the `:e` command. Install YouCompleteMe with [Vundle][]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the `ycm_core` library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. Download and install the following software: - [Python 3][python-win-download]. Be sure to pick the version corresponding to your Vim architecture. It is _Windows x86_ for a 32-bit Vim and _Windows x86-64_ for a 64-bit Vim. We recommend installing Python 3. Additionally, the version of Python you install must match up exactly with the version of Python that Vim is looking for. Type `:version` and look at the bottom of the page at the list of compiler flags. Look for flags that look similar to `-DDYNAMIC_PYTHON3_DLL=\"python36.dll\"`. This indicates that Vim is looking for Python 3.6. You'll need one or the other installed, matching the version number exactly. - [CMake][cmake-download]. Add CMake executable to the PATH environment variable. - [Build Tools for Visual Studio 2019][visual-studio-download]. During setup, select _C++ build tools_ in _Workloads_. Compiling YCM **with** semantic support for C-family languages through **clangd**: ``` cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py --clangd-completer ``` Compiling YCM **without** semantic support for C-family languages: ``` cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py ``` The following additional language support options are available: - C# support: add `--cs-completer` when calling `install.py`. Be sure that [the build utility `msbuild` is in your PATH][add-msbuild-to-path]. - Go support: install [Go][go-install] and add `--go-completer` when calling `install.py`. - JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and add `--ts-completer` when calling `install.py`. - Rust support: add `--rust-completer` when calling `install.py`. - Java support: install [JDK 17][jdk-install] and add `--java-completer` when calling `install.py`. To simply compile with everything enabled, there's a `--all` flag. So, to install with all language features, ensure `msbuild`, `go`, `node` and `npm` tools are installed and in your `PATH`, then simply run: ``` cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py --all ``` You can specify the Microsoft Visual C++ (MSVC) version using the `--msvc` option. YCM officially supports MSVC 15 (2017), MSVC 16 (Visual Studio 2019) and MSVC 17 (Visual Studio 17 2022). That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ### Full Installation Guide The [full installation guide][wiki-full-install] has been moved to the wiki. Quick Feature Summary ----- ### General (all languages) * Super-fast identifier completer including tags files and syntax elements * Intelligent suggestion ranking and filtering * File and path suggestions * Suggestions from Vim's omnifunc * UltiSnips snippet suggestions ### C-family languages (C, C++, Objective C, Objective C++, CUDA) * Semantic auto-completion with automatic fixes * Signature help * Real-time diagnostic display * Go to include/declaration/definition (`GoTo`, etc.) * Go to alternate file (e.g. associated header `GoToAlternateFile`) * Find Symbol (`GoToSymbol`), with interactive search * Document outline (`GoToDocumentOutline`), with interactive search * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Automatically fix certain errors (`FixIt`) * Perform refactoring (`FixIt`) * Reference finding (`GoToReferences`) * Renaming symbols (`RefactorRename `) * Code formatting (`Format`) * Semantic highlighting * Inlay hints * Type hierarchy * Call hierarchy ### C♯ * Semantic auto-completion * Signature help * Real-time diagnostic display * Go to declaration/definition (`GoTo`, etc.) * Go to implementation (`GoToImplementation`) * Find Symbol (`GoToSymbol`), with interactive search * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Automatically fix certain errors (`FixIt`) * Perform refactoring (`FixIt`) * Management of OmniSharp-Roslyn server instance * Renaming symbols (`RefactorRename `) * Code formatting (`Format`) ### Python * Semantic auto-completion * Signature help * Go to definition (`GoTo`) * Find Symbol (`GoToSymbol`), with interactive search * Reference finding (`GoToReferences`) * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Renaming symbols (`RefactorRename `) ### Go * Semantic auto-completion * Signature help * Real-time diagnostic display * Go to declaration/definition (`GoTo`, etc.) * Go to type definition (`GoToType`) * Go to implementation (`GoToImplementation`) * Document outline (`GoToDocumentOutline`), with interactive search * Automatically fix certain errors (`FixIt`) * Perform refactoring (`FixIt`) * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Code formatting (`Format`) * Management of `gopls` server instance * Inlay hints * Call hierarchy ### JavaScript and TypeScript * Semantic auto-completion with automatic import insertion * Signature help * Real-time diagnostic display * Go to definition (`GoTo`, `GoToDefinition`, and `GoToDeclaration` are identical) * Go to type definition (`GoToType`) * Go to implementation (`GoToImplementation`) * Find Symbol (`GoToSymbol`), with interactive search * Reference finding (`GoToReferences`) * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Automatically fix certain errors and perform refactoring (`FixIt`) * Perform refactoring (`FixIt`) * Renaming symbols (`RefactorRename `) * Code formatting (`Format`) * Organize imports (`OrganizeImports`) * Management of `TSServer` server instance * Inlay hints * Call hierarchy ### Rust * Semantic auto-completion * Real-time diagnostic display * Go to declaration/definition (`GoTo`, etc.) * Go to implementation (`GoToImplementation`) * Reference finding (`GoToReferences`) * Document outline (`GoToDocumentOutline`), with interactive search * View documentation comments for identifiers (`GetDoc`) * Automatically fix certain errors (`FixIt`) * Perform refactoring (`FixIt`) * Type information for identifiers (`GetType`) * Renaming symbols (`RefactorRename `) * Code formatting (`Format`) * Management of `rust-analyzer` server instance * Semantic highlighting * Inlay hints * Call hierarchy ### Java * Semantic auto-completion with automatic import insertion * Signature help * Real-time diagnostic display * Go to definition (`GoTo`, `GoToDefinition`, and `GoToDeclaration` are identical) * Go to type definition (`GoToType`) * Go to implementation (`GoToImplementation`) * Find Symbol (`GoToSymbol`), with interactive search * Reference finding (`GoToReferences`) * Document outline (`GoToDocumentOutline`), with interactive search * View documentation comments for identifiers (`GetDoc`) * Type information for identifiers (`GetType`) * Automatically fix certain errors including code generation (`FixIt`) * Renaming symbols (`RefactorRename `) * Code formatting (`Format`) * Organize imports (`OrganizeImports`) * Detection of Java projects * Execute custom server command (`ExecuteCommand `) * Management of `jdt.ls` server instance * Semantic highlighting * Inlay hints * Type hierarchy * Call hierarchy 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" and "smart-[diacritic][]" 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). On top of that, a letter with no diacritic marks will match that letter with or without marks:
matches foo fôo fOo fÔo
foo ✔️ ✔️ ✔️ ✔️
fôo ✔️ ✔️
fOo ✔️ ✔️
fÔo ✔️
Use the TAB key to accept a completion and continue pressing TAB to cycle through the completions. Use Shift-TAB to cycle backward. 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](#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 are libclang-based and clangd-based completers that provide semantic completion for C-family languages. There's a Jedi-based completer for semantic completion for Python. There's also an omnifunc-based completer that uses data from Vim's omnicomplete system to provide semantic completions when no native completer exists for that language in YCM. There are also other completion engines, like the UltiSnips completer and the filepath completer. YCM automatically detects which completion engine would be the best in any situation. On occasion, it queries several of them at once, merges the outputs and presents the results to you. ### Client-Server Architecture YCM has a client-server architecture; the Vim part of YCM is only a thin client that talks to the [ycmd HTTP+JSON server][ycmd] that has the vast majority of YCM logic and functionality. The server is started and stopped automatically as you start and stop Vim. ### Completion String Ranking The subsequence filter removes any completions that do not match the input, but then the sorting system kicks in. It's actually very complicated and uses lots of factors, but suffice it to say that "word boundary" (WB) subsequence character matches are "worth" more than non-WB matches. In effect, this means that 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). Word-boundary characters are all capital characters, characters preceded by an underscore, and the first letter character in the completion string. ### Signature Help Valid signatures are displayed in a second popup menu and the current signature is highlighted along with the current argument. Signature help is triggered in insert mode automatically when `g:ycm_auto_trigger` is enabled and is not supported when it is not enabled. The signatures popup is hidden when there are no matching signatures or when you leave insert mode. If you want to manually control when it is visible, you can map something to `YCMToggleSignatureHelp` (see below). For more details on this feature and a few demos, check out the [PR that proposed it][signature-help-pr]. #### Dismiss signature help The signature help popup sometimes gets in the way. You can toggle its visibility with a mapping. YCM provides the "Plug" mapping `(YCMToggleSignatureHelp)` for this. For example, to hide/show the signature help popup by pressing Ctrl+l in insert mode: `imap (YCMToggleSignatureHelp)`. _NOTE_: No default mapping is provided because insert mappings are very difficult to create without breaking or overriding some existing functionality. Ctrl-l is not a suggestion, just an example. ### Semantic highlighting Semantic highlighting is the process where the buffer text is coloured according to the underlying semantic type of the word, rather than classic syntax highlighting based on regular expressions. This can be powerful additional data that we can process very quickly. This feature is only supported in Vim. For example, here is a function with classic highlighting: ![highliting-classic](https://user-images.githubusercontent.com/10584846/173137003-a265e8b0-84db-4993-98f0-03ee81b9de94.png) And here is the same function with semantic highlighting: ![highliting-semantic](https://user-images.githubusercontent.com/10584846/173137012-7547de0b-145f-45fa-ace3-18943acd2141.png) As you can see, the function calls, macros, etc. are correctly identified. This can be enabled globally with `let g:ycm_enable_semantic_highlighting=1` or per buffer, by setting `b:ycm_enable_semantic_highlighting`. #### Customising the highlight groups YCM uses text properties (see `:help text-prop-intro`) for semantic highlighting. In order to customise the coloring, you can define the text properties that are used. If you define a text property named `YCM_HL_`, then it will be used in place of the defaults. The `` is defined as the Language Server Protocol semantic token type, defined in the [LSP Spec](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens). Some servers also use custom values. In this case, YCM prints a warning including the token type name that you can customise. For example, to render `parameter` tokens using the `Normal` highlight group, you can do this: ```viml call prop_type_add( 'YCM_HL_parameter', { 'highlight': 'Normal' } ) ``` More generally, this pattern can be useful for customising the groups: ```viml let MY_YCM_HIGHLIGHT_GROUP = { \ 'typeParameter': 'PreProc', \ 'parameter': 'Normal', \ 'variable': 'Normal', \ 'property': 'Normal', \ 'enumMember': 'Normal', \ 'event': 'Special', \ 'member': 'Normal', \ 'method': 'Normal', \ 'class': 'Special', \ 'namespace': 'Special', \ } for tokenType in keys( MY_YCM_HIGHLIGHT_GROUP ) call prop_type_add( 'YCM_HL_' . tokenType, \ { 'highlight': MY_YCM_HIGHLIGHT_GROUP[ tokenType ] } ) endfor ``` ## Inlay hints **NOTE**: Highly experimental feature, requiring Vim 9.0.214 or later (not supported in NeoVim). When `g:ycm_enable_inlay_hints` (globally) or `b:ycm_enable_inlay_hints` (for a specific buffer) is set to `1`, then YCM will insert inlay hints as supported by the language semantic engine. An inlay hint is text that is rendered on the screen that is not part of the buffer and is often used to mark up the type or name of arguments, parameters, etc. which help the developer understand the semantics of the code. Here are some examples: * C ![c-inlay](https://user-images.githubusercontent.com/10584846/185708054-68074fc0-e50c-4a65-887c-da6f372b8982.png) * TypeScript ![ts-inlay](https://user-images.githubusercontent.com/10584846/185708156-b52970ce-005f-4f0b-97e7-bdf8feeefedc.png) * Go ![go-inlay](https://user-images.githubusercontent.com/10584846/185708242-e42dab6f-1847-46f1-8585-2d9f2c8a76dc.png) ### Highlight groups By default, YCM renders the inlay hints with the `NonText` highlight group. To override this, define the `YcmInlayHint` highlight yourself, e.g. in your `.vimrc`: ```viml hi link YcmInlayHint Comment ``` Similar to semantic highlighting above, you can override specific highlighting for different inlay hint types by defining text properties named after the kind of inlay hint, for example: ```viml call prop_type_add( 'YCM_INLAY_Type', #{ highlight: 'Comment' } ) ``` The list of inlay hint kinds can be found in `python/ycm/inlay_hints.py` ### Options * `g:ycm_enable_inlay_hints` or `b:ycm_enable_inlay_hints` - enable/disable globally or for local buffer * `g:ycm_clear_inlay_hints_in_insert_mode` - set to `1` to remove all inlay hints when entering insert mode and reinstate them when leaving insert mode ### Toggling Inlay hints can add a lot of text to the screen and may be distracting. You can toggle them on/off instantly, by mapping something to `(YCMToggleInlayHints)`, for example: ```viml nnoremap h (YCMToggleInlayHints) ``` No default mapping is provided for this due to the personal nature of mappings. ### General Semantic Completion You can use Ctrl+Space to trigger the completion suggestions anywhere, even without a string prefix. This is useful to see which top-level functions are available for use. ### C-family Semantic Completion **NOTE:** YCM originally used the `libclang` based engine for C-family, but users should migrate to clangd, as it provides more features and better performance. Users who rely on `override_filename` in their `.ycm_extra_conf.py` will need to stay on the old `libclang` engine. Instructions on how to stay on the old engine are available on [the wiki][libclang-instructions]. Some of the features of clangd: - **Project wide indexing**: Clangd has both dynamic and static index support. The dynamic index stores up-to-date symbols coming from any files you are currently editing, whereas static index contains project-wide symbol information. This symbol information is used for code completion and code navigation. Whereas libclang is limited to the current translation unit(TU). - **Code navigation**: Clangd provides all the GoTo requests libclang provides and it improves those using the above-mentioned index information to contain project-wide information rather than just the current TU. - **Rename**: Clangd can perform semantic rename operations on the current file, whereas libclang doesn't support such functionality. - **Code Completion**: Clangd can perform code completions at a lower latency than libclang; also, it has information about all the symbols in your project so it can suggest items outside your current TU and also provides proper `#include` insertions for those items. - **Signature help**: Clangd provides signature help so that you can see the names and types of arguments when calling functions. - **Format Code**: Clangd provides code formatting either for the selected lines or the whole file, whereas libclang doesn't have such functionality. - **Performance**: Clangd has faster re-parse and code completion times compared to libclang. #### Installation On supported architectures, the `install.py` script will download a suitable clangd (`--clangd-completer`) or libclang (`--clang-completer`) for you. Supported architectures are: * Linux glibc >= 2.39 (Intel, armv7-a, aarch64) - built on ubuntu 24.04 * MacOS >=10.15 (Intel, arm64) - For Intel, compatibility per clang.llvm.org downloads - For arm64, macOS 10.15+ * Windows (Intel) - compatibility per clang.llvm.org downloads ***clangd***: Typically, clangd is installed by the YCM installer (either with `--all` or with `--clangd-completer`). This downloads a pre-built `clangd` binary for your architecture. If your OS or architecture is not supported or is too old, you can install a compatible `clangd` and use [`g:ycm_clangd_binary_path`]() to point to it. ***libclang***: `libclang` can be enabled also with `--all` or `--clang-completer`. As with `clangd`, YCM will try and download a version of `libclang` that is suitable for your environment, but again if your environment can't be supported, you can build or acquire `libclang` for yourself and specify it when building, as: ``` $ EXTRA_CMAKE_ARGS='-DPATH_TO_LLVM_ROOT=/path/to/your/llvm' ./install.py --clang-completer --system-libclang ``` Please note that if using custom `clangd` or `libclang` it _must_ match the version that YCM requires. Currently YCM requires ***clang 17.0.1***. #### Compile flags In order to perform semantic analysis such as code completion, `GoTo`, and diagnostics, YouCompleteMe uses `clangd`, which makes use of clang compiler, sometimes also referred to as LLVM. Like any compiler, clang also requires a set of compile flags in order to parse your code. Simply put: If clang can't parse your code, YouCompleteMe can't provide semantic analysis. There are 2 methods that can be used to provide compile flags to clang: #### Option 1: Use a [compilation database][compdb] The easiest way to get YCM to compile your code is to use a compilation database. A compilation database is usually generated by your build system (e.g. `CMake`) and contains the compiler invocation for each compilation unit in your project. For information on how to generate a compilation database, see the [clang documentation][compdb]. In short: - If using CMake, add `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` when configuring (or add `set( CMAKE_EXPORT_COMPILE_COMMANDS ON )` to `CMakeLists.txt`) and copy or symlink the generated database to the root of your project. - If using Ninja, check out the `compdb` tool (`-t compdb`) in its [docs][ninja-compdb]. - If using GNU make, check out [compiledb][] or [Bear][]. - For other build systems, check out [`.ycm_extra_conf.py`](#option-2-provide-the-flags-manually) below. If no [`.ycm_extra_conf.py`](#option-2-provide-the-flags-manually) is found, YouCompleteMe automatically tries to load a compilation database if there is one. YCM looks for a file named `compile_commands.json` in the directory of the opened file or in any directory above it in the hierarchy (recursively); when the file is found before a local `.ycm_extra_conf.py`, YouCompleteMe stops searching the directories and lets clangd take over and handle the flags. #### Option 2: Provide the flags manually If you don't have a compilation database or aren't able to generate one, you have to tell YouCompleteMe how to compile your code some other way. Every C-family project is different. It is not possible for YCM to guess what compiler flags to supply for your project. Fortunately, YCM provides a mechanism for you to generate the flags for a particular file with _arbitrary complexity_. This is achieved by requiring you to provide a Python module that implements a trivial function that, given the file name as an argument, returns a list of compiler flags to use to compile that file. 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 `Settings` 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 configuration file with the [`g:ycm_global_ycm_extra_conf`](#the-gycm_global_ycm_extra_conf-option) option, 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 [`g:ycm_confirm_extra_conf`](#the-gycm_confirm_extra_conf-option) and [`g:ycm_extra_conf_globlist`](#the-gycm_extra_conf_globlist-option) options respectively. 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. **NOTE**: It is highly recommended to include `-x ` flag to libclang. This is so that the correct language is detected, particularly for header files. Common values are `-x c` for C, `-x c++` for C++, `-x objc` for Objective-C, and `-x cuda` for CUDA. To give you an impression, if your C++ project is trivial, and your usual compilation command is: `g++ -Wall -Wextra -Werror -o FILE.o FILE.cc`, then the following `.ycm_extra_conf.py` is enough to get semantic analysis from YouCompleteMe: ```python def Settings( **kwargs ): return { 'flags': [ '-x', 'c++', '-Wall', '-Wextra', '-Werror' ], } ``` As you can see from the trivial example, YCM calls the `Settings` method which returns a dictionary with a single element `'flags'`. This element is a `list` of compiler flags to pass to libclang for the current file. The absolute path of that file is accessible under the `filename` key of the `kwargs` dictionary. That's it! This is actually enough for most projects, but for complex projects it is not uncommon to integrate directly with an existing build system using the full power of the Python language. For a more elaborate example, [see ycmd's own `.ycm_extra_conf.py`][ycmd_flags_example]. 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. You could also consider using [YCM-Generator][ygen] to generate the `ycm_extra_conf.py` file. #### Errors during compilation 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. ### Java Semantic Completion #### Java Quick Start 1. Ensure that you have enabled the Java completer. See the [installation guide](#installation) for details. 2. Create a project file (gradle or maven) file in the root directory of your Java project, by following the instructions below. 3. (Optional) [Configure the LSP server](#lsp-configuration). The [jdt.ls configuration options][jdtls-preferences] can be found in their codebase. 4. If you previously used Eclim or Syntastic for Java, disable them for Java. 5. Edit a Java file from your project. #### Java Project Files In order to provide semantic analysis, the Java completion engine requires knowledge of your project structure. In particular, it needs to know the class path to use, when compiling your code. Fortunately [jdt.ls][] supports [eclipse project files][eclipse-project], [maven projects][mvn-project] and [gradle projects][gradle-project]. **NOTE:** Our recommendation is to use either Maven or Gradle projects. #### Diagnostic display - Syntastic The native support for Java includes YCM's native real-time diagnostics display. This can conflict with other diagnostics plugins like Syntastic, so when enabling Java support, please **manually disable Syntastic Java diagnostics**. Add the following to your `vimrc`: ```viml let g:syntastic_java_checkers = [] ``` #### Diagnostic display - Eclim The native support for Java includes YCM's native real-time diagnostics display. This can conflict with other diagnostics plugins like Eclim, so when enabling Java support, please **manually disable Eclim Java diagnostics**. Add the following to your `vimrc`: ```viml let g:EclimFileTypeValidate = 0 ``` **NOTE**: We recommend disabling Eclim entirely when editing Java with YCM's native Java support. This can be done temporarily with `:EclimDisable`. #### Eclipse Projects Eclipse-style projects require two files: [.project][eclipse-dot-project] and [.classpath][eclipse-dot-classpath]. If your project already has these files due to previously being set up within Eclipse, then no setup is required. [jdt.ls][] should load the project just fine (it's basically eclipse after all). However, if not, it is possible (easy in fact) to craft them manually, though it is not recommended. You're better off using Gradle or Maven (see below). [A simple eclipse style project example][ycmd-eclipse-project] can be found in the ycmd test directory. Normally all that is required is to copy these files to the root of your project and to edit the `.classpath` to add additional libraries, such as: ```xml ``` It may also be necessary to change the directory in which your source files are located (paths are relative to the .project file itself): ```xml ``` **NOTE**: The eclipse project and classpath files are not a public interface and it is highly recommended to use Maven or Gradle project definitions if you don't already use Eclipse to manage your projects. #### Maven Projects Maven needs a file named [pom.xml][mvn-project] in the root of the project. Once again a simple [pom.xml][ycmd-mvn-pom-xml] can be found in the ycmd source. The format of [pom.xml][mvn-project] files is way beyond the scope of this document, but we do recommend using the various tools that can generate them for you, if you're not familiar with them already. #### Gradle Projects Gradle projects require a [build.gradle][gradle-project]. Again, there is a [trivial example in ycmd's tests][ycmd-gradle-project]. The format of [build.gradle][gradle-project] files are way beyond the scope of this document, but we do recommend using the various tools that can generate them for you if you're not familiar with them already. Some users have experienced issues with their jdt.ls when using the Groovy language for their build.gradle. As such, try using [Kotlin](https://github.com/ycm-core/lsp-examples#kotlin) instead. #### Troubleshooting If you're not getting completions or diagnostics, check the server health: * The Java completion engine takes a while to start up and parse your project. You should be able to see its progress in the command line, and `:YcmDebugInfo`. Ensure that the following lines are present: ``` -- jdt.ls Java Language Server running -- jdt.ls Java Language Server Startup Status: Ready ``` * If the above lines don't appear after a few minutes, check the jdt.ls and ycmd log files using [`:YcmToggleLogs` ](#the-ycmtogglelogs-command). The jdt.ls log file is called `.log` (for some reason). If you get a message about "classpath is incomplete", then make sure you have correctly configured the [project files](#java-project-files). If you get messages about unresolved imports, then make sure you have correctly configured the [project files](#java-project-files), in particular check that the classpath is set correctly. ### C# Semantic Completion YCM relies on [OmniSharp-Roslyn][] to provide completion and code navigation. OmniSharp-Roslyn needs a solution file for a C# project and there are two ways of letting YCM know about your solution files. #### Automatically discovered solution files YCM will scan all parent directories of the file currently being edited and look for a file with `.sln` extension. #### Manually specified solution files If YCM loads `.ycm_extra_conf.py` which contains `CSharpSolutionFile` function, YCM will try to use that to determine the solution file. This is useful when one wants to override the default behaviour and specify a solution file that is not in any of the parent directories of the currently edited file. Example: ```python def CSharpSolutionFile( filepath ): # `filepath` is the path of the file user is editing return '/path/to/solution/file' # Can be relative to the `.ycm_extra_conf.py` ``` If the path returned by `CSharpSolutionFile` is not an actual file, YCM will fall back to the other way of finding the file. #### Use with .NET 6.0 and .NET SDKs YCM ships with older version of OmniSharp-Roslyn based on Mono runtime. It is possible to use it with .NET 6.0 and newer, but it requires manual setup. 1. Download NET 6.0 version of the OmniSharp server for your system from [releases](https://github.com/OmniSharp/omnisharp-roslyn/releases/) 1. Set `g:ycm_roslyn_binary_path` to the unpacked executable `OmniSharp` 1. Create a solution file if one doesn't already exist, it is currently required by YCM for internal bookkeeping 1. Run `dotnet new sln` at the root of your project 1. Run `dotnet sln add ...` for all of your projects 1. Run `:YcmRestartServer` ### Python Semantic Completion YCM relies on the [Jedi][] engine to provide completion and code navigation. By default, it will pick the version of Python running the [ycmd server][ycmd] and use its `sys.path`. While this is fine for simple projects, this needs to be configurable when working with virtual environments or in a project with third-party packages. The next sections explain how to do that. #### Working with virtual environments A common practice when working on a Python project is to install its dependencies in a virtual environment and develop the project inside that environment. To support this, YCM needs to know the interpreter path of the virtual environment. You can specify it by creating a `.ycm_extra_conf.py` file at the root of your project with the following contents: ```python def Settings( **kwargs ): return { 'interpreter_path': '/path/to/virtual/environment/python' } ``` Here, `/path/to/virtual/environment/python` is the path to the Python used by the virtual environment you are working in. Typically, the executable can be found in the `Scripts` folder of the virtual environment directory on Windows and in the `bin` folder on other platforms. If you don't like having to create a `.ycm_extra_conf.py` file at the root of your project and would prefer to specify the interpreter path with a Vim option, read the [Configuring through Vim options](#configuring-through-vim-options) section. #### Working with third-party packages Another common practice is to put the dependencies directly into the project and add their paths to `sys.path` at runtime in order to import them. YCM needs to be told about this path manipulation to support those dependencies. This can be done by creating a `.ycm_extra_conf.py` file at the root of the project. This file must define a `Settings( **kwargs )` function returning a dictionary with the list of paths to prepend to `sys.path` under the `sys_path` key. For instance, the following `.ycm_extra_conf.py` adds the paths `/path/to/some/third_party/package` and `/path/to/another/third_party/package` at the start of `sys.path`: ```python def Settings( **kwargs ): return { 'sys_path': [ '/path/to/some/third_party/package', '/path/to/another/third_party/package' ] } ``` If you would rather prepend paths to `sys.path` with a Vim option, read the [Configuring through Vim options](#configuring-through-vim-options) section. If you need further control on how to add paths to `sys.path`, you should define the `PythonSysPath( **kwargs )` function in the `.ycm_extra_conf.py` file. Its keyword arguments are `sys_path` which contains the default `sys.path`, and `interpreter_path` which is the path to the Python interpreter. Here's a trivial example that inserts the `/path/to/third_party/package` path at the second position of `sys.path`: ```python def PythonSysPath( **kwargs ): sys_path = kwargs[ 'sys_path' ] sys_path.insert( 1, '/path/to/third_party/package' ) return sys_path ``` A more advanced example can be found in [YCM's own `.ycm_extra_conf.py`][ycm_flags_example]. #### Configuring through Vim options You may find it inconvenient to have to create a `.ycm_extra_conf.py` file at the root of each one of your projects in order to set the path to the Python interpreter and/or add paths to `sys.path` and would prefer to be able to configure those through Vim options. Don't worry, this is possible by using the [`g:ycm_extra_conf_vim_data`](#the-gycm_extra_conf_vim_data-option) option and creating a global extra configuration file. Let's take an example. Suppose that you want to set the interpreter path with the `g:ycm_python_interpreter_path` option and prepend paths to `sys.path` with the `g:ycm_python_sys_path` option. Suppose also that you want to name the global extra configuration file `global_extra_conf.py` and that you want to put it in your HOME folder. You should then add the following lines to your vimrc: ```viml let g:ycm_python_interpreter_path = '' let g:ycm_python_sys_path = [] let g:ycm_extra_conf_vim_data = [ \ 'g:ycm_python_interpreter_path', \ 'g:ycm_python_sys_path' \] let g:ycm_global_ycm_extra_conf = '~/global_extra_conf.py' ``` Then, create the `~/global_extra_conf.py` file with the following contents: ```python def Settings( **kwargs ): client_data = kwargs[ 'client_data' ] return { 'interpreter_path': client_data[ 'g:ycm_python_interpreter_path' ], 'sys_path': client_data[ 'g:ycm_python_sys_path' ] } ``` That's it. You are done. Note that you don't need to restart the server when setting one of the options. YCM will automatically pick the new values. ### Rust Semantic Completion YCM uses [rust-analyzer][] for Rust semantic completion. NOTE: Previously, YCM used [rls][] for rust completion. This is no longer supported, as the Rust community has decided on [rust-analyzer][] as the future of Rust tooling. Completions and GoTo commands within the current crate and its dependencies should work out of the box with no additional configuration (provided that you built YCM with the `--rust-completer` flag; see the [*Installation* section](#installation) for details). The install script takes care of installing [the Rust source code][rust-src], so no configuration is necessary. `rust-analyzer` supports a myriad of options. These are configured using [LSP configuration](#lsp-configuration), and are [documented here](https://rust-analyzer.github.io/manual.html#configuration]). ### Go Semantic Completion Completions and GoTo commands should work out of the box (provided that you built YCM with the `--go-completer` flag; see the [*Installation* section](#installation) for details). The server only works for projects with the "canonical" layout. `gopls` also has a load of [documented options](https://github.com/golang/tools/blob/master/gopls/doc/settings.md). You can set these in your `.ycm_extra_conf.py`. For example, to set the build tags: ```python def Settings( **kwargs ): if kwargs[ 'language' ] == 'go': return { 'ls': { 'build.buildFlags': [ '-tags=debug' ] } } } ``` ### JavaScript and TypeScript Semantic Completion **NOTE:** YCM originally used the [Tern][] engine for JavaScript but due to [Tern][] not being maintained anymore by its main author and the [TSServer][] engine offering more features, YCM is moving to [TSServer][]. This won't affect you if you were already using [Tern][] but you are encouraged to do the switch by deleting the `third_party/ycmd/third_party/tern_runtime/node_modules` directory in YCM folder. If you are a new user but still want to use [Tern][], you should pass the `--js-completer` option to the `install.py` script during installation. Further instructions on how to set up YCM with [Tern][] are available on [the wiki][tern-instructions]. All JavaScript and TypeScript features are provided by the [TSServer][] engine, which is included in the TypeScript SDK. To enable these features, install [Node.js 18+ and npm][npm-install] and call the `install.py` script with the `--ts-completer` flag. [TSServer][] relies on [the `jsconfig.json` file][jsconfig.json] for JavaScript and [the `tsconfig.json` file][tsconfig.json] for TypeScript to analyze your project. Ensure the file exists at the root of your project. To get diagnostics in JavaScript, set the `checkJs` option to `true` in your `jsconfig.json` file: ```json { "compilerOptions": { "checkJs": true } } ``` ### Semantic Completion for Other Languages C-family, C#, Go, Java, Python, Rust, and JavaScript/TypeScript languages are supported natively by YouCompleteMe using the [Clang][], [OmniSharp-Roslyn][], [Gopls][], [jdt.ls][], [Jedi][], [rust-analyzer][], and [TSServer][] engines, respectively. Check the [installation](#installation) section for instructions to enable these features if desired. #### Plugging an arbitrary LSP server Similar to other LSP clients, YCM can use an arbitrary LSP server with the help of [`g:ycm_language_server`](#the-gycm_language_server-option) option. An example of a value of this option would be: ```viml let g:ycm_language_server = \ [ \ { \ 'name': 'yaml', \ 'cmdline': [ '/path/to/yaml/server/yaml-language-server', '--stdio' ], \ 'filetypes': [ 'yaml' ] \ }, \ { \ 'name': 'csharp', \ 'cmdline': [ 'OmniSharp', '-lsp' ], \ 'filetypes': [ 'csharp' ], \ 'project_root_files': [ '*.csproj', '*.sln' ] \ }, \ { \ 'name': 'godot', \ 'filetypes': [ 'gdscript' ], \ 'port': 6008, \ 'project_root_files': [ 'project.godot' ] \ } \ ] ``` Each dictionary contains the following keys: `name`, `cmdline`, `port`, `filetypes`, `capabilities`, `project_root_files`, `additional_workspace_dirs`, `triggerCharacters`, and `settings`. The full description of each key can be found in the [ycmd][language_server-configuration] repository. See [the LSP Examples](https://github.com/ycm-core/lsp-examples) project for more examples of configuring the likes of PHP, Ruby, Kotlin, and D. #### LSP Configuration Many LSP servers allow some level of user configuration. YCM enables this with the help of `.ycm_extra_conf.py` files. Here's an example of jdt.ls user examples of configuring the likes of PHP, Ruby, Kotlin, D, and many, many more. ```python def Settings( **kwargs ): if kwargs[ 'language' ] == 'java': return { 'ls': { 'java.format.onType.enabled': True } } ``` The `ls` key tells YCM that the dictionary should be passed to the LSP server. For each of the LSP server's configuration, you should look up the respective server's documentation. Some servers request settings from arbitrary 'sections' of configuration. There is no concept of configuration sections in Vim, so you can specify an additional `config_sections` dictionary which maps section to a dictionary of config required by the server. For example: ```python def Settings( **kwargs ): if kwargs[ 'language' ] == 'java': return { 'ls': { 'java.format.onType.enabled': True }, 'config_sections': { 'some section': { 'some option': 'some value' } } ``` The sections and options/values are completely server-specific and rarely well documented. #### Using `omnifunc` for semantic completion 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 rudimentary omnifuncs for various languages like Ruby, PHP, etc. It depends on the language. You can get a stellar omnifunc for 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` inside Vim and don't forget to have `let g:EclimCompletionMethod = 'omnifunc'` in your vimrc. This will make YCM and Eclim play nice; YCM will use Eclim's omnifuncs as the data source for semantic completions and provide the auto-triggering and subsequence-based matching (and other YCM features) on top of it. ### Writing New Semantic Completers You have two options here: writing an `omnifunc` for Vim's omnicomplete system that YCM will then use through its omni-completer, or a custom completer for YCM using the [Completer API][completer-api]. Here are the differences between the two approaches: - You have to use VimScript to write the omnifunc, but get to use Python to write for the Completer API; this by itself should make you want to use the API. - The Completer API is a _much_ more powerful way to integrate with YCM and it provides a wider set of features. For instance, you can make your Completer query your semantic back-end in an asynchronous fashion, thus not blocking Vim's GUI thread while your completion system is processing stuff. This is impossible with VimScript. All of YCM's completers use the Completer API. - Performance with the Completer API is better since Python executes faster than VimScript. If you want to use the `omnifunc` system, see the relevant Vim docs with `:h complete-functions`. For the Completer API, see [the API docs][completer-api]. If you want to upstream your completer into YCM's source, you should use the Completer API. ### Diagnostic Display YCM will display diagnostic notifications for the C-family, C#, Go, Java, JavaScript, Rust, and TypeScript languages. 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 Finally, you can also style the popup for the detailed diagnostics (it is shown if `g:ycm_show_detailed_diag_in_popup` is set) using the group `YcmErrorPopup`, which falls back to `ErrorMsg`. Note that the line highlighting groups only work when the [`g:ycm_enable_diagnostic_signs`](#the-gycm_enable_diagnostic_signs-option) option is set. If you want highlighted lines but no signs in the Vim gutter, set the `signcolumn` option to `no` in your vimrc: ```viml set signcolumn=no ``` The syntax groups used to highlight regions of text with errors/warnings: - `YcmErrorSection`, which falls back to group `SyntasticError` if it exists and then `SpellBad` - `YcmWarningSection`, which falls back to group `SyntasticWarning` if it exists and then `SpellCap` Here's how you'd change the style for a group: ```viml highlight YcmErrorLine guibg=#3f0000 ``` ### Symbol Search ***This feature requires Vim and is not supported in Neovim*** YCM provides a way to search for and jump to a symbol in the current project or document when using supported languages. You can search for symbols in the current workspace when the `GoToSymbol` request is supported and the current document when `GoToDocumentOutline` is supported. Here's a quick demo: [![asciicast](https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C.svg)](https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C) As you can see, you can type and YCM filters down the list as you type. The current set of matches are displayed in a popup window in the centre of the screen and you can select an entry with the keyboard, to jump to that position. Any matches are then added to the quickfix list. To enable: * `nmap (YCMFindSymbolInWorkspace)` * `nmap (YCMFindSymbolInDocument)` e.g. * `nmap yfw (YCMFindSymbolInWorkspace)` * `nmap yfd (YCMFindSymbolInDocument)` When searching, YCM opens a prompt buffer at the top of the screen for the input and puts you in insert mode. This means that you can hit `` to go into normal mode and use any other input commands that are supported in prompt buffers. As you type characters, the search is updated. Initially, results are queried from all open filetypes. You can hit `` to switch to just the current filetype while the popup is open. While the popup is open, the following keys are intercepted: * ``, ``, ``, `` - select the next item * ``, ``, ``, `` - select the previous item * ``, `` - jump up one screenful of items * ``, `` - jump down one screenful of items * ``, `` - jump to first item * ``, `` - jump to last item * `` - jump to the selected item * `` cancel/dismiss the popup * `` - toggle results from all file types or just the current filetype The search is also cancelled if you leave the prompt buffer window at any time, so you can use window commands `...` for example. #### Closing the popup ***NOTE***: Pressing `` does not close the popup - you must use `Ctrl-c` for that, or use a window command (e.g. `j`) or the mouse to leave the prompt buffer window. ### Type/Call Hierarchy ***This feature requires Vim and is not supported in Neovim*** **NOTE**: This feature is highly experimental and offered in the hope that it is useful. Please help us by reporting issues and offering feedback. YCM provides a way to view and navigate hierarchies. The following hierarchies are supported: * Type hierachy `(YCMTypeHierarchy)`: Display subtypes and supertypes of the symbol under cursor. Expand down to subtypes and up to supertypes. * Call hierarchy `(YCMCallHierarchy)`: Display callees and callers of the symbol under cursor. Expand down to callers and up to callees. Take a look at this [![asciicast](https://asciinema.org/a/659925.svg)](https://asciinema.org/a/659925) for brief demo. Hierarchy UI can be initiated by mapping something to the indicated plug mappings, for example: ```viml nmap yth (YCMTypeHierarchy) nmap ych (YCMCallHierarchy) ``` This opens a "modal" popup showing the current element in the hierarchy tree. The current tree root is aligned to the left and child and parent nodes are expanded to the right. Expand the tree "down" with `` and "up" with ``. The "root" of the tree can be re-focused to the selected item with `` and further `` will show the parents of the selected item. This can take a little getting used to, but it's particularly important with multiple inheritance where a "child" of the current root may actually have other, invisible, parent links. `` on that row will show these by setting the display root to the selected item. When the hierarchy is displayed, the following keys are intercepted: * ``: Drill into the hierarchy at the selected item: expand and show children of the selected item. * ``: Show parents of the selected item. When applied to sub-types, this will re-root the tree at that type, so that all parent types (are displayed). Similar for callers. * ``: Jump to the symbol currently selected. * ``, ``, ``, `j`: Select the next item * ``, ``, ``, `k`; Select the previous item * Any other key: closes the popup without jumping to any location **Note:** you might think the call hierarchy tree is inverted, but we think this way round is more intuitive because this is the typical way that call stacks are displayed (with the current function at the top, and its callers below). Commands -------- ### The `:YcmRestartServer` command If the [ycmd completion server][ycmd] suddenly stops for some reason, you can restart it with this command. ### The `:YcmForceCompileAndDiagnostics` command Calling this command will force YCM to immediately recompile your file and display any new diagnostics it encounters. Do note that recompilation with this command may take a while and during this time the Vim GUI _will_ be blocked. You may want to map this command to a key; try putting `nnoremap :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. If a given error or warning can be fixed by a call to `:YcmCompleter FixIt`, then ` (FixIt available)` is appended to the error or warning text. See the `FixIt` completer subcommand for more information. **NOTE:** The absence of ` (FixIt available)` does not strictly imply a fix-it is not available as not all completers are able to provide this indication. For example, the c-sharp completer provides many fix-its but does not add this additional indication. The `g:ycm_open_loclist_on_ycm_diags` option can be used to prevent the location list from opening, but still have it filled with new diagnostic data. See the _Options_ section for details. ### The `:YcmShowDetailedDiagnostic` command This command shows the full diagnostic text when the user's cursor is on the line with the diagnostic. An options argument can be passed. If the argument is `popup` the diagnostic text will be displayed in a popup at the cursor position. If you prefer the detailed diagnostic to always be shown in a popup, then `let g:ycm_show_detailed_diag_in_popup=1`. ### The `:YcmDebugInfo` command This will print out various debug information for the current file. Useful to see what compile commands will be used for the file if you're using the semantic completion engine. ### The `:YcmToggleLogs` command This command presents the list of logfiles created by YCM, the [ycmd server][ycmd], and the semantic engine server for the current filetype, if any. One of these logfiles can be opened in the editor (or closed if already open) by entering the corresponding number or by clicking on it with the mouse. Additionally, this command can take the logfile names as arguments. Use the `` key (or any other key defined by the `wildchar` option) to complete the arguments or to cycle through them (depending on the value of the `wildmode` option). Each logfile given as an argument is directly opened (or closed if already open) in the editor. Only for debugging purposes. ### The `:YcmCompleter` command This command gives access to a number of additional [IDE-like features](#quick-feature-summary) in YCM, for things like semantic GoTo, type information, FixIt, and refactoring. This command accepts a range that can either be specified through a selection in one of Vim's visual modes (see `:h visual-use`) or on the command line. For instance, `:2,5YcmCompleter` will apply the command from line 2 to line 5. This is useful for [the `Format` subcommand](#the-format-subcommand). Call `YcmCompleter` without further arguments for a list of the commands you can call for the current completer. See the [file type feature summary](#quick-feature-summary) for an overview of the features available for each file type. See the _YcmCompleter subcommands_ section for more information on the available subcommands and their usage. Some commands, like `Format` accept a range, like `:%YcmCompleter Format`. Some commands like `GetDoc` and the various `GoTo` commands respect modifiers, like `:rightbelow YcmCompleter GetDoc`, `:vertical YcmCompleter GoTo`. YcmCompleter Subcommands ------------------------ **NOTE:** See the docs for the `YcmCompleter` command before tackling this section. The invoked subcommand is automatically routed to the currently active semantic completer, so `:YcmCompleter GoToDefinition` will invoke the `GoToDefinition` subcommand on the Python semantic completer if the currently active file is a Python one and on the Clang completer if the currently active file is a C-family language one. You may also want to map the subcommands to something less verbose; for instance, `nnoremap jd :YcmCompleter GoTo` maps the `jd` sequence to the longer subcommand invocation. ### GoTo Commands These commands are useful for jumping around and exploring code. When moving the cursor, the subcommands add entries to Vim's `jumplist` so you can use `CTRL-O` to jump back to where you were before invoking the command (and `CTRL-I` to jump forward; see `:h jumplist` for details). If there is more than one destination, the quickfix list (see `:h quickfix`) is populated with the available locations and opened to the full width at the bottom of the screen. You can change this behavior by using [the `YcmQuickFixOpened` autocommand](#the-ycmquickfixopened-autocommand). #### The `GoToInclude` subcommand Looks up the current line for a header and jumps to it. Supported in filetypes: `c, cpp, objc, objcpp, cuda` #### The `GoToAlternateFile` subcommand Jump to the associated file, as defined by the language server. Typically this will jump you to the associated header file for a C or C++ translation unit. Supported in filetypes: `c, cpp, objc, objcpp, cuda` (clangd only) #### The `GoToDeclaration` subcommand Looks up the symbol under the cursor and jumps to its declaration. Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript` #### 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, cuda, cs, go, java, javascript, python, rust, typescript` #### The `GoTo` subcommand This command tries to perform the "most sensible" GoTo operation it can. Currently, this means that it tries to look up the symbol under the cursor and jumps to its definition if possible; if the definition is not accessible from the current translation unit, jumps to the symbol's declaration. For C-family languages, it first tries to look up the current line for a header and jump to it. For C#, implementations are also considered and preferred. Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript` #### The `GoToImprecise` subcommand WARNING: This command trades correctness for speed! Same as the `GoTo` command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take time to compile but you know that you haven't made any changes since the last parse that would lead to incorrect jumps. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: `c, cpp, objc, objcpp, cuda` #### The `GoToSymbol ` subcommand Finds the definition of all symbols matching a specified string. Note that this does not use any sort of smart/fuzzy matching. However, an [interactive symbol search](#symbol-search) is also available. Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, java, javascript, python, typescript` #### The `GoToReferences` subcommand This command attempts to find all of the references within the project to the identifier under the cursor and populates the quickfix list with those locations. Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust` #### The `GoToImplementation` subcommand Looks up the symbol under the cursor and jumps to its implementation (i.e. non-interface). If there are multiple implementations, instead provides a list of implementations to choose from. Supported in filetypes: `cs, go, java, rust, typescript, javascript` #### The `GoToImplementationElseDeclaration` subcommand Looks up the symbol under the cursor and jumps to its implementation if one, else jump to its declaration. If there are multiple implementations, instead provides a list of implementations to choose from. Supported in filetypes: `cs` #### The `GoToType` subcommand Looks up the symbol under the cursor and jumps to the definition of its type e.g. if the symbol is an object, go to the definition of its class. Supported in filetypes: `go, java, javascript, typescript` #### The `GoToDocumentOutline` subcommand Provides a list of symbols in the current document, in the quickfix list. See also [interactive symbol search](#symbol-search). Supported in filetypes: `c, cpp, objc, objcpp, cuda, go, java, rust` #### The `GoToCallers` and `GoToCallees` subcommands Note: A much more powerful call and type hierarchy can be viewd interactively. See [interactive type and call hierarchy](#interactive-type-and-call-hierarchy). Populate the quickfix list with the callers, or callees respectively, of the function associated with the current cursor position. The semantics of this differ depending on the filetype and language server. Only supported for LSP servers that provide the `callHierarchyProvider` capability. ### Semantic Information Commands These commands are useful for finding static information about the code, such as the types of variables, viewing declarations, and documentation strings. #### The `GetType` subcommand Echos the type of the variable or method under the cursor, and where it differs, the derived type. For example: ```c++ std::string s; ``` Invoking this command on `s` returns `std::string => std::basic_string` **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, go, python, typescript, rust` #### The `GetTypeImprecise` subcommand WARNING: This command trades correctness for speed! Same as the `GetType` command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take time to compile but you know that you haven't made any changes since the last parse that would lead to incorrect type. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: `c, cpp, objc, objcpp, cuda` #### The `GetParent` subcommand Echos the semantic parent of the point under the cursor. The semantic parent is the item that semantically contains the given position. For example: ```c++ class C { void f(); }; void C::f() { } ``` In the out-of-line definition of `C::f`, the semantic parent is the class `C`, of which this function is a member. In the example above, both declarations of `C::f` have `C` as their semantic context, while the lexical context of the first `C::f` is `C` and the lexical context of the second `C::f` is the translation unit. For global declarations, the semantic parent is the translation unit. **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: `c, cpp, objc, objcpp, cuda` #### The `GetDoc` subcommand Displays the preview window populated with quick info about the identifier under the cursor. Depending on the file type, this includes things like: * The type or declaration of identifier, * Doxygen/javadoc comments, * Python docstrings, * etc. The documentation is opened in the preview window, and options like `previewheight` are respected. If you would like to customise the height and position of this window, we suggest a custom command that: * Sets `previewheight` temporarily * Runs the `GetDoc` command with supplied modifiers * Restores `previewheight`. For example: ```viml command -count ShowDocWithSize \ let g:ph=&previewheight \ set previewheight= \ YcmCompleter GetDoc \ let &previewheight=g:ph ``` You can then use something like `:botright vertical 80ShowDocWithSize`. Here's an example of that: https://asciinema.org/a/hE6Pi1gU6omBShwFna8iwGEe9 Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, typescript, rust` #### The `GetDocImprecise` subcommand WARNING: This command trades correctness for speed! Same as the `GetDoc` command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect docs. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: `c, cpp, objc, objcpp, cuda` ### Refactoring Commands These commands make changes to your source code in order to perform refactoring or code correction. YouCompleteMe does not perform any action which cannot be undone, and never saves or writes files to the disk. #### The `FixIt` subcommand Where available, attempts to make changes to the buffer to correct diagnostics, or perform refactoring, on the current line or selection. Where multiple suggestions are available (such as when there are multiple ways to resolve a given warning, or where multiple diagnostics are reported for the current line, or multiple refactoring tweaks are available), the options are presented and one can be selected. Completers that provide diagnostics may also provide trivial modifications to the source in order to correct the diagnostic. Examples include syntax errors such as missing trailing semi-colons, spurious characters, or other errors which the semantic engine can deterministically suggest corrections. A small demo presenting how diagnostics can be fixed with clangd: ![YcmCompleter-FixIt-OnDiagnostic](https://user-images.githubusercontent.com/17928698/206855014-9131a49b-87e8-4ed4-8d91-f2fe7808a0b9.gif) Completers (LSPs) may also provide refactoring tweaks, which may be available even when no diagnostic is presented for the current line. These include function extraction, variable extraction, `switch` population, constructor generation, ... The tweaks work for a selection as well. Consult your LSP for available refactorings. A demonstration of refactoring capabilities with clangd: ![YouCompleter-FixIt-Refactoring](https://user-images.githubusercontent.com/17928698/206855713-3588c8de-d0f5-4725-b65e-bc51110252cc.gif) If no fix-it is available for the current line, or there is no diagnostic on the current line, this command has no effect on the current buffer. If any modifications are made, the number of changes made to the buffer is echo'd and the user may use the editor's undo command to revert. When a diagnostic is available, and `g:ycm_echo_current_diagnostic` is enabled, then the text ` (FixIt)` is appended to the echo'd diagnostic when the completer is able to add this indication. The text ` (FixIt available)` is also appended to the diagnostic text in the output of the `:YcmDiags` command for any diagnostics with available fix-its (where the completer can provide this indication). **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript` #### The `RefactorRename ` subcommand In supported file types, this command attempts to perform a semantic rename of the identifier under the cursor. This includes renaming declarations, definitions, and usages of the identifier, or any other language-appropriate action. The specific behavior is defined by the semantic engine in use. Similar to `FixIt`, this command applies automatic modifications to your source files. Rename operations may involve changes to multiple files, which may or may not be open in Vim buffers at the time. YouCompleteMe handles all of this for you. The behavior is described in [the following section](#multi-file-refactor). Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust, cs` #### Python refactorings The following additional commands are supported for Python: * `RefactorInline` * `RefactorExtractVariable` * `RefactorExtractFunction` See the [jedi docs][jedi-refactor-doc] for what they do. Supported in filetypes: `python` #### Multi-file Refactor When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts to apply those modifications to any existing open, visible buffer in the current tab. If no such buffer can be found, YouCompleteMe opens the file in a new small horizontal split at the top of the current window, applies the change, and then *hides* the window. **NOTE:** The buffer remains open, and must be manually saved. A confirmation dialog is opened prior to doing this to remind you that this is about to happen. Once the modifications have been made, the quickfix list (see `:help quickfix`) is populated with the locations of all modifications. This can be used to review all automatic changes made by using `:copen`. Typically, use the `CTRL-W ` combination to open the selected file in a new split. It is possible to customize how the quickfix window is opened by using [the `YcmQuickFixOpened` autocommand](#the-ycmquickfixopened-autocommand). The buffers are *not* saved automatically. That is, you must save the modified buffers manually after reviewing the changes from the quickfix list. Changes can be undone using Vim's powerful undo features (see `:help undo`). Note that Vim's undo is per-buffer, so to undo all changes, the undo commands must be applied in each modified buffer separately. **NOTE:** While applying modifications, Vim may find files that are already open and have a swap file. The command is aborted if you select Abort or Quit in any such prompts. This leaves the Refactor operation partially complete and must be manually corrected using Vim's undo features. The quickfix list is *not* populated in this case. Inspect `:buffers` or equivalent (see `:help buffers`) to see the buffers that were opened by the command. #### The `Format` subcommand This command formats the whole buffer or some part of it according to the value of the Vim options `shiftwidth` and `expandtab` (see `:h 'sw'` and `:h et` respectively). To format a specific part of your document, you can either select it in one of Vim's visual modes (see `:h visual-use`) and run the command or directly enter the range on the command line, e.g. `:2,5YcmCompleter Format` to format it from line 2 to line 5. Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, go, typescript, rust, cs` #### The `OrganizeImports` subcommand This command removes unused imports and sorts imports in the current file. It can also group imports from the same module in TypeScript and resolve imports in Java. Supported in filetypes: `java, javascript, typescript` ### Miscellaneous Commands These commands are for general administration, rather than IDE-like features. They cover things like the semantic engine server instance and compilation flags. #### The `ExecuteCommand ` subcommand Some LSP completers (currently only Java completers) support executing server-specific commands. Consult the [jdt.ls][] documentation to find out what commands are supported and which arguments are expected. The support for `ExecuteCommand` was implemented to support plugins like [Vimspector][] to debug java, but isn't limited to that specific use case. #### The `RestartServer` subcommand Restarts the downstream semantic engine server for those semantic engines that work as separate servers that YCM talks to. Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript` #### The `ReloadSolution` subcommand Instruct the Omnisharp-Roslyn server to clear its cache and reload all files from the disk. This is useful when files are added, removed, or renamed in the solution, files are changed outside of Vim, or whenever Omnisharp-Roslyn cache is out-of-sync. Supported in filetypes: `cs` Functions -------- ### The `youcompleteme#GetErrorCount` function Get the number of YCM Diagnostic errors. If no errors are present, this function returns 0. For example: ```viml call youcompleteme#GetErrorCount() ``` Both this function and `youcompleteme#GetWarningCount` can be useful when integrating YCM with other Vim plugins. For example, a [lightline][] user could add a diagnostics section to their statusline which would display the number of errors and warnings. ### The `youcompleteme#GetWarningCount` function Get the number of YCM Diagnostic warnings. If no warnings are present, this function returns 0. For example: ```viml call youcompleteme#GetWarningCount() ``` ### The `youcompleteme#GetCommandResponse( ... )` function Run a [completer subcommand](#ycmcompleter-subcommands) and return the result as a string. This can be useful for example to display the `GetDoc` output in a popup window, e.g.: ```viml let s:ycm_hover_popup = -1 function s:Hover() let response = youcompleteme#GetCommandResponse( 'GetDoc' ) if response == '' return endif call popup_hide( s:ycm_hover_popup ) let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} ) endfunction " CursorHold triggers in normal mode after a delay autocmd CursorHold * call s:Hover() " Or, if you prefer, a mapping: nnoremap D :call Hover() ``` **NOTE**: This is only an example, for real hover support, see [`g:ycm_auto_hover`](#the-gycm_auto_hover-option). If the completer subcommand result is not a string (for example, it's a FixIt or a Location), or if the completer subcommand raises an error, an empty string is returned, so that calling code does not have to check for complex error conditions. The arguments to the function are the same as the arguments to the `:YcmCompleter` ex command, e.g. the name of the subcommand, followed by any additional subcommand arguments. As with the `YcmCompleter` command, if the first argument is `ft=` the request is targeted at the specified filetype completer. This is an advanced usage and not necessary in most cases. NOTE: The request is run synchronously and blocks Vim until the response is received, so we do not recommend running this as part of an autocommand that triggers frequently. ### The `youcompleteme#GetCommandResponseAsync( callback, ... )` function This works exactly like `youcompleteme#GetCommandResponse`, except that instead of returning the result, you supply a `callback` argument. This argument must be a `FuncRef` to a function taking a single argument `response`. This callback will be called with the command response at some point later, or immediately. As with `youcompleteme#GetCommandResponse()`, this function will call the callback with `''` (an empty string) if the request is not sent, or if there was some sort of error. Here's an example that's similar to the one above: ```viml let s:ycm_hover_popup = -1 function! s:ShowDataPopup( response ) abort if response == '' return endif call popup_hide( s:ycm_hover_popup ) let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} ) endfunction function! s:GetData() abort call youcompleteme#GetCommandResponseAsync( \ function( 's:ShowDataPopup' ), \ 'GetDoc' ) endfunction autocommand CursorHold * call s:GetData() ``` Again, see [`g:ycm_auto_hover`](#the-gycm_auto_hover-option) for proper hover support. **NOTE**: The callback may be called immediately, in the stack frame that called this function. **NOTE**: Only one command request can be outstanding at once. Attempting to request a second response while the first is outstanding will result in the second callback being immediately called with `''`. Autocommands ------------ ### The `YcmLocationOpened` autocommand This `User` autocommand is fired when YCM opens the location list window in response to the `YcmDiags` command. By default, the location list window is opened to the bottom of the current window and its height is set to fit all entries. This behavior can be overridden by using the `YcmLocationOpened` autocommand which is triggered while the cursor is in the location list window. For instance: ```viml function! s:CustomizeYcmLocationWindow() " Move the window to the top of the screen. wincmd K " Set the window height to 5. 5wincmd _ " Switch back to the working window. wincmd p endfunction autocmd User YcmLocationOpened call s:CustomizeYcmLocationWindow() ``` ### The `YcmQuickFixOpened` autocommand This `User` autocommand is fired when YCM opens the quickfix window in response to the `GoTo*` and `RefactorRename` subcommands. By default, the quickfix window is opened to full width at the bottom of the screen and its height is set to fit all entries. This behavior can be overridden by using the `YcmQuickFixOpened` autocommand which is triggered while the cursor is in the quickfix window. For instance: ```viml function! s:CustomizeYcmQuickFixWindow() " Move the window to the top of the screen. wincmd K " Set the window height to 5. 5wincmd _ endfunction autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow() ``` Options ------- All options have reasonable defaults so if the plug-in works after installation you don't need to change any options. These options can be configured in your [vimrc script][vimrc] by including a line like this: ```viml let g:ycm_min_num_of_chars_for_completion = 1 ``` Note that after changing an option in your [vimrc script][vimrc] you have to restart [ycmd][] with the `:YcmRestartServer` command for the changes to take effect. ### The `g:ycm_min_num_of_chars_for_completion` option This option controls the number of characters the user needs to type before identifier-based completion suggestions are triggered. For example, if the option is set to `2`, then when the user types a second alphanumeric character after a whitespace character, completion suggestions will be triggered. This option is NOT used for semantic completion. Setting this option to a high number like `99` effectively turns off the identifier completion engine and just leaves the semantic engine. Default: `2` ```viml let g:ycm_min_num_of_chars_for_completion = 2 ``` ### The `g:ycm_min_num_identifier_candidate_chars` option This option controls the minimum number of characters that a completion candidate coming from the identifier completer must have to be shown in the popup menu. A special value of `0` means there is no limit. **NOTE:** This option only applies to the identifier completer; it has no effect on the various semantic completers. Default: `0` ```viml let g:ycm_min_num_identifier_candidate_chars = 0 ``` ### The `g:ycm_max_num_candidates` option This option controls the maximum number of semantic completion suggestions shown in the completion menu. This only applies to suggestions from semantic completion engines; see [the `g:ycm_max_identifier_candidates` option](#the-gycm_max_num_identifier_candidates-option) to limit the number of suggestions from the identifier-based engine. A special value of `0` means there is no limit. **NOTE:** Setting this option to `0` or to a value greater than `100` is not recommended as it will slow down completion when there is a very large number of suggestions. Default: `50` ```viml let g:ycm_max_num_candidates = 50 ``` ### The `g:ycm_max_num_candidates_to_detail` option Some completion engines require completion candidates to be 'resolved' in order to get detailed info such as inline documentation, method signatures, etc. This information is displayed by YCM in the preview window, or if `completeopt` contains `popup`, in the info popup next to the completion menu. By default, if the info popup is in use, and there are more than 10 candidates, YCM will defer resolving candidates until they are selected in the completion menu. Otherwise, YCM must resolve the details upfront, which can be costly. If neither `popup` nor `preview` are in `completeopt`, YCM disables resolving altogether as the information would not be displayed. This setting can be used to override these defaults and controls the number of completion candidates that should be resolved upfront. Typically users do not need to change this, as YCM will work out an appropriate value based on your `completeopt` and `g:ycm_add_preview_to_completeopt` settings. However, you may override this calculation by setting this value to a number: * `-1` - Resolve all candidates upfront * `0` - Never resolve any candidates upfront. * `> 0` - Resolve up to this many candidates upfront. If the number of candidates is greater than this value, no candidates are resolved. In the latter two cases, if `completeopt` contains `popup`, then candidates are resolved on demand asynchronously. Default: * `0` if neither `popup` nor `preview` are in `completeopt`. * `10` if `popup` is in completeopt. * `-1` if `preview` is in completeopt. Example: ```viml let g:ycm_max_num_candidates_to_detail = 0 ``` ### The `g:ycm_max_num_identifier_candidates` option This option controls the maximum number of completion suggestions from the identifier-based engine shown in the completion menu. A special value of `0` means there is no limit. **NOTE:** Setting this option to `0` or to a value greater than `100` is not recommended as it will slow down completion when there is a very large number of suggestions. Default: `10` ```viml let g:ycm_max_num_identifier_candidates = 10 ``` ### 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`. When `g:ycm_auto_trigger` is `0`, YCM sets the `completefunc`, so that you can manually trigger normal completion using `C-x C-u`. If you want to map something else to trigger completion, such as `C-d`, then you can map it to `(YCMComplete)`. For example: ```viml let g:ycm_auto_trigger = 0 imap (YCMComplete) ``` NOTE: It's not possible to map one of the keys in `g:ycm_key_list_select_completion` (or similar) to `(YCMComplete)`. In practice that means that you can't use `` for this. Default: `1` ```viml let g:ycm_auto_trigger = 1 ``` ### The `g:ycm_filetype_whitelist` option This option controls for which Vim filetypes (see `:h filetype`) should YCM be turned on. The option value should be a Vim dictionary with keys being filetype strings (like `python`, `cpp`, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter). The `*` key is special and matches all filetypes. By default, the whitelist contains only this `*` key. YCM also has a `g:ycm_filetype_blacklist` option that lists filetypes for which YCM shouldn't be turned on. YCM will work only in filetypes that both the whitelist and the blacklist allow (the blacklist "allows" a filetype by _not_ having it as a key). For example, let's assume you want YCM to work in files with the `cpp` filetype. The filetype should then be present in the whitelist either directly (`cpp` key in the whitelist) or indirectly through the special `*` key. It should _not_ be present in the blacklist. Filetypes that are blocked by either of the lists will be completely ignored by YCM, meaning that neither the identifier-based completion engine nor the semantic engine will operate in them. You can get the filetype of the current file in Vim with `:set ft?`. Default: `{'*': 1}` ```viml let g:ycm_filetype_whitelist = {'*': 1} ``` ** Completion in buffers with no filetype ** There is one exception to the above rule. YCM supports completion in buffers with no filetype set, but this must be _explicitly_ whitelisted. To identify buffers with no filetype, we use the `ycm_nofiletype` pseudo-filetype. To enable completion in buffers with no filetype, set: ```viml let g:ycm_filetype_whitelist = { \ '*': 1, \ 'ycm_nofiletype': 1 \ } ``` ### The `g:ycm_filetype_blacklist` option This option controls for which Vim filetypes (see `:h filetype`) should YCM be turned off. The option value should be a Vim dictionary with keys being filetype strings (like `python`, `cpp`, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter). See the `g:ycm_filetype_whitelist` option for more details on how this works. Default: `[see next line]` ```viml let g:ycm_filetype_blacklist = { \ 'tagbar': 1, \ 'notes': 1, \ 'markdown': 1, \ 'netrw': 1, \ 'unite': 1, \ 'text': 1, \ 'vimwiki': 1, \ 'pandoc': 1, \ 'infolog': 1, \ 'leaderf': 1, \ 'mail': 1 \} ``` In addition, `ycm_nofiletype` (representing buffers with no filetype set) is blacklisted if `ycm_nofiletype` is not _explicitly_ whitelisted (using `g:ycm_filetype_whitelist`). ### The `g:ycm_filetype_specific_completion_to_disable` option This option controls for which Vim filetypes (see `:h filetype`) should the YCM semantic completion engine be turned off. The option value should be a Vim dictionary with keys being filetype strings (like `python`, `cpp`, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter). The listed filetypes will be ignored by the YCM semantic completion engine, but the identifier-based completion engine will still trigger in files of those filetypes. Note that even if semantic completion is not turned off for a specific filetype, you will not get semantic completion if the semantic engine does not support that filetype. You can get the filetype of the current file in Vim with `:set ft?`. Default: `[see next line]` ```viml let g:ycm_filetype_specific_completion_to_disable = { \ 'gitcommit': 1 \} ``` ### The `g:ycm_filepath_blacklist` option This option controls for which Vim filetypes (see `:h filetype`) should filepath completion be disabled. 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. Use this key if you want to completely disable filepath completion: ```viml let g:ycm_filepath_blacklist = {'*': 1} ``` You can get the filetype of the current file in Vim with `:set ft?`. Default: `[see next line]` ```viml let g:ycm_filepath_blacklist = { \ 'html': 1, \ 'jsx': 1, \ 'xml': 1, \} ``` ### The `g:ycm_show_diagnostics_ui` option When set, this option turns on YCM's diagnostic display features. See the _Diagnostic display_ section in the _User Manual_ for more details. Specific parts of the diagnostics UI (like the gutter signs, text highlighting, diagnostic echo, and auto location list population) can be individually turned on or off. See the other options below for details. Note that YCM's diagnostics UI is only supported for C-family languages. When set, this option also makes YCM remove all Syntastic checkers set for the `c`, `cpp`, `objc`, `objcpp`, and `cuda` filetypes since this would conflict with YCM's own diagnostics UI. If you're using YCM's identifier completer in C-family languages but cannot use the clang-based semantic completer for those languages _and_ want to use the GCC Syntastic checkers, unset this option. Default: `1` ```viml let g:ycm_show_diagnostics_ui = 1 ``` ### The `g:ycm_error_symbol` option YCM will use the value of this option as the symbol for errors in the Vim gutter. This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the `g:syntastic_error_symbol` option before using this option's default. Default: `>>` ```viml let g:ycm_error_symbol = '>>' ``` ### The `g:ycm_warning_symbol` option YCM will use the value of this option as the symbol for warnings in the Vim gutter. This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the `g:syntastic_warning_symbol` option before using this option's default. Default: `>>` ```viml let g:ycm_warning_symbol = '>>' ``` ### The `g:ycm_enable_diagnostic_signs` option When this option is set, YCM will put icons in Vim's gutter on lines that have a diagnostic set. Turning this off will also turn off the `YcmErrorLine` and `YcmWarningLine` highlighting. This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the `g:syntastic_enable_signs` option before using this option's default. Default: `1` ```viml let g:ycm_enable_diagnostic_signs = 1 ``` ### The `g:ycm_enable_diagnostic_highlighting` option When this option is set, YCM will highlight regions of text that are related to the diagnostic that is present on a line, if any. This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the `g:syntastic_enable_highlighting` option before using this option's default. Default: `1` ```viml let g:ycm_enable_diagnostic_highlighting = 1 ``` ### The `g:ycm_echo_current_diagnostic` option When this option is set to 1, YCM will echo the text of the diagnostic present on the current line when you move your cursor to that line. If a `FixIt` is available for the current diagnostic, then ` (FixIt)` is appended. If you have a Vim that supports virtual text, you can set this option to the string `virtual-text`, and the diagnostic will be displayed inline with the text, right aligned in the window and wrapping to the next line if there is not enough space, for example: ![Virtual text diagnostic demo][diagnostic-echo-virtual-text1] ![Virtual text diagnostic demo][diagnostic-echo-virtual-text2] **NOTE**: It's _strongly_ recommended to also set `g:ycm_update_diagnostics_in_insert_mode` to `0` when using `virtual-text` for diagnostics. This is due to the increased amount of distraction provided by drawing diagnostics next to your input position. 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` Valid values: * `0` - disabled * `1` - echo diagnostic to the command area * `'virtual-text'` - display the dignostic to the right of the line in the window using virtual text ```viml let g:ycm_echo_current_diagnostic = 1 " Or, when you have Vim supporting virtual text let g:ycm_echo_current_diagnostic = 'virtual-text' ``` ### The `g:ycm_auto_hover` option This option controls whether or not YCM shows documentation in a popup at the cursor location after a short delay. Only supported in Vim. When this option is set to `'CursorHold'`, the popup is displayed on the `CursorHold` autocommand. See `:help CursorHold` for the details, but this means that it is displayed after `updatetime` milliseconds. When set to an empty string, the popup is not automatically displayed. In addition to this setting, there is the `(YCMHover)` mapping, which can be used to manually trigger or hide the popup (it works like a toggle). For example: ```viml nmap D (YCMHover) ``` After dismissing the popup with this mapping, it will not be automatically triggered again until the cursor is moved (i.e. `CursorMoved` autocommand). The displayed documentation depends on what the completer for the current language supports. It's selected heuristically in this order of preference: 1. `GetHover` with `markdown` syntax 2. `GetDoc` with no syntax 3. `GetType` with the syntax of the current file. You can customise this by manually setting up `b:ycm_hover` to your liking. This buffer-local variable can be set to a dictionary with the following keys: * `command`: The YCM completer subcommand which should be run on hover * `syntax`: The syntax to use (as in `set syntax=`) in the popup window for highlighting. * `popup_params`: The params passed to a popup window which gets opened. For example, to use C/C++ syntax highlighting in the popup for C-family languages, add something like this to your vimrc: ```viml augroup MyYCMCustom autocmd! autocmd FileType c,cpp let b:ycm_hover = { \ 'command': 'GetDoc', \ 'syntax': &filetype \ } augroup END ``` You can also modify the opened popup with `popup_params` key. For example, you can limit the popup's maximum width and add a border to it: ```viml augroup MyYCMCustom autocmd! autocmd FileType c,cpp let b:ycm_hover = { \ 'command': 'GetDoc', \ 'syntax': &filetype \ 'popup_params': { \ 'maxwidth': 80, \ 'border': [], \ 'borderchars': ['─', '│', '─', '│', '┌', '┐', '┘', '└'], \ }, \ } augroup END ``` See `:help popup_create-arguments` for the list of available popup window options. Default: `'CursorHold'` ### The `g:ycm_filter_diagnostics` option This option controls which diagnostics will be rendered by YCM. This option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are dictionaries describing the filter. A filter is a dictionary of key-values, where the keys are the type of filter, and the value is a list of arguments to that filter. In the case of just a single item in the list, you may omit the brackets and just provide the argument directly. If any filter matches a diagnostic, it will be dropped and YCM will not render it. The following filter types are supported: - "regex": Accepts a string [regular expression][python-re]. This type matches when the regex (treated as case-insensitive) is found anywhere in the diagnostic text (`re.search`, not `re.match`) - "level": Accepts a string level, either "warning" or "error." This type matches when the diagnostic has the same level, that is, specifying `level: "error"` will remove **all** errors from the diagnostics. **NOTE:** The regex syntax is **NOT** Vim's, it's [Python's][python-re]. Default: `{}` The following example will do, for Java filetype only: - Remove **all** error level diagnostics, and, - Also remove anything that contains `taco` ```viml let g:ycm_filter_diagnostics = { \ "java": { \ "regex": [ "ta.+co", ... ], \ "level": "error", \ ... \ } \ } ``` ### 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. Note: if YCM's errors aren't visible, it might be that YCM is updating an older location list. See `:help :lhistory` and `:lolder`. Default: `0` ```viml let g:ycm_always_populate_location_list = 0 ``` ### The `g:ycm_open_loclist_on_ycm_diags` option When this option is set, `:YcmDiags` will automatically open the location list after forcing a compilation and filling the list with diagnostic data. See `:help location-list` in Vim to learn more about the location list. Default: `1` ```viml let g:ycm_open_loclist_on_ycm_diags = 1 ``` ### The `g:ycm_complete_in_comments` option When this option is set to `1`, YCM will show the completion menu even when typing inside comments. Default: `0` ```viml let g:ycm_complete_in_comments = 0 ``` ### The `g:ycm_complete_in_strings` option When this option is set to `1`, YCM will show the completion menu even when typing inside strings. Note that this is turned on by default so that you can use the filename completion inside strings. This is very useful for instance in C-family files where typing `#include "` will trigger the start of filename completion. If you turn off this option, you will turn off filename completion in such situations as well. Default: `1` ```viml let g:ycm_complete_in_strings = 1 ``` ### The `g:ycm_collect_identifiers_from_comments_and_strings` option When this option is set to `1`, YCM's identifier completer will also collect identifiers from strings and comments. Otherwise, the text in comments and strings will be ignored. Default: `0` ```viml let g:ycm_collect_identifiers_from_comments_and_strings = 0 ``` ### The `g:ycm_collect_identifiers_from_tags_files` option When this option is set to `1`, YCM's identifier completer will also collect identifiers from tags files. The list of tags files to examine is retrieved from the `tagfiles()` Vim function which examines the `tags` Vim option. See `:h 'tags'` for details. YCM will re-index your tags files if it detects that they have been modified. The only supported tag format is the [Exuberant Ctags format][ctags-format]. The format from "plain" ctags is NOT supported. Ctags needs to be called with the `--fields=+l` option (that's a lowercase `L`, not a one) because YCM needs the `language:` field in the tags output. See the _FAQ_ for pointers if YCM does not appear to read your tag files. This option is off by default because it makes Vim slower if your tags are on a network directory. Default: `0` ```viml let g:ycm_collect_identifiers_from_tags_files = 0 ``` ### The `g:ycm_seed_identifiers_with_syntax` option When this option is set to `1`, YCM's identifier completer will seed its identifier database with the keywords of the programming language you're writing. Since the keywords are extracted from the Vim syntax file for the filetype, all keywords may not be collected, depending on how the syntax file was written. Usually at least 95% of the keywords are successfully extracted. Default: `0` ```viml let g:ycm_seed_identifiers_with_syntax = 0 ``` ### The `g:ycm_extra_conf_vim_data` option If you're using semantic completion for C-family files, this option might come handy; it's a way of sending data from Vim to your `Settings` function in your `.ycm_extra_conf.py` file. This option is supposed to be a list of VimScript expression strings that are evaluated for every request to the [ycmd server][ycmd] and then passed to your `Settings` function as a `client_data` keyword argument. For instance, if you set this option to `['v:version']`, your `Settings` function will be called like this: ```python # The '801' value is of course contingent on Vim 8.1; in 8.0 it would be '800' Settings( ..., client_data = { 'v:version': 801 } ) ``` 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 `Settings` function: ```python def Settings( **kwargs ): ``` You can then get to `client_data` with `kwargs['client_data']`. Default: `[]` ```viml let g:ycm_extra_conf_vim_data = [] ``` ### The `g:ycm_server_python_interpreter` option YCM will by default search for an appropriate Python interpreter on your system. You can use this option to override that behavior and force the use of a specific interpreter of your choosing. **NOTE:** This interpreter is only used for the [ycmd server][ycmd]. The YCM client running inside Vim always uses the Python interpreter that's embedded inside Vim. Default: `''` ```viml let g:ycm_server_python_interpreter = '' ``` ### The `g:ycm_keep_logfiles` option When this option is set to `1`, YCM and the [ycmd completion server][ycmd] will keep the logfiles around after shutting down (they are deleted on shutdown by default). To see where the log files are, call `:YcmDebugInfo`. Default: `0` ```viml let g:ycm_keep_logfiles = 0 ``` ### The `g:ycm_log_level` option The logging level that YCM and the [ycmd completion server][ycmd] use. Valid values are the following, from most verbose to least verbose: - `debug` - `info` - `warning` - `error` - `critical` Note that `debug` is _very_ verbose. Default: `info` ```viml let g:ycm_log_level = 'info' ``` ### The `g:ycm_auto_start_csharp_server` option When set to `1`, the OmniSharp-Roslyn server will be automatically started (once per Vim session) when you open a C# file. Default: `1` ```viml let g:ycm_auto_start_csharp_server = 1 ``` ### The `g:ycm_auto_stop_csharp_server` option When set to `1`, the OmniSharp-Roslyn server will be automatically stopped upon closing Vim. Default: `1` ```viml let g:ycm_auto_stop_csharp_server = 1 ``` ### The `g:ycm_csharp_server_port` option When g:ycm_auto_start_csharp_server is set to `1`, specifies the port for the OmniSharp-Roslyn server to listen on. When set to `0` uses an unused port provided by the OS. Default: `0` ```viml let g:ycm_csharp_server_port = 0 ``` ### The `g:ycm_csharp_insert_namespace_expr` option By default, when YCM inserts a namespace, it will insert the `using` statement under the nearest `using` statement. You may prefer that the `using` statement is inserted somewhere, for example, to preserve sorting. If so, you can set this option to override this behavior. When this option is set, instead of inserting the `using` statement itself, YCM will set the global variable `g:ycm_namespace_to_insert` to the namespace to insert, and then evaluate this option's value as an expression. The option's expression is responsible for inserting the namespace - the default insertion will not occur. Default: '' ```viml let g:ycm_csharp_insert_namespace_expr = '' ``` ### The `g:ycm_add_preview_to_completeopt` option When this option is set to `1`, YCM will add the `preview` string to Vim's `completeopt` option (see `:h completeopt`). If your `completeopt` option already has `preview` set, there will be no effect. Alternatively, when set to `popup` and your version of Vim supports popup windows (see `:help popup`), the `popup` string will be used instead. 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. When `popup` is present in `completeopt`, YCM will instead use a `popup` window to the side of the completion popup for storing detailed information about the current completion candidate. In addition, YCM may truncate the detailed completion information in order to give the popup sufficient room to display that detailed information. Default: `0` ```viml let g:ycm_add_preview_to_completeopt = 0 ``` ### The `g:ycm_autoclose_preview_window_after_completion` option When this option is set to `1`, YCM will auto-close the `preview` window after the user accepts the offered completion string. If there is no `preview` window triggered because there is no `preview` string in `completeopt`, this option is irrelevant. See the `g:ycm_add_preview_to_completeopt` option for more details. Default: `0` ```viml let g:ycm_autoclose_preview_window_after_completion = 0 ``` ### The `g:ycm_autoclose_preview_window_after_insertion` option When this option is set to `1`, YCM will auto-close the `preview` window after the user leaves insert mode. This option is irrelevant if `g:ycm_autoclose_preview_window_after_completion` is set or if no `preview` window is triggered. See the `g:ycm_add_preview_to_completeopt` option for more details. Default: `0` ```viml let g:ycm_autoclose_preview_window_after_insertion = 0 ``` ### The `g:ycm_max_diagnostics_to_display` option This option controls the maximum number of diagnostics shown to the user when errors or warnings are detected in the file. This option is only relevant for the C-family, C#, Java, JavaScript, and TypeScript languages. A special value of `0` means there is no limit. Default: `30` ```viml let g:ycm_max_diagnostics_to_display = 30 ``` ### The `g:ycm_key_list_select_completion` option This option controls the key mappings used to select the first completion string. Invoking any of them repeatedly cycles forward through the completion list. Some users like adding `` to this list. Default: `['', '']` ```viml 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 backward 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: `['', '']` ```viml let g:ycm_key_list_previous_completion = ['', ''] ``` ### The `g:ycm_key_list_stop_completion` option This option controls the key mappings used to close the completion menu. This is useful when the menu is blocking the view, when you need to insert the `` character, or when you want to expand a snippet from [UltiSnips][] and navigate through it. Default: `['']` ```viml let g:ycm_key_list_stop_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 triggered automatically after typing characters appropriate for the language, such as `.`, `->`, `::`, etc. 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 the 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: `` ```viml 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. If you prefer the detailed diagnostic to be shown in a popup, then `let g:ycm_show_detailed_diag_in_popup=1`. Default: `d` ```viml let g:ycm_key_detailed_diagnostics = 'd' ``` ### The `g:ycm_show_detailed_diag_in_popup` option Makes `:YcmShowDetailedDiagnostic` always show in a popup rather than echoing to the command line. Default: 0 ```viml let g:ycm_show_detailed_diag_in_popup = 0 ``` ### The `g:ycm_global_ycm_extra_conf` option Normally, YCM searches for a `.ycm_extra_conf.py` file for compilation flags (see the User Guide for more details on how this works). This option specifies a fallback path to a config file which is used if no `.ycm_extra_conf.py` is found. You can place such a global file anywhere in your filesystem. Default: `''` ```viml let g:ycm_global_ycm_extra_conf = '' ``` ### The `g:ycm_confirm_extra_conf` option When this option is set to `1` YCM will ask once per `.ycm_extra_conf.py` file if it is safe to be loaded. This is to prevent the execution of malicious code from a `.ycm_extra_conf.py` file you didn't write. To selectively get YCM to ask/not ask about loading certain `.ycm_extra_conf.py` files, see the `g:ycm_extra_conf_globlist` option. Default: `1` ```viml let g:ycm_confirm_extra_conf = 1 ``` ### The `g:ycm_extra_conf_globlist` option This option is a list that may contain several globbing patterns. If a pattern starts with a `!` all `.ycm_extra_conf.py` files matching that pattern will be blacklisted, that is they won't be loaded and no confirmation dialog will be shown. If a pattern does not start with a `!` all files matching that pattern will be whitelisted. Note that this option is not used when confirmation is disabled using `g:ycm_confirm_extra_conf` and that items earlier in the list will take precedence over the later ones. Rules: * `*` matches everything * `?` matches any single character * `[seq]` matches any character in seq * `[!seq]` matches any char not in seq Example: ```viml let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*'] ``` * The first rule will match everything contained in the `~/dev` directory so `.ycm_extra_conf.py` files from there will be loaded. * The second rule will match everything in the home directory so a `.ycm_extra_conf.py` file from there won't be loaded. * As the first rule takes precedence everything in the home directory excluding the `~/dev` directory will be blacklisted. **NOTE:** The glob pattern is first expanded with Python's `os.path.expanduser()` and then resolved with `os.path.abspath()` before being matched against the filename. Default: `[]` ```viml let g:ycm_extra_conf_globlist = [] ``` ### The `g:ycm_filepath_completion_use_working_dir` option By default, YCM's filepath completion will interpret relative paths like `../` as being relative to the folder of the file of the currently active buffer. Setting this option will force YCM to always interpret relative paths as being relative to Vim's current working directory. Default: `0` ```viml let g:ycm_filepath_completion_use_working_dir = 0 ``` ### The `g:ycm_semantic_triggers` option This option controls the character-based triggers for the various semantic completion engines. The option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are lists of strings, where the strings are the triggers. Setting key-value pairs on the dictionary _adds_ semantic triggers to the internal default set (listed below). You cannot remove the default triggers, only add new ones. A "trigger" is a sequence of one or more characters that trigger semantic completion when typed. For instance, C++ (`cpp` filetype) has `.` listed as a trigger. So when the user types `foo.`, the semantic engine will trigger and serve `foo`'s list of member functions and variables. Since C++ also has `->` listed as a trigger, the same thing would happen when the user typed `foo->`. It's also possible to use a regular expression as a trigger. You have to prefix your trigger with `re!` to signify it's a regex trigger. For instance, `re!\w+\.` would only trigger after the `\w+\.` regex matches. **NOTE:** The regex syntax is **NOT** Vim's, it's [Python's][python-re]. Default: `[see next line]` ```viml let g:ycm_semantic_triggers = { \ 'c': ['->', '.'], \ 'objc': ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s', \ 're!\[.*\]\s'], \ 'ocaml': ['.', '#'], \ 'cpp,cuda,objcpp': ['->', '.', '::'], \ 'perl': ['->'], \ 'php': ['->', '::'], \ 'cs,d,elixir,go,groovy,java,javascript,julia,perl6,python,scala,typescript,vb': ['.'], \ 'ruby,rust': ['.', '::'], \ 'lua': ['.', ':'], \ 'erlang': [':'], \ } ``` ### The `g:ycm_cache_omnifunc` option Some omnicompletion engines do not work well with the YCM cache—in particular, they might not produce all possible results for a given prefix. By unsetting this option you can ensure that the omnicompletion engine is re-queried on every keypress. That will ensure all completions will be presented but might cause stuttering and lag if the omnifunc is slow. Default: `1` ```viml let g:ycm_cache_omnifunc = 1 ``` ### The `g:ycm_use_ultisnips_completer` option By default, YCM will query the UltiSnips plugin for possible completions of snippet triggers. This option can turn that behavior off. Default: `1` ```viml let g:ycm_use_ultisnips_completer = 1 ``` ### The `g:ycm_goto_buffer_command` option Defines where `GoTo*` commands result should be opened. Can take one of the following values: `'same-buffer'`, `'split'`, or `'split-or-existing-window'`. If this option is set to the `'same-buffer'` but current buffer can not be switched (when buffer is modified and `nohidden` option is set), then result will be opened in a split. When the option is set to `'split-or-existing-window'`, if the result is already open in a window of the current tab page (or any tab pages with the `:tab` modifier; see below), it will jump to that window. Otherwise, the result will be opened in a split as if the option was set to `'split'`. To customize the way a new window is split, prefix the `GoTo*` command with one of the following modifiers: `:aboveleft`, `:belowright`, `:botright`, `:leftabove`, `:rightbelow`, `:topleft`, and `:vertical`. For instance, to split vertically to the right of the current window, run the command: ```viml :rightbelow vertical YcmCompleter GoTo ``` To open in a new tab page, use the `:tab` modifier with the `'split'` or `'split-or-existing-window'` options e.g.: ```viml :tab YcmCompleter GoTo ``` Default: `'same-buffer'` ```viml let g:ycm_goto_buffer_command = 'same-buffer' ``` ### The `g:ycm_disable_for_files_larger_than_kb` option Defines the max size (in Kb) for a file to be considered for completion. If this option is set to 0 then no check is made on the size of the file you're opening. Default: 1000 ```viml let g:ycm_disable_for_files_larger_than_kb = 1000 ``` ### The `g:ycm_use_clangd` option This option controls whether **clangd** should be used as a completion engine for C-family languages. Can take one of the following values: `1`, `0`, with meanings: - `1`: YCM will use clangd if clangd binary exists in third party or it was provided with `ycm_clangd_binary_path` option. - `0`: YCM will never use clangd completer. Default: `1` ```viml let g:ycm_use_clangd = 1 ``` ### The `g:ycm_clangd_binary_path` option When `ycm_use_clangd` option is set to `1`, this option sets the path to **clangd** binary. Default: `''` ```viml let g:ycm_clangd_binary_path = '' ``` ### The `g:ycm_clangd_args` option This option controls the command line arguments passed to the clangd binary. It appends new options and overrides the existing ones. Default: `[]` ```viml let g:ycm_clangd_args = [] ``` ### The `g:ycm_clangd_uses_ycmd_caching` option This option controls which ranking and filtering algorithm to use for completion items. It can take values: - `1`: Uses ycmd's caching and filtering logic. - `0`: Uses clangd's caching and filtering logic. Default: `1` ```viml let g:ycm_clangd_uses_ycmd_caching = 1 ``` ### The `g:ycm_language_server` option This option lets YCM use an arbitrary Language Server Protocol (LSP) server, not unlike many other completion systems. The officially supported completers are favoured over custom LSP ones, so overriding an existing completer means first making sure YCM won't choose that existing completer in the first place. A simple working example of this option can be found in the section called ["Semantic Completion for Other Languages"](#semantic-completion-for-other-languages). Many working examples can be found in the YCM [lsp-examples][] repository. Default: `[]` ```viml let g:ycm_language_server = [] ``` ### The `g:ycm_disable_signature_help` option This option allows you to disable all signature help for all completion engines. There is no way to disable it per-completer. Default: `0` ```viml " Disable signature help let g:ycm_disable_signature_help = 1 ``` ### The `g:ycm_signature_help_disable_syntax` option Set this to 1 to disable syntax highlighting in the signature help popup. Thiis can help if your colourscheme doesn't work well with the default highliting and inverse video. Default: `0` ```viml " Disable signature help syntax highliting let g:ycm_signature_help_disable_syntax = 1 ``` ### The `g:ycm_gopls_binary_path` option In case the system-wide `gopls` binary is newer than the bundled one, setting this option to the path of the system-wide `gopls` would make YCM use that one instead. If the path is just `gopls`, YCM will search in `$PATH`. ### The `g:ycm_gopls_args` option Similar to [the `g:ycm_clangd_args`](#the-gycm-clangd-args), this option allows passing additional flags to the `gopls` command line. Default: `[]` ```viml let g:ycm_gopls_args = [] ``` ### The `g:ycm_rls_binary_path` and `g:ycm_rustc_binary_path` options YCM no longer uses RLS for rust, and these options are therefore no longer supported. To use a custom rust-analyzer, see `g:ycm_rust_toolchain_root`. ### The `g:ycm_rust_toolchain_root` option Optionally specify the path to a custom rust toolchain including at least a supported version of `rust-analyzer`. ### The `g:ycm_tsserver_binary_path` option Similar to [the `gopls` path](#the-gycm-gopls-binaty-path), this option tells YCM where is the TSServer executable located. ### The `g:ycm_roslyn_binary_path` option Similar to [the `gopls` path](#the-gycm-gopls-binaty-path), this option tells YCM where is the Omnisharp-Roslyn executable located. ### The `g:ycm_update_diagnostics_in_insert_mode` option With async diagnostics, LSP servers might send new diagnostics mid-typing. If seeing these new diagnostics while typing is not desired, this option can be set to 0. When this option is set to `0`, diagnostic signs, virtual text, and highlights are cleared when entering insert mode and replaced when leaving insert mode. This reduces visual noise while editing. In addition, this option is recommended when `g:ycm_echo_current_diagnostic` is set to `virtual-text` as it prevents updating the virtual text while you are typing. Default: `1` ```viml let g:ycm_update_diagnostics_in_insert_mode = 1 ``` FAQ --- The FAQ section has been moved to the [wiki][wiki-faq]. Contributor Code of Conduct --------------------------- Please note that this project is released with a [Contributor Code of Conduct][ccoc]. By participating in this project you agree to abide by its terms. Contact ------- If you have questions about the plugin or need help, please join the [Gitter room][gitter] or use the [ycm-users][] mailing list. If you have bug reports or feature suggestions, please use the [issue tracker][tracker]. Before you do, please carefully read [CONTRIBUTING.md][contributing-md] as this asks for important diagnostics which the team will use to help get you going. The latest version of the plugin is available at . The author's homepage is . Please do **NOT** go to #vim, Reddit, or Stack Overflow for support. Please contact the YouCompleteMe maintainers directly using the [contact details](#contact). License ------- This software is licensed under the [GPL v3 license][gpl]. © 2015-2018 YouCompleteMe contributors Sponsorship ----------- If you like YCM so much that you're willing to part with your hard-earned cash, please consider donating to one of the following charities, which are meaningful to the current maintainers (in no particular order): * [Hector's Greyhound Rescue](https://www.hectorsgreyhoundrescue.org) * [Be Humane](https://www.budihuman.rs/en) * [Cancer Research UK](https://www.cancerresearchuk.org) * [ICCF Holland](https://iccf.nl) * Any charity of your choosing. Please note: The YCM maintainers do not specifically endorse nor necessarily have any relationship with the above charities. Disclosure: It is noted that one key maintainer is a family with Trustees of Greyhound Rescue Wales. [ycmd]: https://github.com/ycm-core/ycmd [Clang]: https://clang.llvm.org/ [vundle]: https://github.com/VundleVim/Vundle.vim#about [brew]: https://brew.sh [cmake-download]: https://cmake.org/download/ [macvim]: https://macvim-dev.github.io/macvim/ [vimrc]: https://vimhelp.appspot.com/starting.txt.html#vimrc [gpl]: https://www.gnu.org/copyleft/gpl.html [vim]: https://www.vim.org/ [syntastic]: https://github.com/scrooloose/syntastic [lightline]: https://github.com/itchyny/lightline.vim [ycm_flags_example]: https://github.com/ycm-core/YouCompleteMe/blob/master/.ycm_extra_conf.py [ycmd_flags_example]: https://raw.githubusercontent.com/ycm-core/ycmd/66030cd94299114ae316796f3cad181cac8a007c/.ycm_extra_conf.py [compdb]: https://clang.llvm.org/docs/JSONCompilationDatabase.html [subsequence]: https://en.wikipedia.org/wiki/Subsequence [listtoggle]: https://github.com/Valloric/ListToggle [vim-build]: https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source [tracker]: https://github.com/ycm-core/YouCompleteMe/issues?state=open [completer-api]: https://github.com/ycm-core/ycmd/blob/master/ycmd/completers/completer.py [eclim]: http://eclim.org/ [jedi]: https://github.com/davidhalter/jedi [ultisnips]: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt [ctags-format]: http://ctags.sourceforge.net/FORMAT [ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users [omnisharp-roslyn]: https://github.com/OmniSharp/omnisharp-roslyn [python-re]: https://docs.python.org/2/library/re.html#regular-expression-syntax [Bear]: https://github.com/rizsotto/Bear [ygen]: https://github.com/rdnetto/YCM-Generator [Gopls]: https://github.com/golang/go/wiki/gopls [gopls-preferences]: https://github.com/golang/tools/blob/master/internal/lsp/server.go [TSServer]: https://github.com/Microsoft/TypeScript/tree/master/src/server [jsconfig.json]: https://code.visualstudio.com/docs/languages/jsconfig [tsconfig.json]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html [vim-win-download]: https://github.com/vim/vim-win32-installer/releases [python-win-download]: https://www.python.org/downloads/windows/ [visual-studio-download]: https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16 [mono-install-macos]: https://www.mono-project.com/download/stable/ [mono-install-linux]: https://www.mono-project.com/download/stable/#download-lin [go-install]: https://golang.org/doc/install [npm-install]: https://docs.npmjs.com/getting-started/installing-node#1-install-nodejs--npm [tern-instructions]: https://github.com/ycm-core/YouCompleteMe/wiki/JavaScript-Semantic-Completion-through-Tern [libclang-instructions]: https://github.com/ycm-core/YouCompleteMe/wiki/C-family-Semantic-Completion-through-libclang [Tern]: https://ternjs.net [rls]: https://github.com/rust-lang/rls [rust-analyzer]: https://rust-analyzer.github.io [rust-src]: https://www.rust-lang.org/downloads.html [add-msbuild-to-path]: https://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1 [ccoc]: https://github.com/ycm-core/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md [gitter]: https://gitter.im/Valloric/YouCompleteMe [ninja-compdb]: https://ninja-build.org/manual.html [++enc]: http://vimdoc.sourceforge.net/htmldoc/editing.html#++enc [contributing-md]: https://github.com/ycm-core/YouCompleteMe/blob/master/CONTRIBUTING.md [jdt.ls]: https://github.com/eclipse/eclipse.jdt.ls [jdk-install]: https://adoptium.net/en-GB/temurin/releases [mvn-project]: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html [eclipse-project]: https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html [gradle-project]: https://docs.gradle.org/current/userguide/tutorial_java_projects.html [eclipse-dot-project]: https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html [eclipse-dot-classpath]: https://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIClasspathEntry.html [ycmd-eclipse-project]: https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_eclipse_project [ycmd-mvn-pom-xml]: https://github.com/ycm-core/ycmd/blob/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_maven_project/pom.xml [ycmd-gradle-project]: https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_gradle_project [jdtls-preferences]: https://github.com/eclipse/eclipse.jdt.ls/blob/master/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/preferences/Preferences.java [diacritic]: https://www.unicode.org/glossary/#diacritic [clangd]: https://clang.llvm.org/extra/clangd.html [vimspector]: https://github.com/puremourning/vimspector [compiledb]: https://pypi.org/project/compiledb/ [signature-help-pr]: https://github.com/ycm-core/ycmd/pull/1255 [wiki-faq]: https://github.com/ycm-core/YouCompleteMe/wiki/FAQ [wiki-full-install]: https://github.com/ycm-core/YouCompleteMe/wiki/Full-Installation-Guide [wiki-troubleshooting]: https://github.com/ycm-core/YouCompleteMe/wiki/Troubleshooting-steps-for-ycmd-server-SHUT-DOWN [lsp-examples]: https://github.com/ycm-core/lsp-examples [language_server-configuration]: https://github.com/ycm-core/ycmd#language_server-configuration [diagnostic-echo-virtual-text1]: https://user-images.githubusercontent.com/10584846/185707973-39703699-0263-47d3-82ac-639d52259bea.png [diagnostic-echo-virtual-text2]: https://user-images.githubusercontent.com/10584846/185707993-14ff5fd7-c082-4e5a-b825-f1364e619b6a.png [jedi-refactor-doc]: https://jedi.readthedocs.io/en/latest/docs/api.html#jedi.Script.extract_variable ================================================ FILE: autoload/youcompleteme/filetypes.vim ================================================ " Copyright (C) 2011-2018 YouCompleteMe contributors " " This file is part of YouCompleteMe. " " YouCompleteMe is free software: you can redistribute it and/or modify " it under the terms of the GNU General Public License as published by " the Free Software Foundation, either version 3 of the License, or " (at your option) any later version. " " YouCompleteMe is distributed in the hope that it will be useful, " but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " GNU General Public License for more details. " " You should have received a copy of the GNU General Public License " along with YouCompleteMe. If not, see . function! s:HasAnyKey( dict, keys ) abort for key in a:keys if has_key( a:dict, key ) return 1 endif endfor return 0 endfunction function! youcompleteme#filetypes#AllowedForFiletype( filetype ) abort let whitelist_allows = type( g:ycm_filetype_whitelist ) != v:t_dict || \ has_key( g:ycm_filetype_whitelist, '*' ) || \ s:HasAnyKey( g:ycm_filetype_whitelist, split( a:filetype, '\.' ) ) let blacklist_allows = type( g:ycm_filetype_blacklist ) != v:t_dict || \ !s:HasAnyKey( g:ycm_filetype_blacklist, split( a:filetype, '\.' ) ) return whitelist_allows && blacklist_allows endfunction ================================================ FILE: autoload/youcompleteme/finder.vim ================================================ " Copyright (C) 2021 YouCompleteMe contributors " " This file is part of YouCompleteMe. " " YouCompleteMe is free software: you can redistribute it and/or modify " it under the terms of the GNU General Public License as published by " the Free Software Foundation, either version 3 of the License, or " (at your option) any later version. " " YouCompleteMe is distributed in the hope that it will be useful, " but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " GNU General Public License for more details. " " You should have received a copy of the GNU General Public License " along with YouCompleteMe. If not, see . " This is basic vim plugin boilerplate let s:save_cpo = &cpoptions set cpoptions&vim scriptencoding utf-8 " " Explanation for how this module works: " " The entry point is youcompleteme#finder#FindSymbol, which takes a scope " argument: " " * 'document' scope - search document symbols - GoToDocumentOutline " * 'workspace' scope - search workspace symbols - GoToSymbol " " In general, the approach is: " - create a prompt buffer, and display it to use for input of a query " - open up a popup to display the results in the middle of the screen " - as the query changes, re-query the server to get the newly filtered results " - as the server returns results, update the contents of the results-popup " - use a popup-filter to implement some interractivity with the results, such " as down/up, and select item " - when an item is selected, open its buffer in the window that was current " when the search started and jump to the selected item. " - then populate the quickfix list with any matching results and close the " popup and prompt buffer. " " However, there is an important wrinke/distinction that leads to the code being " a little more complicated than that: the 'search' mechanism for workspace and " document symbols is different. " " The reaosn for this differece is what the servers provide in response to the 2 " requests: " " * 'document' scope - we use ycmd's filtering and sorting. " GoToDocumentOutline (LSP documentSymbol) request does not take any filter " argument. It returns all symbols in the current document. Therefore, we use " ycmd's filter_and_sort_candidates endpoint to use our own fuzzy search on " the results. This is a _great_ experience, it's _super_ fast and familar to " YCM users. " * 'workspace' scope - we have to rely on the downstream server's filtering and " sorting. " GoToSymbol (LSP workspaceSymbol) request takes a query parameter to search " with. While the LSP spec states that an empty query means 'return " everything', no servers actually implement that, so we have to pass our " query down to the server. " " The result of this is that while a lot of the code is shared, there are " slightly different steps involved in the process: " " * for 'document' requests, as soon as the popup is opened, we issue a " GoToDocumentOutline request, storing the results as `raw_results`, then " then immediately start filtering it with filter_and_sort_candidates, storing " the filtered results in `results` " * for 'workspace' requests, as soon as the popup is opened, we issue a " GoToSymbol request with an empty query. This usually returns nothing, but if " any servers return anything then it would be stored in 'results'. As the " user types, we repeat the GoToSymbol request and update the 'results' " " In order to simplify the re-query code, we put the function used to filter " results in the state variable as 'query_func'. " " As the expereince of completely different filtering and sorting for workspace " vs document is so jarring, by default we actually pass all restuls from " 'workspace' search through filter_and_sort_candidates too. This isn't perfect " because it breaks the mental model when the server's filtering is dumb, but it " at least means that sorting is consistent. This can be disabled by setting " g:ycm_refilter_workspace_symbols to 0. " " The key functions are: " " - FindSymbol - initiate the request - open the popup/prompt buffer, set up " the state object to defaults and initiate the first request " (RequestDocumentSymbols for 'documnt' and SearchWorkspace for 'workspace' ) " " - RequestDocumentSymbols - perform the GoToDocumentOutline request and store " the results in 'raw_results' " " - SearchDocument - perform filter_and_sort_candidates request on the " 'raw_results', and store the results in 'results', then call " "HandleSymbolSearchResults" " " - SearchWorkspace - perform GoToSymbol request for all open filetypes, " and store the results in 'raw_results' as a dict mapping " filetype->results. Merge the results in to 'results', then call " "HandleSymbolSearchResults" " " - HandleSymbolSearchResults - redraw the popup with the 'results' " " - HandleKeyPress - handle a keypress while the popup is visible, intercepts " things to handle interractivity " " - PopupClosed - callback when the popup is closed. This openes the result in " the original window. " " The other functions are utility for the most part and handle things like " TextChangedI event, starting/stopping drawing the spinner and such. let s:icon_spinner = [ '/', '-', '\', '|', '/', '-', '\', '|' ] let s:icon_done = 'X' let s:spinner_delay = 100 let s:prompt = 'Find Symbol: ' let s:find_symbol_status = {} " Entry point {{{ function! youcompleteme#finder#FindSymbol( scope ) abort if !py3eval( 'vimsupport.VimSupportsPopupWindows()' ) echo 'Sorry, this feature is not supported in your editor' return endif call youcompleteme#symbol#InitSymbolProperties() let s:find_symbol_status = { \ 'selected': -1, \ 'query': '', \ 'results': [], \ 'raw_results': v:none, \ 'all_filetypes': v:true, \ 'pending': [], \ 'winid': win_getid(), \ 'bufnr': bufnr(), \ 'prompt_bufnr': -1, \ 'prompt_winid': -1, \ 'filter': v:none, \ 'id': v:none, \ 'cursorline_match': v:none, \ 'spinner': 0, \ 'spinner_timer': -1, \ } let opts = { \ 'padding': [ 1, 2, 1, 2 ], \ 'wrap': 0, \ 'minwidth': &columns / 3 * 2, \ 'minheight': &lines / 3 * 2, \ 'maxwidth': &columns / 3 * 2, \ 'maxheight': &lines / 3 * 2, \ 'line': &lines / 6, \ 'col': &columns / 6, \ 'pos': 'topleft', \ 'drag': 1, \ 'resize': 1, \ 'close': 'button', \ 'border': [], \ 'callback': function( 's:PopupClosed' ), \ 'filter': function( 's:HandleKeyPress' ), \ 'highlight': 'Normal', \ } if &ambiwidth ==# 'single' && &encoding ==? 'utf-8' let opts[ 'borderchars' ] = [ '─', '│', '─', '│', '╭', '╮', '┛', '╰' ] endif if a:scope ==# 'document' let s:find_symbol_status.query_func = function( 's:SearchDocument' ) else let s:find_symbol_status.query_func = function( 's:SearchWorkspace' ) endif let s:find_symbol_status.id = popup_create( 'Type to query for stuff', opts ) " Kick off the request now if a:scope ==# 'document' call s:RequestDocumentSymbols() else call s:SearchWorkspace( '', v:true ) endif let bufnr = bufadd( '_ycm_filter_' ) silent call bufload( bufnr ) silent topleft 1split _ycm_filter_ " Disable ycm/completion in this buffer call setbufvar( bufnr, 'ycm_largefile', 1 ) let s:find_symbol_status.prompt_bufnr = bufnr let s:find_symbol_status.prompt_winid = win_getid() setlocal buftype=prompt noswapfile modifiable nomodified noreadonly setlocal nobuflisted bufhidden=delete textwidth=0 call prompt_setprompt( bufnr(), s:prompt ) augroup YCMPromptFindSymbol autocmd! autocmd TextChanged,TextChangedI call s:OnQueryTextChanged() autocmd WinLeave call s:Cancel() autocmd CmdLineEnter call s:Cancel() augroup END startinsert endfunction function! s:OnQueryTextChanged() abort if s:find_symbol_status.id < 0 return endif let bufnr = s:find_symbol_status.prompt_bufnr let query = getbufline( bufnr, '$' )[ 0 ] let s:find_symbol_status.query = query[ len( s:prompt ) : ] " really, re-query if we can call s:RequeryFinderPopup( v:true ) call win_execute( s:find_symbol_status.prompt_winid, 'setlocal nomodified' ) endfunction function! s:Cancel() abort if s:find_symbol_status.id < 0 return endif call popup_close( s:find_symbol_status.id, -1 ) endfunction " }}} " Popup and keyboard events {{{ function! s:HandleKeyPress( id, key ) abort let redraw = 0 let handled = 0 let requery = 0 " The input for the search/query is taken from the prompt buffer and the " TextChangedI event if a:key ==# "\" || \ a:key ==# "\" || \ a:key ==# "\" || \ a:key ==# "\" let s:find_symbol_status.selected += 1 " wrap if s:find_symbol_status.selected >= len( s:find_symbol_status.results ) let s:find_symbol_status.selected = 0 endif let redraw = 1 let handled = 1 elseif a:key ==# "\" || \ a:key ==# "\" || \ a:key ==# "\" || \ a:key ==# "\" let s:find_symbol_status.selected -= 1 " wrap if s:find_symbol_status.selected < 0 let s:find_symbol_status.selected = \ len( s:find_symbol_status.results ) - 1 endif let redraw = 1 let handled = 1 elseif a:key ==# "\" || a:key ==# "\" let s:find_symbol_status.selected += \ popup_getpos( s:find_symbol_status.id ).core_height " Don't wrap if s:find_symbol_status.selected >= len( s:find_symbol_status.results ) let s:find_symbol_status.selected = \ len( s:find_symbol_status.results ) - 1 endif let redraw = 1 let handled = 1 elseif a:key ==# "\" || a:key ==# "\" let s:find_symbol_status.selected -= \ popup_getpos( s:find_symbol_status.id ).core_height " Don't wrap if s:find_symbol_status.selected < 0 let s:find_symbol_status.selected = 0 endif let redraw = 1 let handled = 1 elseif a:key ==# "\" call popup_close( a:id, -1 ) let handled = 1 elseif a:key ==# "\" if s:find_symbol_status.selected >= 0 call popup_close( a:id, s:find_symbol_status.selected ) let handled = 1 endif elseif a:key ==# "\" || a:key ==# "\" let s:find_symbol_status.selected = 0 let redraw = 1 let handled = 1 elseif a:key ==# "\" || a:key ==# "\" let s:find_symbol_status.selected = len( s:find_symbol_status.results ) - 1 let redraw = 1 let handled = 1 elseif a:key ==# "\" " TOggle filetypes? let s:find_symbol_status.all_filetypes = !s:find_symbol_status.all_filetypes let redraw = 0 let requery = 1 let handled = 1 endif if requery call s:RequeryFinderPopup( v:true ) elseif redraw call s:RedrawFinderPopup() endif return handled endfunction " Handle the popup closing: jump to the selected item function! s:PopupClosed( id, selected ) abort stopinsert call win_gotoid( s:find_symbol_status.prompt_winid ) silent bwipe! " Return to original window call win_gotoid( s:find_symbol_status.winid ) if a:selected >= 0 let selected = s:find_symbol_status.results[ a:selected ] py3 vimsupport.JumpToLocation( \ filename = vimsupport.ToUnicode( vim.eval( 'selected.filepath' ) ), \ line = int( vim.eval( 'selected.line_num' ) ), \ column = int( vim.eval( 'selected.column_num' ) ), \ modifiers = '', \ command = 'same-buffer' \ ) if len( s:find_symbol_status.results ) > 1 " Also, populate the quickfix list py3 vimsupport.SetQuickFixList( \ [ vimsupport.BuildQfListItem( x ) for x in \ vim.eval( 's:find_symbol_status.results' ) ] ) " Emulate :echo, to avoid a redraw getting rid of the message. let txt = 'Added ' . len( getqflist() ) . ' entries to quickfix list.' call popup_notification( \ txt, \ { \ 'line': 1, \ 'col': &columns - len( txt ), \ 'padding': [ 0, 0, 0, 0 ], \ 'border': [ 0, 0, 0, 0 ], \ 'highlight': 'PMenu' \ } ) " But don't open it, as this could take up valuable actual screen space " py3 vimsupport.OpenQuickFixList() endif endif call s:EndRequest() let s:find_symbol_status.id = -1 endfunction "}}} " Results handling and re-query {{{ " Render a set of results returned from the filter/search function function! s:HandleSymbolSearchResults( results ) abort let s:find_symbol_status.results = [] if s:find_symbol_status.id < 0 " Popup was closed, ignore this event return endif let s:find_symbol_status.results = a:results call s:RedrawFinderPopup() " Re-query but no change in the query text call s:RequeryFinderPopup( v:false ) endfunction " Set the popup text function! s:RedrawFinderPopup() abort " Clamp selected. If there are any results, the first one is selected by " default let s:find_symbol_status.selected = max( [ \ s:find_symbol_status.selected, \ len( s:find_symbol_status.results ) > 0 ? 0 : -1 \ ] ) let s:find_symbol_status.selected = min( [ \ s:find_symbol_status.selected, \ len( s:find_symbol_status.results ) - 1 \ ] ) if empty( s:find_symbol_status.results ) call popup_settext( s:find_symbol_status.id, 'No results' ) let s:find_symbol_status.selected = -1 else let popup_width = popup_getpos( s:find_symbol_status.id ).core_width let buffer = [] let len_filetype = 0 for result in s:find_symbol_status.results let len_filetype = max( [ len_filetype, len( result[ 'filetype' ] ) ] ) endfor if len_filetype > 0 let filetype_sep = ' ' else let filetype_sep = '' endif let available_width = popup_width - len_filetype - len( filetype_sep ) for result in s:find_symbol_status.results " Calculate the text to use. Try and include the full path and line " number, (right aligned), but truncate if there isn't space for the " description and the file path. Include at least 8 spaces between them " (if there's room). if result->has_key( 'extra_data' ) let kind = result[ 'extra_data' ][ 'kind' ] let name = result[ 'extra_data' ][ 'name' ] let desc = kind .. ': ' .. name let prop = youcompleteme#symbol#GetPropForSymbolKind( kind ) let props = [ \ { 'col': 1, \ 'length': len( kind ) + 2, \ 'type': 'YCM-symbol-Normal' }, \ { 'col': len( kind ) + 3, \ 'length': len( name ), \ 'type': prop }, \ ] elseif result->has_key( 'description' ) let desc = result[ 'description' ] let props = [ \ { 'col': 1, 'length': len( desc ), 'type': 'YCM-symbol-Normal' }, \ ] else let desc = 'Invalid entry: ' . string( result ) let props = [] endif let line_num = result[ 'line_num' ] let path = fnamemodify( result[ 'filepath' ], ':.' ) \ .. ':' \ .. line_num let path_includes_line = 1 let spaces = available_width - strdisplaywidth( desc ) - strdisplaywidth( path ) let spacing = 4 if spaces < spacing let spaces = spacing let space_for_path = available_width - spacing - len( desc ) let path_includes_line = space_for_path - 3 > len( line_num ) + 1 if space_for_path > 3 let path = '...' . strpart( path, len( path ) - space_for_path + 3 ) elseif space_for_path <= 0 let path = '' else let path_includes_line = 0 let path = '...' endif endif let line = desc \ .. repeat( ' ', spaces ) \ .. path \ .. filetype_sep \ .. result[ 'filetype' ] if len( path ) > 0 if path_includes_line let props += [ \ { 'col': len( desc ) + spaces + 1, \ 'length': len( path ) - len( line_num ), \ 'type': 'YCM-symbol-file' }, \ { 'col': len( desc ) + spaces + 1 + len( path ) - len( line_num ), \ 'length': len( line_num ), \ 'type': 'YCM-symbol-line-num' }, \ ] else let props += [ \ { 'col': len( desc ) + spaces + 1, \ 'length': len( path ), \ 'type': 'YCM-symbol-file' }, \ ] endif endif if len_filetype > 0 let props += [ \ { 'col': popup_width - len_filetype + len( filetype_sep ), \ 'length': len_filetype, \ 'type': 'YCM-symbol-filetype' }, \ ] endif call add( buffer, { 'text': line, 'props': props } ) endfor call popup_settext( s:find_symbol_status.id, buffer ) endif if s:find_symbol_status.selected > -1 " Move the cursor so that cursorline highlights the selected item. Also " scroll the window if the selected item is not in view. To make scrolling " feel natural we position the current line a the bottom of the window if " the new current line is below the current viewport, and at the top if the " new current line is above the viewport. let new_line = s:find_symbol_status.selected + 1 let pos = popup_getpos( s:find_symbol_status.id ) call win_execute( s:find_symbol_status.id, \ 'call cursor( [' . string( new_line ) . ', 1] )' ) if new_line < pos.firstline " New line is above the viewport, scroll so that this line is at the top " of the window. call win_execute( s:find_symbol_status.id, "normal z\" ) elseif new_line >= ( pos.firstline + pos.core_height ) " New line is below the viewport, scroll so that this line is at the " bottom of the window. call win_execute( s:find_symbol_status.id, ':normal z-' ) endif " Otherwise, new item is already displayed - don't scroll the window. if !getwinvar( s:find_symbol_status.id, '&cursorline' ) call win_execute( s:find_symbol_status.id, \ 'set cursorline cursorlineopt&' ) endif else call win_execute( s:find_symbol_status.id, 'set nocursorline' ) endif endfunction function! s:SetTitle() abort if s:find_symbol_status.spinner_timer > -1 let status = s:icon_spinner[ s:find_symbol_status.spinner ] else let status = s:icon_done endif call popup_setoptions( s:find_symbol_status.id, { \ 'title': ' [' . status . '] Search for symbol: ' \ . s:find_symbol_status.query . ' ' \ } ) endfunction " Re-query or re-filter by calling the filter function function! s:RequeryFinderPopup( new_query ) abort " Update the title even if we delay the query, as this makes the UI feel " snappy call s:SetTitle() call win_execute( s:find_symbol_status.winid, \ 'call s:find_symbol_status.query_func(' \ . 's:find_symbol_status.query,' \ . 'a:new_query )' ) endfunction function! s:ParseGoToResponse( filetype, results ) abort if type( a:results ) == v:t_none || empty( a:results ) let results = [] elseif type( a:results ) != v:t_list if type( a:results ) == v:t_dict && has_key( a:results, 'error' ) let results = [] else let results = [ a:results ] endif else let results = a:results endif call map( results, { _, r -> extend( r, { \ 'key': r->get( 'extra_data', {} )->get( 'name', r[ 'description' ] ), \ 'filetype': a:filetype \ } ) } ) return results endfunction " }}} " Spinner {{{ function! s:StartRequest() abort call s:EndRequest() let s:find_symbol_status.spinner = 0 let s:find_symbol_status.spinner_timer = timer_start( s:spinner_delay, \ function( 's:TickSpinner' ) ) call s:SetTitle() endfunction function! s:EndRequest() abort call timer_stop( s:find_symbol_status.spinner_timer ) let s:find_symbol_status.spinner_timer = -1 call s:SetTitle() endfunction function! s:TickSpinner( timer_id ) abort let s:find_symbol_status.spinner = ( s:find_symbol_status.spinner + 1 ) % \ len( s:icon_spinner ) let s:find_symbol_status.spinner_timer = timer_start( s:spinner_delay, \ function( 's:TickSpinner' ) ) call s:SetTitle() endfunction " }}} " Workspace search {{{ function! s:SearchWorkspace( query, new_query ) abort if a:new_query if s:find_symbol_status.raw_results is# v:none let raw_results = {} else let raw_results = copy( s:find_symbol_status.raw_results ) endif let s:find_symbol_status.raw_results = {} " FIXME: We might still get results for any pending results. There is no " cancellation mechanism implemented for the async request! let s:find_symbol_status.pending = [] if s:find_symbol_status.all_filetypes let ft_buffer_map = py3eval( 'vimsupport.AllOpenedFiletypes()' ) else let current_filetypes = py3eval( 'vimsupport.CurrentFiletypes()' ) let ft_buffer_map = {} for ft in current_filetypes let ft_buffer_map[ ft ] = [ bufnr() ] endfor endif for ft in keys( ft_buffer_map ) if !youcompleteme#filetypes#AllowedForFiletype( ft ) continue endif let s:find_symbol_status.raw_results[ ft ] = v:none if has_key( raw_results, ft ) && raw_results[ ft ] is# v:none call add( s:find_symbol_status.pending, \ [ ft, ft_buffer_map[ ft ][ 0 ] ] ) else call youcompleteme#GetRawCommandResponseAsync( \ function( 's:HandleWorkspaceSymbols', [ ft ] ), \ 'GoToSymbol', \ '--bufnr=' . ft_buffer_map[ ft ][ 0 ], \ 'ft=' . ft, \ a:query ) endif endfor if !empty( s:find_symbol_status.raw_results ) " We sent some requests call s:StartRequest() endif else " Just requery those completer filetypes that we're not currently waiting " for for [ ft, bufnr ] in copy( s:find_symbol_status.pending ) if s:find_symbol_status.raw_results[ ft ] isnot# v:none call filter( s:find_symbol_status.pending, { v -> v !=# ft } ) let s:find_symbol_status.raw_results[ ft ] = v:none call youcompleteme#GetRawCommandResponseAsync( \ function( 's:HandleWorkspaceSymbols', [ ft ] ), \ 'GoToSymbol', \ '--bufnr=' . bufnr, \ 'ft=' . ft, \ a:query ) endif endfor endif endfunction function! s:HandleWorkspaceSymbols( filetype, results ) abort let s:find_symbol_status.raw_results[ a:filetype ] = \ s:ParseGoToResponse( a:filetype, a:results ) " Collate the results from each filetype let results = [] let waiting = 0 for ft in keys( s:find_symbol_status.raw_results ) if s:find_symbol_status.raw_results[ ft ] is v:none let waiting = 1 continue endif call extend( results, s:find_symbol_status.raw_results[ ft ] ) endfor let query = s:find_symbol_status.query if g:ycm_refilter_workspace_symbols && !empty( results ) " This is kinda wonky, but seems to work well enough. " " We get the server to give us a result set, then use our own " filter_and_sort_candidates on the result set filtered by the server " " The reason for this is: " - server filterins will differ by server and this leads to horrible wonky " user experience " - ycmd filter is consistent, even if not perfect " - servers are supposed to return _all_ symbols if we request a query of " "" but not all servers actually do " " So as a compromise we let the server filter the results, then we " _refilter_ and sort them using ycmd's method. This provides consistency " with the filtering and sorting on the completion popup menu, with the " disadvantage of additional latency. " " We're not currently sure this is going to be perfecct, so we have a hidden " option to disable this re-filter/sort. " let results = py3eval( \ 'ycm_state.FilterAndSortItems( vim.eval( "results" ),' \ . ' "key",' \ . ' vim.eval( "query" ) )' ) endif if !waiting call s:EndRequest() endif eval s:HandleSymbolSearchResults( results ) endfunction " }}} " Document Search {{{ function! s:SearchDocument( query, new_query ) abort if !a:new_query return endif if type( s:find_symbol_status.raw_results ) == v:t_none call popup_settext( s:find_symbol_status.id, \ 'No symbols found in document' ) return endif " No spinner, because this is actually a synchronous call " Call filter_and_sort_candidates on the results (synchronously) let response = py3eval( \ 'ycm_state.FilterAndSortItems( ' \ . ' vim.eval( "s:find_symbol_status.raw_results" ),' \ . ' "key",' \ . ' vim.eval( "a:query" ) )' ) eval s:HandleSymbolSearchResults( response ) endfunction function! s:RequestDocumentSymbols() call s:StartRequest() call youcompleteme#GetRawCommandResponseAsync( \ function( 's:HandleDocumentSymbols' ), \ 'GoToDocumentOutline' ) endfunction function! s:HandleDocumentSymbols( results ) abort call s:EndRequest() let s:find_symbol_status.raw_results = s:ParseGoToResponse( '', a:results ) call s:SearchDocument( '', v:true ) endfunction " }}} " Utility for testing {{{ function! youcompleteme#finder#GetState() abort return s:find_symbol_status endfunction " }}} " This is basic vim plugin boilerplate let &cpoptions = s:save_cpo unlet s:save_cpo " vim: foldmethod=marker ================================================ FILE: autoload/youcompleteme/hierarchy.vim ================================================ " Copyright (C) 2021 YouCompleteMe contributors " " This file is part of YouCompleteMe. " " YouCompleteMe is free software: you can redistribute it and/or modify " it under the terms of the GNU General Public License as published by " the Free Software Foundation, either version 3 of the License, or " (at your option) any later version. " " YouCompleteMe is distributed in the hope that it will be useful, " but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " GNU General Public License for more details. " " You should have received a copy of the GNU General Public License " along with YouCompleteMe. If not, see . " This is basic vim plugin boilerplate let s:save_cpo = &cpoptions set cpoptions&vim scriptencoding utf-8 let s:popup_id = -1 let s:lines_and_handles = v:null " 1-based index of the selected item in the popup " -1 means none set " 0 means nothing, (Invalid) let s:select = -1 let s:kind = '' let s:ingored_keys = [ \ "\", \ "\", \ ] function! youcompleteme#hierarchy#StartRequest( kind ) if !py3eval( 'vimsupport.VimSupportsPopupWindows()' ) echo 'Sorry, this feature is not supported in your editor' return endif call youcompleteme#symbol#InitSymbolProperties() py3 ycm_state.ResetCurrentHierarchy() py3 from ycm.client.command_request import GetRawCommandResponse if a:kind == 'call' let lines_and_handles = py3eval( \ 'ycm_state.InitializeCurrentHierarchy( GetRawCommandResponse( ' . \ '[ "CallHierarchy" ], False ), ' . \ 'vim.eval( "a:kind" ) )' ) else let lines_and_handles = py3eval( \ 'ycm_state.InitializeCurrentHierarchy( GetRawCommandResponse( ' . \ '[ "TypeHierarchy" ], False ), ' . \ 'vim.eval( "a:kind" ) )' ) endif if len( lines_and_handles ) let s:lines_and_handles = lines_and_handles let s:kind = a:kind let s:select = 1 call s:SetUpMenu() endif endfunction function! s:MenuFilter( winid, key ) if a:key == "\" " Root changes if we're showing super-tree of a sub-tree of the root " (indicated by the handle being positive) let will_change_root = s:lines_and_handles[ s:select - 1 ][ 1 ] > 0 call popup_close( \ s:popup_id, \ [ s:select - 1, 'resolve_up', will_change_root ] ) return 1 endif if a:key == "\" " Root changes if we're showing sub-tree of a super-tree of the root " (indicated by the handle being negative) let will_change_root = s:lines_and_handles[ s:select - 1 ][ 1 ] < 0 call popup_close( \ s:popup_id, \ [ s:select - 1, 'resolve_down', will_change_root ] ) return 1 endif if a:key == "\" call popup_close( s:popup_id, [ s:select - 1, 'jump', v:none ] ) return 1 endif if a:key == "\" || a:key == "\" || a:key == "\" || a:key == "k" let s:select -= 1 if s:select < 1 let s:select = 1 endif call win_execute( s:popup_id, \ 'call cursor( [' . string( s:select ) . ', 1 ] )' ) call win_execute( s:popup_id, \ 'set cursorline cursorlineopt&' ) return 1 endif if a:key == "\" || a:key == "\" || a:key == "\" || a:key == "j" let s:select += 1 if s:select > len( s:lines_and_handles ) let s:select = len( s:lines_and_handles ) endif call win_execute( s:popup_id, \ 'call cursor( [' . string( s:select ) . ', 1 ] )' ) call win_execute( s:popup_id, \ 'set cursorline cursorlineopt&' ) return 1 endif if index( s:ingored_keys, a:key ) >= 0 return 0 endif " Close the popup on any other key press call popup_close( s:popup_id, [ s:select - 1, 'cancel', v:none ] ) if a:key == "\" || a:key == "\" return 1 endif return 0 endfunction function! s:MenuCallback( winid, result ) let operation = a:result[ 1 ] let selection = a:result[ 0 ] if operation == 'resolve_down' call s:ResolveItem( selection, 'down', a:result[ 2 ] ) elseif operation == 'resolve_up' call s:ResolveItem( selection, 'up', a:result[ 2 ] ) else if operation == 'jump' let handle = s:lines_and_handles[ selection ][ 1 ] py3 ycm_state.JumpToHierarchyItem( vimsupport.GetIntValue( "handle" ) ) endif py3 ycm_state.ResetCurrentHierarchy() let s:kind = '' let s:select = 1 endif endfunction function! s:SetUpMenu() let opts = #{ \ filter: funcref( 's:MenuFilter' ), \ callback: funcref( 's:MenuCallback' ), \ wrap: 0, \ minwidth: &columns * 90/100, \ maxwidth: &columns * 90/100, \ maxheight: &lines * 75/100, \ scrollbar: 1, \ padding: [ 0, 0, 0, 0 ], \ highlight: 'Normal', \ border: [], \ } if &ambiwidth ==# 'single' && &encoding ==? 'utf-8' let opts[ 'borderchars' ] = [ '─', '│', '─', '│', '╭', '╮', '╯', '╰' ] endif let s:popup_id = popup_create( [], opts ) let menu_lines = [] let popup_width = popup_getpos( s:popup_id ).core_width let tabstop = popup_width / 3 for [ item, handle ] in s:lines_and_handles let indent = repeat( ' ', item.indent ) let name = indent \ .. item.icon \ .. item.kind \ .. ': ' .. item.symbol " -2 because: " 0-based index " 1 for the tab character let trunc_name = name[ : tabstop - 2 ] let props = [] let name_pfx_len = len( indent ) + len( item.icon ) + len( item.kind ) + 2 if len( trunc_name ) > name_pfx_len let props += [ \ { \ 'col': name_pfx_len + 1, \ 'length': len( trunc_name ) - name_pfx_len, \ 'type': youcompleteme#symbol#GetPropForSymbolKind( item.kind ), \ } \ ] endif let file_name = item.filepath .. ':' .. item.line_num let trunc_path = file_name[ : tabstop - 2 ] if len(trunc_path) > 0 let props += [ \ { \ 'col': len(trunc_name) + 2, \ 'length': min( [ len(trunc_path), len( item.filepath ) ] ), \ 'type': 'YCM-symbol-file' \ } \ ] if len(trunc_path) > len(item.filepath) + 1 let props += [ \ { \ 'col': len(trunc_name) + 2 + len(item.filepath) + 1, \ 'length': min( [ len(trunc_path), len( item.line_num ) ] ), \ 'type': 'YCM-symbol-line-num' \ } \ ] endif endif let trunc_desc = item.description[ : tabstop - 2 ] let line = trunc_name \ . "\t" \ .. trunc_path \ . "\t" \ .. trunc_desc call add( menu_lines, { 'text': line, 'props': props } ) endfor call win_execute( s:popup_id, \ 'setlocal tabstop=' . tabstop ) call popup_settext( s:popup_id, menu_lines ) call win_execute( s:popup_id, \ 'call cursor( [' . string( s:select ) . ', 1 ] )' ) call win_execute( s:popup_id, \ 'set cursorline cursorlineopt&' ) endfunction function! s:ResolveItem( choice, direction, will_change_root ) let handle = s:lines_and_handles[ a:choice ][ 1 ] if py3eval( \ 'ycm_state.ShouldResolveItem( vimsupport.GetIntValue( "handle" ), vim.eval( "a:direction" ) )' ) let lines_and_handles_with_offset = py3eval( \ 'ycm_state.UpdateCurrentHierarchy( ' . \ 'vimsupport.GetIntValue( "handle" ), ' . \ 'vim.eval( "a:direction" ) )' ) let s:lines_and_handles = lines_and_handles_with_offset[ 0 ] if a:will_change_root " When re-rooting the tree, put the cursor on the new "root" item, as this " helps with orientation. This behaviour is consistent with an expansion " where we _don't_ re-root the tree, so feels more natural than anything " else. " The new root is the element with indent of 0. " let s:select = 1 + indexof( s:lines_and_handles, " \ { i, v -> v[0].indent == 0 } ) let s:select = 1 for item in s:lines_and_handles if item[0].indent == 0 break endif let s:select += 1 endfor else let s:select += lines_and_handles_with_offset[ 1 ] endif endif call s:SetUpMenu() endfunction ================================================ FILE: autoload/youcompleteme/symbol.vim ================================================ " Copyright (C) 2024 YouCompleteMe contributors " " This file is part of YouCompleteMe. " " YouCompleteMe is free software: you can redistribute it and/or modify " it under the terms of the GNU General Public License as published by " the Free Software Foundation, either version 3 of the License, or " (at your option) any later version. " " YouCompleteMe is distributed in the hope that it will be useful, " but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " GNU General Public License for more details. " " You should have received a copy of the GNU General Public License " along with YouCompleteMe. If not, see . let s:highlight_group_for_symbol_kind = { \ 'Array': 'Identifier', \ 'Boolean': 'Boolean', \ 'Class': 'Structure', \ 'Constant': 'Constant', \ 'Constructor': 'Function', \ 'Enum': 'Structure', \ 'EnumMember': 'Identifier', \ 'Event': 'Identifier', \ 'Field': 'Identifier', \ 'Function': 'Function', \ 'Interface': 'Structure', \ 'Key': 'Identifier', \ 'Method': 'Function', \ 'Module': 'Include', \ 'Namespace': 'Type', \ 'Null': 'Keyword', \ 'Number': 'Number', \ 'Object': 'Structure', \ 'Operator': 'Operator', \ 'Package': 'Include', \ 'Property': 'Identifier', \ 'String': 'String', \ 'Struct': 'Structure', \ 'TypeParameter': 'Typedef', \ 'Variable': 'Identifier', \ } let s:initialized_text_properties = v:false function! youcompleteme#symbol#InitSymbolProperties() abort if !s:initialized_text_properties call prop_type_add( 'YCM-symbol-Normal', { 'highlight': 'Normal' } ) for k in keys( s:highlight_group_for_symbol_kind ) call prop_type_add( \ 'YCM-symbol-' . k, \ { 'highlight': s:highlight_group_for_symbol_kind[ k ] } ) endfor call prop_type_add( 'YCM-symbol-file', { 'highlight': 'Comment' } ) call prop_type_add( 'YCM-symbol-filetype', { 'highlight': 'Special' } ) call prop_type_add( 'YCM-symbol-line-num', { 'highlight': 'Number' } ) let s:initialized_text_properties = v:true endif endfunction function! youcompleteme#symbol#GetPropForSymbolKind( kind ) abort if s:highlight_group_for_symbol_kind->has_key( a:kind ) return 'YCM-symbol-' . a:kind endif return 'YCM-symbol-Normal' endfunction ================================================ FILE: autoload/youcompleteme.vim ================================================ " Copyright (C) 2011-2018 YouCompleteMe contributors " " This file is part of YouCompleteMe. " " YouCompleteMe is free software: you can redistribute it and/or modify " it under the terms of the GNU General Public License as published by " the Free Software Foundation, either version 3 of the License, or " (at your option) any later version. " " YouCompleteMe is distributed in the hope that it will be useful, " but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " GNU General Public License for more details. " " You should have received a copy of the GNU General Public License " along with YouCompleteMe. If not, see . " This is basic vim plugin boilerplate let s:save_cpo = &cpo set cpo&vim " NOTE: Neovim reports v:version as 800, which is garbage. For some features " that are supported by our minimum Vim version, we have to guard them against " neovim, which doesn't implement them. let s:is_neovim = has( 'nvim' ) " Only useful in neovim, for handling text properties... I mean extmarks. let g:ycm_neovim_ns_id = s:is_neovim ? nvim_create_namespace( 'ycm_id' ) : -1 " This needs to be called outside of a function let s:script_folder_path = escape( expand( ':p:h' ), '\' ) let s:force_semantic = 0 let s:force_manual = 0 let s:completion_stopped = 0 " These two variables are initialized in youcompleteme#Enable. let s:default_completion = {} let s:completion = s:default_completion let s:default_signature_help = {} let s:signature_help = s:default_completion let s:previous_allowed_buffer_number = 0 let s:pollers = { \ 'completion': { \ 'id': -1, \ 'wait_milliseconds': 10, \ }, \ 'signature_help': { \ 'id': -1, \ 'wait_milliseconds': 10, \ }, \ 'file_parse_response': { \ 'id': -1, \ 'wait_milliseconds': 100, \ }, \ 'server_ready': { \ 'id': -1, \ 'wait_milliseconds': 100, \ }, \ 'receive_messages': { \ 'id': -1, \ 'wait_milliseconds': 100, \ }, \ 'command': { \ 'id': -1, \ 'wait_milliseconds': 100, \ 'requests': {}, \ }, \ 'semantic_highlighting': { \ 'id': -1, \ 'wait_milliseconds': 100, \ }, \ 'inlay_hints': { \ 'id': -1, \ 'wait_milliseconds': 100, \ }, \ } let s:buftype_blacklist = { \ 'help': 1, \ 'terminal': 1, \ 'quickfix': 1, \ 'popup': 1, \ 'nofile': 1, \ } let s:last_char_inserted_by_user = v:true let s:enable_hover = 0 let s:cursorhold_popup = -1 let s:enable_inlay_hints = 0 let s:force_preview_popup = 0 let s:RESOLVE_NONE = 0 let s:RESOLVE_UP_FRONT = 1 let s:RESOLVE_ON_DEMAND = 2 let s:resolve_completions = s:RESOLVE_NONE function! s:StartMessagePoll() if s:pollers.receive_messages.id < 0 let s:pollers.receive_messages.id = timer_start( \ s:pollers.receive_messages.wait_milliseconds, \ function( 's:ReceiveMessages' ) ) endif endfunction function! s:ReceiveMessages( timer_id ) let poll_again = v:false if s:AllowedToCompleteInCurrentBuffer() let poll_again = py3eval( 'ycm_state.OnPeriodicTick()' ) endif if poll_again let s:pollers.receive_messages.id = timer_start( \ s:pollers.receive_messages.wait_milliseconds, \ function( 's:ReceiveMessages' ) ) else " Don't poll again until we open another buffer let s:pollers.receive_messages.id = -1 endif endfunction function! s:SetUpOptions() call s:SetUpCommands() call s:SetUpCpoptions() call s:SetUpCompleteopt() call s:SetUpKeyMappings() if g:ycm_show_diagnostics_ui call s:TurnOffSyntasticForCFamily() endif call s:SetUpSigns() call s:SetUpSyntaxHighlighting() endfunction function! youcompleteme#Enable() call s:SetUpBackwardsCompatibility() let completeopt = split( &completeopt, ',' ) " Will we add 'popup' to the 'completeopt' (later) let s:force_preview_popup = \ type( g:ycm_add_preview_to_completeopt ) == v:t_string && \ g:ycm_add_preview_to_completeopt ==# 'popup' && \ !s:is_neovim " Will we add 'preview' to the 'completeopt' (later) let force_preview = \ type( g:ycm_add_preview_to_completeopt ) != v:t_string && \ g:ycm_add_preview_to_completeopt " Will we be using the preview popup ? That is either the user set it in their " completeopt or we're going to add it later. let use_preview_popup = \ s:force_preview_popup || \ index( completeopt, 'popup' ) >= 0 " We should only ask the server to resolve completion items upfront if we're " going to display them - that is either: " - popup is (or will be) in completeopt " - preview is (or will be) in completeopt, or let require_resolve = \ use_preview_popup || \ force_preview || \ index( completeopt, 'preview' ) >= 0 if use_preview_popup && exists( '*popup_findinfo' ) " If the preview popup is going to be used, and on-demand resolve can be " supported, enable it. let s:resolve_completions = s:RESOLVE_ON_DEMAND elseif require_resolve " The preview window or info popup is enabled - request the server " pre-resolves completion items let s:resolve_completions = s:RESOLVE_UP_FRONT else " Otherwise, there's no point in resolving completions - they'll never be " displayed. endif if !s:SetUpPython() return endif call s:SetUpOptions() py3 ycm_semantic_highlighting.Initialise() let s:enable_inlay_hints = py3eval( 'ycm_inlay_hints.Initialise()' ) ? 1 : 0 call youcompleteme#EnableCursorMovedAutocommands() augroup youcompleteme autocmd! " Note that these events will NOT trigger for the file vim is started with; " so if you do "vim foo.cc", these events will not trigger when that buffer " is read. This is because youcompleteme#Enable() is called on VimEnter and " that happens *after* FileType has already triggered for the initial file. " We don't parse the buffer on the BufRead event since it would only be " useful if the buffer filetype is set (we ignore the buffer if there is no " filetype) and if so, the FileType event has triggered before and thus the " buffer is already parsed. autocmd BufWritePost,FileWritePost * call s:OnFileSave() autocmd FileType * call s:OnFileTypeSet() autocmd BufEnter,CmdwinEnter,WinEnter * call s:OnBufferEnter() autocmd BufUnload * call s:OnBufferUnload() autocmd InsertLeave * call s:OnInsertLeave() autocmd VimLeave * call s:OnVimLeave() autocmd CompleteDone * call s:OnCompleteDone() autocmd CompleteChanged * call s:OnCompleteChanged() augroup END " The FileType event is not triggered for the first loaded file. We wait until " the server is ready to manually run the s:OnFileTypeSet function. let s:pollers.server_ready.id = timer_start( \ s:pollers.server_ready.wait_milliseconds, \ function( 's:PollServerReady' ) ) let s:default_completion = py3eval( 'vimsupport.NO_COMPLETIONS' ) let s:completion = s:default_completion if s:PropertyTypeNotDefined( 'YCM-signature-help-current-argument' ) hi default YCMInverse term=reverse cterm=reverse gui=reverse call prop_type_add( 'YCM-signature-help-current-argument', { \ 'highlight': 'YCMInverse', \ 'combine': 1, \ 'priority': 50, \ } ) endif nnoremap (YCMFindSymbolInWorkspace) \ :call youcompleteme#finder#FindSymbol( 'workspace' ) nnoremap (YCMFindSymbolInDocument) \ :call youcompleteme#finder#FindSymbol( 'document' ) endfunction function! youcompleteme#EnableCursorMovedAutocommands() augroup ycmcompletemecursormove autocmd! autocmd CursorMoved * call s:OnCursorMovedNormalMode() autocmd CursorMovedI * let s:current_cursor_position = getpos( '.' ) autocmd InsertEnter * call s:OnInsertEnter() autocmd TextChanged * call s:OnTextChangedNormalMode() autocmd TextChangedI * call s:OnTextChangedInsertMode( v:false ) autocmd TextChangedP * call s:OnTextChangedInsertMode( v:true ) autocmd InsertCharPre * call s:OnInsertChar() if exists( '##WinScrolled' ) autocmd WinScrolled * call s:OnWinScrolled() endif augroup END endfunction function! youcompleteme#DisableCursorMovedAutocommands() autocmd! ycmcompletemecursormove endfunction function! youcompleteme#GetErrorCount() return py3eval( 'ycm_state.GetErrorCount()' ) endfunction function! youcompleteme#GetWarningCount() return py3eval( 'ycm_state.GetWarningCount()' ) endfunction function! s:SetUpPython() abort py3 << EOF import os.path as p import sys import traceback import vim root_folder = p.normpath( p.join( vim.eval( 's:script_folder_path' ), '..' ) ) third_party_folder = p.join( root_folder, 'third_party' ) # Add dependencies to Python path. sys.path[ 0:0 ] = [ p.join( root_folder, 'python' ), p.join( third_party_folder, 'ycmd' ) ] # We enclose this code in a try/except block to avoid backtraces in Vim. try: # Import the modules used in this file. from ycm import base, vimsupport, youcompleteme from ycm import semantic_highlighting as ycm_semantic_highlighting from ycm import inlay_hints as ycm_inlay_hints if 'ycm_state' in globals(): # If re-initializing, pretend that we shut down ycm_state.OnVimLeave() del ycm_state # If we're able to resolve completion details asynchronously, set the option # which enables this in the server. if int( vim.eval( 's:resolve_completions == s:RESOLVE_ON_DEMAND' ) ): # resolve a small number upfront, the rest on demand default_options = { 'max_num_candidates_to_detail': 10 } elif int( vim.eval( 's:resolve_completions == s:RESOLVE_NONE' ) ): # don't resolve any default_options = { 'max_num_candidates_to_detail': 0 } else: # i.e. s:resolve_completions == s:RESOLVE_UP_FRONT # The server will decide - i.e. resolve everything upfront default_options = {} ycm_state = youcompleteme.YouCompleteMe( default_options ) except Exception as error: # We don't use PostVimMessage or EchoText from the vimsupport module because # importing this module may fail. vim.command( 'redraw | echohl WarningMsg' ) for line in traceback.format_exc().splitlines(): vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) ) vim.command( "echo 'YouCompleteMe unavailable: {0}'" .format( str( error ).replace( "'", "''" ) ) ) vim.command( 'echohl None' ) vim.command( 'return 0' ) else: vim.command( 'return 1' ) EOF endfunction function! s:SetUpKeyMappings() " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to " exist and are now here purely for the sake of backwards compatibility; we " don't want to break users if we can avoid it. if exists('g:ycm_key_select_completion') && \ index(g:ycm_key_list_select_completion, \ g:ycm_key_select_completion) == -1 call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion) endif if exists('g:ycm_key_previous_completion') && \ index(g:ycm_key_list_previous_completion, \ g:ycm_key_previous_completion) == -1 call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion) endif for key in g:ycm_key_list_select_completion " With this command, when the completion window is visible, the tab key " (default) will select the next candidate in the window. In vim, this also " changes the typed-in text to that of the candidate completion. exe 'inoremap ' . 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 for key in g:ycm_key_list_stop_completion " When selecting a candidate and closing the completion menu with the " key, the menu will automatically be reopened because of the TextChangedI " event. We define a command to prevent that. exe 'inoremap ' . key . ' StopCompletion( "\' . 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 ==# '' imap endif silent! exe 'inoremap ' . invoke_key . \ ' =RequestSemanticCompletion()' 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 default link YcmErrorSign SyntasticErrorSign else highlight default link YcmErrorSign error endif endif if !hlexists( 'YcmWarningSign' ) if hlexists( 'SyntasticWarningSign') highlight default link YcmWarningSign SyntasticWarningSign else highlight default link YcmWarningSign todo endif endif if !hlexists( 'YcmErrorLine' ) highlight default link YcmErrorLine SyntasticErrorLine endif if !hlexists( 'YcmWarningLine' ) highlight default link YcmWarningLine SyntasticWarningLine endif call sign_define( [ \ { 'name': 'YcmError', \ 'text': g:ycm_error_symbol, \ 'texthl': 'YcmErrorSign', \ 'linehl': 'YcmErrorLine', \ 'group': 'ycm_signs' }, \ { 'name': 'YcmWarning', \ 'text': g:ycm_warning_symbol, \ 'texthl': 'YcmWarningSign', \ 'linehl': 'YcmWarningLine', \ 'group': 'ycm_signs' } \ ] ) 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 default link YcmErrorSection SyntasticError else highlight default link YcmErrorSection SpellBad endif endif if s:PropertyTypeNotDefined( 'YcmErrorProperty' ) call prop_type_add( 'YcmErrorProperty', { \ 'highlight': 'YcmErrorSection', \ 'priority': 30, \ 'combine': 0, \ 'override': 1 } ) endif " Used for virtual text if !hlexists( 'YcmInvisible' ) highlight default link YcmInvisible Normal endif if !hlexists( 'YcmInlayHint' ) highlight default link YcmInlayHint NonText endif if !hlexists( 'YcmErrorText' ) if exists( '*hlget' ) let YcmErrorText = hlget( 'SpellBad', v:true )[ 0 ] let YcmErrorText.name = 'YcmErrorText' let YcmErrorText.cterm = {} let YcmErrorText.gui = {} let YcmErrorText.term = {} call hlset( [ YcmErrorText ] ) else " approximation hi default link YcmErrorText WarningMsg endif endif if !hlexists( 'YcmWarningText' ) if exists( '*hlget' ) let YcmWarningText = hlget( 'SpellCap', v:true )[ 0 ] let YcmWarningText.name = 'YcmWarningText' let YcmWarningText.cterm = {} let YcmWarningText.gui = {} let YcmWarningText.term = {} call hlset( [ YcmWarningText] ) else " Lame approximation hi default link YcmWarningText Conceal endif endif if s:PropertyTypeNotDefined( 'YcmVirtDiagError' ) call prop_type_add( 'YcmVirtDiagError', { \ 'highlight': 'YcmErrorText', \ 'priority': 20, \ 'combine': 0 } ) endif if s:PropertyTypeNotDefined( 'YcmVirtDiagWarning' ) call prop_type_add( 'YcmVirtDiagWarning', { \ 'highlight': 'YcmWarningText', \ 'priority': 19, \ 'combine': 0 } ) endif if s:PropertyTypeNotDefined( 'YcmVirtDiagPadding' ) call prop_type_add( 'YcmVirtDiagPadding', { \ 'highlight': 'YcmInvisible', \ 'priority': 100, \ 'combine': 1 } ) endif if !hlexists( 'YcmWarningSection' ) if hlexists( 'SyntasticWarning' ) highlight default link YcmWarningSection SyntasticWarning else highlight default link YcmWarningSection SpellCap endif endif if s:PropertyTypeNotDefined( 'YcmWarningProperty' ) call prop_type_add( 'YcmWarningProperty', { \ 'highlight': 'YcmWarningSection', \ 'priority': 29, \ 'combine': 0, \ 'override': 1 } ) endif if !hlexists( 'YcmErrorPopup' ) highlight default link YcmErrorPopup ErrorMsg 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 = [] let g:syntastic_cuda_checkers = [] endfunction function! s:DisableOnLargeFile( buffer ) if exists( 'b:ycm_largefile' ) return b:ycm_largefile endif let threshold = g:ycm_disable_for_files_larger_than_kb * 1024 let b:ycm_largefile = \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold if b:ycm_largefile py3 vimsupport.PostVimMessage( 'YouCompleteMe is disabled in this buffer;' + \ ' the file exceeded the max size (see YCM options).' ) endif return b:ycm_largefile endfunction function! s:PropertyTypeNotDefined( type ) return exists( '*prop_type_add' ) && \ index( prop_type_list(), a:type ) == -1 endfunction function! s:AllowedToCompleteInBuffer( buffer ) let buftype = getbufvar( a:buffer, '&buftype' ) if has_key( s:buftype_blacklist, buftype ) return 0 endif let filetype = getbufvar( a:buffer, '&filetype' ) if empty( filetype ) let filetype = 'ycm_nofiletype' endif let allowed = youcompleteme#filetypes#AllowedForFiletype( filetype ) if !allowed || s:DisableOnLargeFile( a:buffer ) return 0 endif let s:previous_allowed_buffer_number = bufnr( a:buffer ) return allowed endfunction function! s:AllowedToCompleteInCurrentBuffer() return s:AllowedToCompleteInBuffer( '%' ) endfunction function! s:VisitedBufferRequiresReparse() if bufnr( '%' ) ==# s:previous_allowed_buffer_number return 0 endif return s:AllowedToCompleteInCurrentBuffer() 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. set shortmess+=c 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 s:resolve_completions == s:RESOLVE_ON_DEMAND set completeopt+=popuphidden endif if s:force_preview_popup set completeopt+=popup elseif g:ycm_add_preview_to_completeopt set completeopt+=preview endif endfunction function! s:EnableCompletingInCurrentBuffer() if !g:ycm_auto_trigger call s:SetCompleteFunc() endif let b:ycm_completing = 1 endfunction function s:StopPoller( poller ) abort call timer_stop( a:poller.id ) let a:poller.id = -1 endfunction function! s:OnVimLeave() " Workaround a NeoVim issue - not shutting down timers correctly " https://github.com/neovim/neovim/issues/6840 for poller in values( s:pollers ) call s:StopPoller( poller ) endfor py3 ycm_state.OnVimLeave() endfunction function! s:OnCompleteDone() if !s:AllowedToCompleteInCurrentBuffer() return endif let s:last_char_inserted_by_user = v:false py3 ycm_state.OnCompleteDone() call s:UpdateSignatureHelp() endfunction function! s:OnCompleteChanged() if !s:AllowedToCompleteInCurrentBuffer() return endif if ! empty( v:event.completed_item ) let s:last_char_inserted_by_user = v:false call s:ResolveCompletionItem( v:event.completed_item ) endif call s:UpdateSignatureHelp() endfunction function! s:ResolveCompletionItem( item ) if s:resolve_completions != s:RESOLVE_ON_DEMAND return endif let complete_mode = complete_info( [ 'mode' ] ).mode if complete_mode !=# 'eval' && complete_mode !=# 'function' return endif if py3eval( 'ycm_state.ResolveCompletionItem( vim.eval( "a:item" ) )' ) call s:StopPoller( s:pollers.completion ) call timer_start( 0, function( 's:PollResolve', [ a:item ] ) ) else call s:ShowInfoPopup( a:item ) endif endfunction function! s:EnableAutoHover() if g:ycm_auto_hover ==# 'CursorHold' && s:enable_hover augroup YcmBufHover autocmd! * autocmd CursorHold call s:Hover() if exists( '##WinResized' ) autocmd WinResized call popup_close( s:cursorhold_popup ) endif if exists( '##WinScrolled' ) autocmd WinScrolled call popup_close( s:cursorhold_popup ) endif augroup END endif endfunction function! s:DisableAutoHover() augroup YcmBufHover autocmd! * augroup END endfunction function! s:OnFileTypeSet() " The contents of the command-line window are empty when the filetype is set " for the first time. Users should never change its filetype so we only rely " on the CmdwinEnter event for that window. if !empty( getcmdwintype() ) return endif if !s:AllowedToCompleteInCurrentBuffer() return endif call s:SetUpCompleteopt() call s:EnableCompletingInCurrentBuffer() call s:StartMessagePoll() call s:EnableAutoHover() py3 ycm_state.OnFileTypeSet() call s:OnFileReadyToParse( 1 ) endfunction function! s:OnFileSave() let buffer_number = str2nr( expand( '' ) ) if !s:AllowedToCompleteInBuffer( buffer_number ) return endif py3 ycm_state.OnFileSave( vimsupport.GetIntValue( 'buffer_number' ) ) endfunction function! s:AbortAutohoverRequest() abort if g:ycm_auto_hover ==# 'CursorHold' && s:enable_hover let requests = copy( s:pollers.command.requests ) for request_id in keys( requests ) let request = requests[ request_id ] if request.origin == 'autohover' call remove( s:pollers.command.requests, request_id ) py3 ycm_state.FlushCommandRequest( int( vim.eval( "request_id" ) ) ) call request.callback( '' ) endif endfor endif endfunction function! s:OnBufferEnter() call s:StartMessagePoll() if !s:VisitedBufferRequiresReparse() return endif call s:AbortAutohoverRequest() call s:SetUpCompleteopt() call s:EnableCompletingInCurrentBuffer() py3 ycm_state.UpdateMatches() py3 ycm_state.OnBufferVisit() " Last parse may be outdated because of changes from other buffers. Force a " new parse. call s:OnFileReadyToParse( 1 ) endfunction function! s:OnBufferUnload() " Expanding returns the unloaded buffer number as a string but we want " it as a true number for the getbufvar function. let buffer_number = str2nr( expand( '' ) ) if !s:AllowedToCompleteInBuffer( buffer_number ) return endif py3 ycm_state.OnBufferUnload( vimsupport.GetIntValue( 'buffer_number' ) ) endfunction function! s:PollServerReady( timer_id ) if !py3eval( 'ycm_state.IsServerAlive()' ) py3 ycm_state.NotifyUserIfServerCrashed() " Server crashed. Don't poll it again. return endif if !py3eval( 'ycm_state.CheckIfServerIsReady()' ) let s:pollers.server_ready.id = timer_start( \ s:pollers.server_ready.wait_milliseconds, \ function( 's:PollServerReady' ) ) return endif call s:OnFileTypeSet() endfunction function! s:OnFileReadyToParse( ... ) " Accepts an optional parameter that is either 0 or 1. If 1, send a " FileReadyToParse event notification, whether the buffer has changed or not; " effectively forcing a parse of the buffer. Default is 0. let force_parsing = a:0 > 0 && a:1 " We only want to send a new FileReadyToParse event notification if the buffer " has changed since the last time we sent one, or if forced. if force_parsing || py3eval( "ycm_state.NeedsReparse()" ) " We switched buffers or something, so clear. " FIXME: sig help should be buffer local? call s:ClearSignatureHelp() py3 ycm_state.OnFileReadyToParse() call s:StopPoller( s:pollers.file_parse_response ) let s:pollers.file_parse_response.id = timer_start( \ s:pollers.file_parse_response.wait_milliseconds, \ function( 's:PollFileParseResponse' ) ) call s:UpdateSemanticHighlighting( bufnr(), 1, 0 ) call s:UpdateInlayHints( bufnr(), 1, 0 ) endif endfunction function! s:UpdateSemanticHighlighting( bufnr, force, redraw_anyway ) abort call s:StopPoller( s:pollers.semantic_highlighting ) if !s:is_neovim && \ get( b:, 'ycm_enable_semantic_highlighting', \ get( g:, 'ycm_enable_semantic_highlighting', 0 ) ) if py3eval( \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).' \ . 'semantic_highlighting.Request( ' \ . ' force=int( vim.eval( "a:force" ) ) )' ) let s:pollers.semantic_highlighting.id = timer_start( \ s:pollers.semantic_highlighting.wait_milliseconds, \ function( 's:PollSemanticHighlighting', [ a:bufnr ] ) ) elseif a:redraw_anyway py3 ycm_state.Buffer( \ int( vim.eval( "a:bufnr" ) ) ).semantic_highlighting.Refresh() endif endif endfunction function s:ShouldUseInlayHintsNow( bufnr ) return s:enable_inlay_hints && \ getbufvar( a:bufnr, 'ycm_enable_inlay_hints', \ get( g:, 'ycm_enable_inlay_hints', 0 ) ) endfunction function! s:UpdateInlayHints( bufnr, force, redraw_anyway ) abort call s:StopPoller( s:pollers.inlay_hints ) if s:ShouldUseInlayHintsNow( a:bufnr ) if py3eval( \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).' \ . 'inlay_hints.Request( force=int( vim.eval( "a:force" ) ) )' ) let s:pollers.inlay_hints.id = timer_start( \ s:pollers.inlay_hints.wait_milliseconds, \ function( 's:PollInlayHints', [ a:bufnr ] ) ) elseif a:redraw_anyway py3 ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).inlay_hints.Refresh() endif endif endfunction function! s:PollFileParseResponse( ... ) if !py3eval( "ycm_state.FileParseRequestReady()" ) let s:pollers.file_parse_response.id = timer_start( \ s:pollers.file_parse_response.wait_milliseconds, \ function( 's:PollFileParseResponse' ) ) return endif py3 ycm_state.HandleFileParseRequest() if py3eval( "ycm_state.ShouldResendFileParseRequest()" ) call s:OnFileReadyToParse( 1 ) endif endfunction function! s:PollSemanticHighlighting( bufnr, ... ) abort return s:PollScrollable( a:bufnr, 'semantic_highlighting' ) endfunction function! s:PollInlayHints( bufnr, ... ) abort return s:PollScrollable( a:bufnr, 'inlay_hints' ) endfunction function! s:PollScrollable( bufnr, scrollable, ... ) abort if !py3eval( \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )' \ . '.' . a:scrollable . '.Ready()' ) let s:pollers[a:scrollable].id = timer_start( \ s:pollers[a:scrollable].wait_milliseconds, \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) ) elseif ! py3eval( \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )' \ . '.' . a:scrollable . '.Update()' ) let s:pollers[ a:scrollable ].id = timer_start( \ s:pollers[ a:scrollable ].wait_milliseconds, \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) ) endif endfunction function! s:SendKeys( keys ) " By default keys are added to the end of the typeahead buffer. If there are " already keys in the buffer, they will be processed first and may change " the state that our keys combination was sent for (e.g. in " normal mode instead of insert mode or outside of completion mode). " We avoid that by inserting the keys at the start of the typeahead buffer " with the 'i' option. Also, we don't want the keys to be remapped to " something else so we add the 'n' option. call feedkeys( a:keys, 'in' ) endfunction function! s:CloseCompletionMenu() if pumvisible() call s:SendKeys( "\" ) endif endfunction function! s:OnInsertChar() if !s:AllowedToCompleteInCurrentBuffer() return endif let s:last_char_inserted_by_user = v:true endfunction function! s:StopCompletion( key ) call s:StopPoller( s:pollers.completion ) call s:ClearSignatureHelp() if pumvisible() let s:completion_stopped = 1 return "\" endif return a:key endfunction function! s:OnCursorMovedNormalMode() if !s:AllowedToCompleteInCurrentBuffer() return endif call s:AbortAutohoverRequest() py3 ycm_state.OnCursorMoved() endfunction function! s:OnWinScrolled() if !s:AllowedToCompleteInCurrentBuffer() return endif let bufnr = winbufnr( expand( '' ) ) call s:UpdateSemanticHighlighting( bufnr, 0, 0 ) call s:UpdateInlayHints( bufnr, 0, 0 ) endfunction function! s:OnTextChangedNormalMode() if !s:AllowedToCompleteInCurrentBuffer() return endif call s:OnFileReadyToParse() endfunction function! s:OnTextChangedInsertMode( popup_is_visible ) if !s:AllowedToCompleteInCurrentBuffer() return endif if a:popup_is_visible && !s:last_char_inserted_by_user " If the last "input" wasn't from a user typing (i.e. didn't come from " InsertCharPre, then ignore this change in the text. This prevents ctrl-n " or tab from causing us to re-filter the list based on the now-selected " item. return endif let s:current_cursor_position = getpos( '.' ) if s:completion_stopped let s:completion_stopped = 0 let s:completion = s:default_completion return endif call s:IdentifierFinishedOperations() " We have to make sure we correctly leave semantic mode even when the user " inserts something like a "operator[]" candidate string which fails " CurrentIdentifierFinished check. if s:force_semantic && !py3eval( 'base.LastEnteredCharIsIdentifierChar()' ) let s:force_semantic = 0 let s:force_manual = 0 endif if get( b:, 'ycm_completing' ) && \ ( g:ycm_auto_trigger || s:force_semantic || s:force_manual ) && \ !s:InsideCommentOrStringAndShouldStop() && \ !s:OnBlankLine() call s:RequestCompletion() call s:RequestSignatureHelp() endif py3 ycm_state.OnCursorMoved() if g:ycm_autoclose_preview_window_after_completion call s:ClosePreviewWindowIfNeeded() endif endfunction function! s:OnInsertEnter() abort let s:current_cursor_position = getpos( '.' ) py3 ycm_state.OnInsertEnter() if s:ShouldUseInlayHintsNow( bufnr() ) && \ get(g:, 'ycm_clear_inlay_hints_in_insert_mode' ) py3 ycm_state.CurrentBuffer().inlay_hints.Clear() endif endfunction function! s:OnInsertLeave() if !s:AllowedToCompleteInCurrentBuffer() return endif let s:last_char_inserted_by_user = v:false call s:StopPoller( s:pollers.completion ) let s:force_semantic = 0 let s:force_manual = 0 let s:completion = s:default_completion call s:OnFileReadyToParse() py3 ycm_state.OnInsertLeave() if g:ycm_autoclose_preview_window_after_completion || \ g:ycm_autoclose_preview_window_after_insertion call s:ClosePreviewWindowIfNeeded() endif call s:ClearSignatureHelp() if s:ShouldUseInlayHintsNow( bufnr() ) \ && get( g:, 'ycm_clear_inlay_hints_in_insert_mode' ) " We cleared inlay hints on insert enter py3 ycm_state.CurrentBuffer().inlay_hints.Refresh() endif endfunction function! s:ClosePreviewWindowIfNeeded() let current_buffer_name = bufname('') " We don't want to try to close the preview window in special buffers like " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start " with '['. if current_buffer_name[ 0 ] == '[' return endif " This command does the actual closing of the preview window. If no preview " window is shown, nothing happens. pclose endfunction function! s:IdentifierFinishedOperations() if !py3eval( 'base.CurrentIdentifierFinished()' ) return endif py3 ycm_state.OnCurrentIdentifierFinished() let s:force_semantic = 0 let s:force_manual = 0 let s:completion = s:default_completion 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 py3eval( 'not vim.current.line or vim.current.line.isspace()' ) endfunction function! s:RequestCompletion() call s:StopPoller( s:pollers.completion ) py3 ycm_state.SendCompletionRequest( \ vimsupport.GetBoolValue( 's:force_semantic' ) ) if py3eval( 'ycm_state.CompletionRequestReady()' ) " We can't call complete() synchronously in the TextChangedI/TextChangedP " autocommands (it's designed to be used async only completion). The result " (somewhat oddly) is that the completion menu is shown, but ctrl-n doesn't " actually select anything. " When the request is satisfied synchronously (e.g. the omnicompleter), we " must return to the main loop before triggering completion, so we use a 0ms " timer for that. let s:pollers.completion.id = timer_start( 0, \ function( 's:PollCompletion' ) ) else " Otherwise, use our usual poll timeout call s:PollCompletion() endif endfunction function! s:ManuallyRequestCompletion() abort " Since this function is called in a mapping through the expression register " =, its return value is inserted (see :h c_CTRL-R_=). We don't want to " insert anything so we return an empty string. if !s:AllowedToCompleteInCurrentBuffer() return '' endif if get( b:, 'ycm_completing' ) let s:force_manual = 0 call s:RequestCompletion() call s:RequestSignatureHelp() endif return '' endfunction function! s:SetCompleteFunc() let &completefunc = 'youcompleteme#CompleteFunc' endfunction function! youcompleteme#CompleteFunc( findstart, base ) abort call s:ManuallyRequestCompletion() " Cancel, but silently stay in completion mode. return -2 endfunction inoremap (YCMComplete) =ManuallyRequestCompletion() function! s:RequestSemanticCompletion() abort if !s:AllowedToCompleteInCurrentBuffer() return '' endif if get( b:, 'ycm_completing' ) let s:force_semantic = 1 let s:current_cursor_position = getpos( '.' ) call s:StopPoller( s:pollers.completion ) py3 ycm_state.SendCompletionRequest( True ) if py3eval( 'ycm_state.CompletionRequestReady()' ) " We can't call complete() synchronously in the TextChangedI/TextChangedP " autocommands (it's designed to be used async only completion). The " result (somewhat oddly) is that the completion menu is shown, but ctrl-n " doesn't actually select anything. When the request is satisfied " synchronously (e.g. the omnicompleter), we must return to the main loop " before triggering completion, so we use a 0ms timer for that. let s:pollers.completion.id = timer_start( \ 0, \ function( 's:PollCompletion' ) ) else " Otherwise, use our usual poll timeout call s:PollCompletion() endif endif " Since this function is called in a mapping through the expression register " =, its return value is inserted (see :h c_CTRL-R_=). We don't want to " insert anything so we return an empty string. return '' endfunction function! s:PollCompletion( ... ) if !py3eval( 'ycm_state.CompletionRequestReady()' ) let s:pollers.completion.id = timer_start( \ s:pollers.completion.wait_milliseconds, \ function( 's:PollCompletion' ) ) return endif let s:completion = py3eval( 'ycm_state.GetCompletionResponse()' ) if s:current_cursor_position == getpos( '.' ) call s:Complete() endif endfunction function! s:PollResolve( item, ... ) if !py3eval( 'ycm_state.CompletionRequestReady()' ) let s:pollers.completion.id = timer_start( \ s:pollers.completion.wait_milliseconds, \ function( 's:PollResolve', [ a:item ] ) ) return endif " Note we re-use the 'completion' request for resolves. This prevents us " sending a completion request and a resolve request at the same time, as " resolve requests re-use the request data from the last completion request " and it must not change. " We also re-use the poller, so that any new completion request effectively " cancels this poller. let completion_item = \ py3eval( 'ycm_state.GetCompletionResponse()[ "completion" ]' ) if empty( completion_item ) || empty( completion_item.info ) return endif call s:ShowInfoPopup( completion_item ) endfunction function! s:ShowInfoPopup( completion_item ) let id = popup_findinfo() if id call popup_settext( id, split( a:completion_item.info, '\n' ) ) call popup_show( id ) endif endfunction function! s:ShouldUseSignatureHelp() return py3eval( 'vimsupport.VimSupportsPopupWindows()' ) endfunction function! s:RequestSignatureHelp() if !s:ShouldUseSignatureHelp() return endif call s:StopPoller( s:pollers.signature_help ) if py3eval( 'ycm_state.SendSignatureHelpRequest()' ) call s:PollSignatureHelp() endif endfunction function! s:PollSignatureHelp( ... ) if !s:ShouldUseSignatureHelp() return endif if a:0 == 0 && s:pollers.signature_help.id >= 0 " OK this is a bug. We have tried to poll for a response while the timer is " already running. Just return and wait for the timer to fire. return endif if !py3eval( 'ycm_state.SignatureHelpRequestReady()' ) let s:pollers.signature_help.id = timer_start( \ s:pollers.signature_help.wait_milliseconds, \ function( 's:PollSignatureHelp' ) ) return endif let s:signature_help = py3eval( 'ycm_state.GetSignatureHelpResponse()' ) call s:UpdateSignatureHelp() endfunction function! s:Complete() " It's possible for us to be called (by our timer) when we're not _strictly_ " in insert mode. This can happen when mode is temporarily switched, e.g. " due to Ctrl-r or Ctrl-o or a timer or something. If we're not in insert " mode _now_ do nothing (FIXME: or should we queue a timer ?) if count( [ 'i', 'R' ], mode() ) == 0 return endif if s:completion.line != line( '.' ) " Given " scb: column where the completion starts before auto-wrapping " cb: cursor column before auto-wrapping " sca: column where the completion starts after auto-wrapping " ca: cursor column after auto-wrapping " we have " ca - sca = cb - scb " sca = scb + ca - cb let s:completion.completion_start_column += \ col( '.' ) - s:completion.column endif if len( s:completion.completions ) let old_completeopt = &completeopt setlocal completeopt+=noselect call complete( s:completion.completion_start_column, \ s:completion.completions ) let &completeopt = old_completeopt elseif pumvisible() call s:CloseCompletionMenu() endif endfunction function! s:UpdateSignatureHelp() if !s:ShouldUseSignatureHelp() return endif call py3eval( \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' ) endfunction function! s:ClearSignatureHelp() if !s:ShouldUseSignatureHelp() return endif call s:StopPoller( s:pollers.signature_help ) let s:signature_help = s:default_signature_help call py3eval( 'ycm_state.ClearSignatureHelp()' ) endfunction function! youcompleteme#ServerPid() return py3eval( 'ycm_state.ServerPid()' ) endfunction function! s:SetUpCommands() command! YcmRestartServer call s:RestartServer() command! YcmDebugInfo call s:DebugInfo() command! -nargs=* -complete=custom,youcompleteme#LogsComplete -count=0 \ YcmToggleLogs call s:ToggleLogs( , \ , \ ) command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range \ YcmCompleter call s:CompleterCommand(, \ , \ , \ , \ ) command! YcmDiags call s:ShowDiagnostics() command! -nargs=? YcmShowDetailedDiagnostic \ call s:ShowDetailedDiagnostic( ) command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics() endfunction function! s:RestartServer() call s:SetUpOptions() py3 ycm_state.RestartServer() call s:StopPoller( s:pollers.receive_messages ) call s:StopPoller( s:pollers.command ) call s:ClearSignatureHelp() call s:StopPoller( s:pollers.server_ready ) let s:pollers.server_ready.id = timer_start( \ s:pollers.server_ready.wait_milliseconds, \ function( 's:PollServerReady' ) ) endfunction function! s:DebugInfo() echom "Printing YouCompleteMe debug information..." let debug_info = py3eval( 'ycm_state.DebugInfo()' ) echom '-- Resolve completions:' \ ( s:resolve_completions == s:RESOLVE_ON_DEMAND ? 'On demand' : \ s:resolve_completions == s:RESOLVE_UP_FRONT ? 'Up front' : \ 'Never' ) for line in split( debug_info, "\n" ) echom '-- ' . line endfor endfunction function! s:ToggleLogs( count, ... ) py3 ycm_state.ToggleLogs( vimsupport.GetIntValue( 'a:count' ), \ *vim.eval( 'a:000' ) ) endfunction function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos ) return join( py3eval( 'list( ycm_state.GetLogfiles() )' ), "\n" ) endfunction function! youcompleteme#GetCommandResponse( ... ) abort if !s:AllowedToCompleteInCurrentBuffer() return '' endif if !get( b:, 'ycm_completing' ) return '' endif return py3eval( 'ycm_state.GetCommandResponse( vim.eval( "a:000" ) )' ) endfunction function! s:GetCommandResponseAsyncImpl( callback, origin, ... ) abort let request_id = py3eval( \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' ) let s:pollers.command.requests[ request_id ] = { \ 'response_func': 'StringResponse', \ 'origin': a:origin, \ 'callback': a:callback \ } if s:pollers.command.id == -1 let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds, \ function( 's:PollCommands' ) ) endif endfunction function! youcompleteme#GetCommandResponseAsync( callback, ... ) abort if !s:AllowedToCompleteInCurrentBuffer() eval a:callback( '' ) return endif if !get( b:, 'ycm_completing' ) eval a:callback( '' ) return endif call s:GetCommandResponseAsyncImpl( callback, 'extern', a:000 ) endfunction function! youcompleteme#GetRawCommandResponseAsync( callback, ... ) abort if !s:AllowedToCompleteInCurrentBuffer() eval a:callback( { 'error': 'ycm not allowed in buffer' } ) return endif if !get( b:, 'ycm_completing' ) eval a:callback( { 'error': 'ycm disabled in buffer' } ) return endif let request_id = py3eval( \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' ) let s:pollers.command.requests[ request_id ] = { \ 'response_func': 'Response', \ 'origin': 'extern_raw', \ 'callback': a:callback \ } if s:pollers.command.id == -1 let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds, \ function( 's:PollCommands' ) ) endif endfunction function! s:PollCommands( timer_id ) abort " Clear the timer id before calling the callback, as the callback might fire " more requests call s:StopPoller( s:pollers.command ) " Must copy the requests because this loop is likely to modify it let requests = copy( s:pollers.command.requests ) let poll_again = 0 for request_id in keys( requests ) let request = requests[ request_id ] if py3eval( 'ycm_state.GetCommandRequest( int( vim.eval( "request_id" ) ) )' \ . 'is None' ) " Possible in case of race conditions and things like RestartServer " But particularly in the tests let result = v:none elseif !py3eval( 'ycm_state.GetCommandRequest( ' \ . 'int( vim.eval( "request_id" ) ) ).Done()' ) " Not ready yet, poll again and skip this one for now let poll_again = 1 continue else let result = py3eval( 'ycm_state.GetCommandRequest( ' \ . 'int( vim.eval( "request_id" ) ) ).' \ . request.response_func \ . '()' ) endif " This request is done call remove( s:pollers.command.requests, request_id ) py3 ycm_state.FlushCommandRequest( int( vim.eval( "request_id" ) ) ) call request[ 'callback' ]( result ) endfor if poll_again && s:pollers.command.id == -1 let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds, \ function( 's:PollCommands' ) ) endif endfunction function! s:CompleterCommand( mods, count, line1, line2, ... ) py3 ycm_state.SendCommandRequest( \ vim.eval( 'a:000' ), \ vim.eval( 'a:mods' ), \ vimsupport.GetBoolValue( 'a:count != -1' ), \ vimsupport.GetIntValue( 'a:line1' ), \ vimsupport.GetIntValue( 'a:line2' ) ) endfunction function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos ) return join( py3eval( 'ycm_state.GetDefinedSubcommands()' ), "\n" ) endfunction function! youcompleteme#GetDefinedSubcommands() if !s:AllowedToCompleteInCurrentBuffer() return [] endif if !exists( 'b:ycm_completing' ) return [] endif return py3eval( 'ycm_state.GetDefinedSubcommands()' ) endfunction function! youcompleteme#OpenGoToList() py3 vimsupport.PostVimMessage( \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " . \ "Do NOT use it.'" ) py3 vimsupport.OpenQuickFixList( True, True ) endfunction function! s:ShowDiagnostics() py3 ycm_state.ShowDiagnostics() endfunction function! s:ShowDetailedDiagnostic( ... ) if ( a:0 && a:1 == 'popup' ) \ || get( g:, 'ycm_show_detailed_diag_in_popup', 0 ) py3 ycm_state.ShowDetailedDiagnostic( True ) else py3 ycm_state.ShowDetailedDiagnostic( False ) endif endfunction function! s:ForceCompileAndDiagnostics() py3 ycm_state.ForceCompileAndDiagnostics() endfunction if exists( '*popup_atcursor' ) function s:Hover() if !py3eval( 'ycm_state.NativeFiletypeCompletionUsable()' ) " Cancel the autocommand if it happens to have been set call s:DisableAutoHover() return endif if !has_key( b:, 'ycm_hover' ) let cmds = youcompleteme#GetDefinedSubcommands() if index( cmds, 'GetHover' ) >= 0 let b:ycm_hover = { \ 'command': 'GetHover', \ 'syntax': 'markdown', \ } elseif index( cmds, 'GetDoc' ) >= 0 let b:ycm_hover = { \ 'command': 'GetDoc', \ 'syntax': '', \ } elseif index( cmds, 'GetType' ) >= 0 let b:ycm_hover = { \ 'command': 'GetType', \ 'syntax': &syntax, \ } else let b:ycm_hover = {} endif endif if empty( b:ycm_hover ) return endif if empty( popup_getpos( s:cursorhold_popup ) ) call s:GetCommandResponseAsyncImpl( \ function( 's:ShowHoverResult' ), \ 'autohover', \ b:ycm_hover.command ) endif endfunction function! s:ShowHoverResult( response ) call popup_hide( s:cursorhold_popup ) if empty( a:response ) || !exists( 'b:ycm_hover' ) return endif " Try to position the popup at the cursor, but avoid wrapping. If the " longest line is > screen width (&columns), then we just have to wrap, and " place the popup at the leftmost column. " " Find the longest line (FIXME: probably doesn't work well for multi-byte) let lines = split( a:response, "\n" ) let len = max( map( copy( lines ), "len( v:val )" ) ) let wrap = 0 let col = 'cursor' " max width is screen columns minus x padding (2) if len >= (&columns - 2) " There's at least one line > our max - enable word wrap and draw the " popup at the leftmost column let col = 1 let wrap = 1 endif let popup_params = { \ 'col': col, \ 'wrap': wrap, \ 'padding': [ 0, 1, 0, 1 ], \ 'moved': 'word', \ 'maxwidth': &columns, \ 'close': 'click', \ 'fixed': 0, \ } if has_key( b:ycm_hover, 'popup_params' ) let popup_params = extend( copy( popup_params ), \ b:ycm_hover.popup_params ) endif let s:cursorhold_popup = popup_atcursor( lines, popup_params ) call setbufvar( winbufnr( s:cursorhold_popup ), \ '&syntax', \ b:ycm_hover.syntax ) endfunction function! s:ToggleHover() let pos = popup_getpos( s:cursorhold_popup ) if !empty( pos ) && pos.visible call popup_hide( s:cursorhold_popup ) let s:cursorhold_popup = -1 " Disable the auto-trigger until the next cursor movement. call s:DisableAutoHover() augroup YCMHover autocmd! CursorMoved autocmd CursorMoved call s:EnableAutoHover() augroup END else call s:Hover() endif endfunction let s:enable_hover = 1 nnoremap (YCMHover) :call ToggleHover() else " Don't break people's mappings if this feature is disabled, just do nothing. nnoremap (YCMHover) endif function! youcompleteme#Test_GetPollers() return s:pollers endfunction function! s:ToggleSignatureHelp() call py3eval( 'ycm_state.ToggleSignatureHelp()' ) " Because we do this in a insert-mode mapping, we return empty string to " insert/type nothing return '' endfunction silent! inoremap (YCMToggleSignatureHelp) \ =ToggleSignatureHelp() function! s:ToggleInlayHints() let b:ycm_enable_inlay_hints = \ !get( b:, \ 'ycm_enable_inlay_hints', \ get( g:, 'ycm_enable_inlay_hints' ) ) if !b:ycm_enable_inlay_hints && s:enable_inlay_hints py3 ycm_state.CurrentBuffer().inlay_hints.Clear() else call s:UpdateInlayHints( bufnr(), 0, 1 ) endif endfunction silent! nnoremap (YCMToggleInlayHints) \ call ToggleInlayHints() silent! nnoremap (YCMTypeHierarchy) \ call youcompleteme#hierarchy#StartRequest( 'type' ) silent! nnoremap (YCMCallHierarchy) \ call youcompleteme#hierarchy#StartRequest( 'call' ) " This is basic vim plugin boilerplate let &cpo = s:save_cpo unlet s:save_cpo ================================================ FILE: codecov.yml ================================================ codecov: notify: require_ci_to_pass: yes coverage: precision: 2 round: down range: 70...100 status: # Learn more at https://codecov.io/docs#yaml_default_commit_status project: true patch: true changes: true # We don't want statistics for the tests themselves. ignore: - .*/tests/.* comment: layout: "header, diff, changes, uncovered" behavior: default # update if exists else create new ================================================ FILE: doc/youcompleteme.txt ================================================ *youcompleteme* YouCompleteMe: a code-completion engine for Vim =============================================================================== Contents ~ 1. Introduction |youcompleteme-introduction| 1. Help, Advice, Support |youcompleteme-help-advice-support| 2. Vundle |youcompleteme-vundle| 1. Contents |youcompleteme-contents| 2. Intro |youcompleteme-intro| 3. Installation |youcompleteme-installation| 1. Requirements |youcompleteme-requirements| 1. Supported Vim Versions |youcompleteme-supported-vim-versions| 2. Supported Python runtime |youcompleteme-supported-python-runtime| 3. Supported Compilers |youcompleteme-supported-compilers| 4. Individual completer requirements |youcompleteme-individual-completer-requirements| 2. macOS |youcompleteme-macos| 1. Quick start, installing all completers |youcompleteme-quick-start-installing-all-completers| 2. Explanation for the quick start |youcompleteme-explanation-for-quick-start| 3. Linux 64-bit |youcompleteme-linux-64-bit| 1. Quick start, installing all completers 2. Explanation for the quick start 4. Windows |youcompleteme-windows| 1. Quick start, installing all completers 2. Explanation for the quick start 5. Full Installation Guide |youcompleteme-full-installation-guide| 4. Quick Feature Summary |youcompleteme-quick-feature-summary| 1. General (all languages) |youcompleteme-general| 2. C-family languages (C, C++, Objective C, Objective C++, CUDA) |youcompleteme-c-family-languages| 3. C♯ |youcompleteme-c| 4. Python |youcompleteme-python| 5. Go |youcompleteme-go| 6. JavaScript and TypeScript |youcompleteme-javascript-typescript| 7. Rust |youcompleteme-rust| 8. Java |youcompleteme-java| 5. User Guide |youcompleteme-user-guide| 1. General Usage |youcompleteme-general-usage| 2. Client-Server Architecture |youcompleteme-client-server-architecture| 3. Completion String Ranking |youcompleteme-completion-string-ranking| 4. Signature Help |youcompleteme-signature-help| 1. Dismiss signature help |youcompleteme-dismiss-signature-help| 5. Semantic highlighting |youcompleteme-semantic-highlighting| 1. Customising the highlight groups |youcompleteme-customising-highlight-groups| 6. Inlay hints |youcompleteme-inlay-hints| 1. Highlight groups |youcompleteme-highlight-groups| 2. Options |youcompleteme-options| 3. Toggling |youcompleteme-toggling| 4. General Semantic Completion |youcompleteme-general-semantic-completion| 5. C-family Semantic Completion |youcompleteme-c-family-semantic-completion| 1. Installation 2. Compile flags |youcompleteme-compile-flags| 3. Option 1: Use a compilation database [53] |youcompleteme-option-1-use-compilation-database-53| 4. Option 2: Provide the flags manually |youcompleteme-option-2-provide-flags-manually| 5. Errors during compilation |youcompleteme-errors-during-compilation| 6. Java Semantic Completion |youcompleteme-java-semantic-completion| 1. Java Quick Start |youcompleteme-java-quick-start| 2. Java Project Files |youcompleteme-java-project-files| 3. Diagnostic display - Syntastic |youcompleteme-diagnostic-display-syntastic| 4. Diagnostic display - Eclim |youcompleteme-diagnostic-display-eclim| 5. Eclipse Projects |youcompleteme-eclipse-projects| 6. Maven Projects |youcompleteme-maven-projects| 7. Gradle Projects |youcompleteme-gradle-projects| 8. Troubleshooting |youcompleteme-troubleshooting| 7. C# Semantic Completion |youcompleteme-c-semantic-completion| 1. Automatically discovered solution files |youcompleteme-automatically-discovered-solution-files| 2. Manually specified solution files |youcompleteme-manually-specified-solution-files| 3. Use with .NET 6.0 and .NET SDKs |youcompleteme-use-with-.net-6.0-.net-sdks| 8. Python Semantic Completion |youcompleteme-python-semantic-completion| 1. Working with virtual environments |youcompleteme-working-with-virtual-environments| 2. Working with third-party packages |youcompleteme-working-with-third-party-packages| 3. Configuring through Vim options |youcompleteme-configuring-through-vim-options| 9. Rust Semantic Completion |youcompleteme-rust-semantic-completion| 10. Go Semantic Completion |youcompleteme-go-semantic-completion| 11. JavaScript and TypeScript Semantic Completion |youcompleteme-javascript-typescript-semantic-completion| 12. Semantic Completion for Other Languages |youcompleteme-semantic-completion-for-other-languages| 1. Plugging an arbitrary LSP server |youcompleteme-plugging-an-arbitrary-lsp-server| 2. LSP Configuration |youcompleteme-lsp-configuration| 3. Using 'omnifunc' for semantic completion |youcompleteme-using-omnifunc-for-semantic-completion| 13. Writing New Semantic Completers |youcompleteme-writing-new-semantic-completers| 14. Diagnostic Display |youcompleteme-diagnostic-display| 1. Diagnostic Highlighting Groups |youcompleteme-diagnostic-highlighting-groups| 15. Symbol Search |youcompleteme-symbol-search| 1. Closing the popup |youcompleteme-closing-popup| 16. Type/Call Hierarchy |youcompleteme-type-call-hierarchy| 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 |:YcmToggleLogs| command 7. The |:YcmCompleter| command 8. YcmCompleter Subcommands |youcompleteme-ycmcompleter-subcommands| 1. GoTo Commands |youcompleteme-goto-commands| 1. The |GoToInclude| subcommand 2. The |GoToAlternateFile| subcommand 3. The |GoToDeclaration| subcommand 4. The |GoToDefinition| subcommand 5. The |GoTo| subcommand 6. The |GoToImprecise| subcommand 7. The 'GoToSymbol ' subcommand |GoToSymbol-symbol-query| 8. The |GoToReferences| subcommand 9. The |GoToImplementation| subcommand 10. The |GoToImplementationElseDeclaration| subcommand 11. The |GoToType| subcommand 12. The |GoToDocumentOutline| subcommand 13. The |GoToCallers| and 'GoToCallees' subcommands 2. Semantic Information Commands |youcompleteme-semantic-information-commands| 1. The |GetType| subcommand 2. The |GetTypeImprecise| subcommand 3. The |GetParent| subcommand 4. The |GetDoc| subcommand 5. The |GetDocImprecise| subcommand 3. Refactoring Commands |youcompleteme-refactoring-commands| 1. The |FixIt| subcommand 2. The 'RefactorRename ' subcommand |RefactorRename-new-name| 3. Python refactorings |youcompleteme-python-refactorings| 4. Multi-file Refactor |youcompleteme-multi-file-refactor| 5. The |Format| subcommand 6. The |OrganizeImports| subcommand 4. Miscellaneous Commands |youcompleteme-miscellaneous-commands| 1. The 'ExecuteCommand ' subcommand |ExecuteCommand-args| 2. The |RestartServer| subcommand 3. The |ReloadSolution| subcommand 9. Functions |youcompleteme-functions| 1. The |youcompleteme#GetErrorCount| function 2. The |youcompleteme#GetWarningCount| function 3. The 'youcompleteme#GetCommandResponse( ... )' function |youcompleteme#GetCommandResponse()| 4. The 'youcompleteme#GetCommandResponseAsync( callback, ... )' function |youcompleteme#GetCommandResponseAsync()| 10. Autocommands |youcompleteme-autocommands| 1. The |YcmLocationOpened| autocommand 2. The |YcmQuickFixOpened| autocommand 11. 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_max_num_candidates| option 4. The |g:ycm_max_num_candidates_to_detail| option 5. The |g:ycm_max_num_identifier_candidates| option 6. The |g:ycm_auto_trigger| option 7. The |g:ycm_filetype_whitelist| option 8. The |g:ycm_filetype_blacklist| option 9. The |g:ycm_filetype_specific_completion_to_disable| option 10. The |g:ycm_filepath_blacklist| option 11. The |g:ycm_show_diagnostics_ui| option 12. The |g:ycm_error_symbol| option 13. The |g:ycm_warning_symbol| option 14. The |g:ycm_enable_diagnostic_signs| option 15. The |g:ycm_enable_diagnostic_highlighting| option 16. The |g:ycm_echo_current_diagnostic| option 17. The |g:ycm_auto_hover| option 18. The |g:ycm_filter_diagnostics| option 19. The |g:ycm_always_populate_location_list| option 20. The |g:ycm_open_loclist_on_ycm_diags| option 21. The |g:ycm_complete_in_comments| option 22. The |g:ycm_complete_in_strings| option 23. The |g:ycm_collect_identifiers_from_comments_and_strings| option 24. The |g:ycm_collect_identifiers_from_tags_files| option 25. The |g:ycm_seed_identifiers_with_syntax| option 26. The |g:ycm_extra_conf_vim_data| option 27. The |g:ycm_server_python_interpreter| option 28. The |g:ycm_keep_logfiles| option 29. The |g:ycm_log_level| option 30. The |g:ycm_auto_start_csharp_server| option 31. The |g:ycm_auto_stop_csharp_server| option 32. The |g:ycm_csharp_server_port| option 33. The |g:ycm_csharp_insert_namespace_expr| option 34. The |g:ycm_add_preview_to_completeopt| option 35. The |g:ycm_autoclose_preview_window_after_completion| option 36. The |g:ycm_autoclose_preview_window_after_insertion| option 37. The |g:ycm_max_diagnostics_to_display| option 38. The |g:ycm_key_list_select_completion| option 39. The |g:ycm_key_list_previous_completion| option 40. The |g:ycm_key_list_stop_completion| option 41. The |g:ycm_key_invoke_completion| option 42. The |g:ycm_key_detailed_diagnostics| option 43. The |g:ycm_show_detailed_diag_in_popup| option 44. The |g:ycm_global_ycm_extra_conf| option 45. The |g:ycm_confirm_extra_conf| option 46. The |g:ycm_extra_conf_globlist| option 47. The |g:ycm_filepath_completion_use_working_dir| option 48. The |g:ycm_semantic_triggers| option 49. The |g:ycm_cache_omnifunc| option 50. The |g:ycm_use_ultisnips_completer| option 51. The |g:ycm_goto_buffer_command| option 52. The |g:ycm_disable_for_files_larger_than_kb| option 53. The |g:ycm_use_clangd| option 54. The |g:ycm_clangd_binary_path| option 55. The |g:ycm_clangd_args| option 56. The |g:ycm_clangd_uses_ycmd_caching| option 57. The |g:ycm_language_server| option 58. The |g:ycm_disable_signature_help| option 59. The |g:ycm_signature_help_disable_syntax| option 60. The |g:ycm_gopls_binary_path| option 61. The |g:ycm_gopls_args| option 62. The |g:ycm_rls_binary_path| and 'g:ycm_rustc_binary_path' options 63. The |g:ycm_rust_toolchain_root| option 64. The |g:ycm_tsserver_binary_path| option 65. The |g:ycm_roslyn_binary_path| option 66. The |g:ycm_update_diagnostics_in_insert_mode| option 12. FAQ |youcompleteme-faq| 13. Contributor Code of Conduct |youcompleteme-contributor-code-of-conduct| 14. Contact |youcompleteme-contact| 15. License |youcompleteme-license| 16. Sponsorship |youcompleteme-sponsorship| 3. References |youcompleteme-references| =============================================================================== *youcompleteme-introduction* Introduction ~ Image: Gitter room [1] Image: Build status [3] Image: Coverage status [5] ------------------------------------------------------------------------------- *youcompleteme-help-advice-support* Help, Advice, Support ~ Looking for help, advice, or support? Having problems getting YCM to work? First carefully read the installation instructions for your OS. We recommend you use the supplied 'install.py' - the "full" installation guide is for rare, advanced use cases and most users should use 'install.py'. If the server isn't starting and you're getting a "YouCompleteMe unavailable" error, check the Troubleshooting [7] guide. Next, check the User Guide section on the semantic completer that you are using. For C/C++/Objective-C/Objective-C++/CUDA, you _must_ read this section. Finally, check the FAQ [8]. If, after reading the installation and user guides, and checking the FAQ, you're still having trouble, check the contacts section below for how to get in touch. Please do **NOT** go to #vim on Freenode for support. Please contact the YouCompleteMe maintainers directly using the contact details below. =============================================================================== *youcompleteme-vundle* Vundle ~ Please note that the below instructions suggest using Vundle. Currently there are problems with Vundle, so here are some alternative instructions [9] using Vim packages. ------------------------------------------------------------------------------- *youcompleteme-contents* Contents ~ - Intro - Installation - Requirements - macOS - Linux 64-bit - Windows - Full Installation Guide - Quick Feature Summary - User Guide - General Usage - Client-Server Architecture - Completion String Ranking - General Semantic Completion - Signature Help - Semantic Highlighting - Inlay Hints - C-family Semantic Completion - Java Semantic Completion - C# Semantic Completion - Python Semantic Completion - Rust Semantic Completion - Go Semantic Completion - JavaScript and TypeScript Semantic Completion - Semantic Completion for Other Languages - LSP Configuration - Writing New Semantic Completers - Diagnostic Display - Diagnostic Highlighting Groups - Symbol Search - Type/Call Hierarchy - Commands - YcmCompleter subcommands - GoTo Commands - Semantic Information Commands - Refactoring Commands - Miscellaneous Commands - Functions - Autocommands - Options - FAQ - Contributor Code of Conduct - Contact - License - Sponsorship ------------------------------------------------------------------------------- *youcompleteme-intro* Intro ~ YouCompleteMe is a fast, as-you-type, fuzzy-search code completion, comprehension and refactoring engine for Vim [10]. It has several completion engines built-in and supports any protocol-compliant Language Server, so can work with practically any language. YouCompleteMe contains: - an identifier-based engine that works with every programming language, - a powerful clangd [11]-based engine that provides native semantic code completion for C/C++/Objective-C/Objective-C++/CUDA (from now on referred to as "the C-family languages"), - a Jedi [12]-based completion engine for Python 2 and 3, - an OmniSharp-Roslyn [13]-based completion engine for C#, - a Gopls [14]-based completion engine for Go, - a TSServer [15]-based completion engine for JavaScript and TypeScript, - a rust-analyzer [16]-based completion engine for Rust, - a jdt.ls [17]-based completion engine for Java. - a generic Language Server Protocol implementation for any language - 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 completion demo (see reference [18]) Here's an explanation of what happened in the last 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 [19] 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 [20]) if you are editing a C-family file. As the completer engine 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. **And that's not all...** YCM might be the only Vim completion engine with the correct Unicode support. Though we do assume UTF-8 everywhere. Image: YouCompleteMe GIF unicode demo (see reference [21]) YCM also provides semantic IDE-like features in a number of languages, including: - displaying signature help (argument hints) when entering the arguments to a function call (Vim only) - finding declarations, definitions, usages, etc. of identifiers, and an interactive symbol finder - displaying type information for classes, variables, functions etc., - displaying documentation for methods, members, etc. in the preview window, or in a popup next to the cursor (Vim only) - fixing common coding errors, like missing semi-colons, typos, etc., - semantic renaming of variables across files, - formatting code, - removing unused imports, sorting imports, etc. For example, here's a demo of signature help: Image: Signature Help Early Demo (see reference [22]) Below we can see YCM being able to do a few things: - Retrieve references across files - Go to declaration/definition - Expand 'auto' in C++ - Fix some common errors, and provide refactorings, with |FixIt| - Not shown in the GIF are |GoToImplementation| and |GoToType| for servers that support it. Image: YouCompleteMe GIF subcommands demo (see reference [23]) And here's some documentation being shown in a hover popup, automatically and manually: Image: hover demo (see reference [24]) Features vary by file type, so make sure to check out the file type feature summary and the full list of completer subcommands to find out what's available for your favourite languages. You'll also find that YCM has filepath completers (try typing './' in a file) and a completer that integrates with UltiSnips [25]. ------------------------------------------------------------------------------- *youcompleteme-installation* Installation ~ ------------------------------------------------------------------------------- *youcompleteme-requirements* Requirements ~ =============================================================================== | _Runtime_ | _Min Version_ | _Recommended Version (full support)_ | _Python_ | =============================================================================== | Vim | 9.1.0016 | 9.1.0016 | 3.12 | ------------------------------------------------------------------------------- | Neovim | 0.5 | Vim 9.1.0016 | 3.12 | ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- *youcompleteme-supported-vim-versions* Supported Vim Versions ~ Our policy is to support the Vim version that's in the latest LTS of Ubuntu. Vim must have a working Python 3 runtime. For Neovim users, our policy is to require the latest released version. Currently, Neovim 0.5.0 is required. Please note that some features are not available in Neovim, and Neovim is not officially supported. ------------------------------------------------------------------------------- *youcompleteme-supported-python-runtime* Supported Python runtime ~ YCM has two components: A server and a client. Both the server and client require Python 3.12 or later 3.x release. For the Vim client, Vim must be, compiled with '--enable-shared' (or '--enable-framework' on macOS). You can check if this is working with ':py3 import sys; print( sys.version)'. It should say something like '3.12.0 (...)'. For Neovim, you must have a python 3.12 runtime and the Neovim python extensions. See Neovim's ':help provider-python' for how to set that up. For the server, you must run the 'install.py' script with a python 3.12 (or later) runtime. Anaconda etc. are not supported. YCM will remember the runtime you used to run 'install.py' and will use that when launching the server, so if you usually use anaconda, then make sure to use the full path to a real cpython3, e.g. '/usr/bin/python3 install.py --all' etc. Our policy is to support the python3 version that's available in the latest Ubuntu LTS (similar to our Vim version policy). We don't increase the Python runtime version without a reason, though. Typically, we do this when the current python version we're using goes out of support. At that time we will typically pick a version that will be supported for a number of years. ------------------------------------------------------------------------------- *youcompleteme-supported-compilers* Supported Compilers ~ In order to provide the best possible performance and stability, ycmd has updated its code to C++17. This requires a version bump of the minimum supported compilers. The new requirements are: =============================== | _Compiler_ | _Current Min_ | =============================== | GCC | 8 | ------------------------------- | Clang | 7 | ------------------------------- | MSVC | 15.7 (VS 2017) | ------------------------------- YCM requires CMake 3.13 or greater. If your CMake is too old, you may be able to simply 'pip install --user cmake' to get a really new version. ------------------------------------------------------------------------------- *youcompleteme-individual-completer-requirements* Individual completer requirements ~ When enabling language support for a particular language, there may be runtime requirements, such as needing a very recent Java Development Kit for Java support. In general, YCM is not in control of the required versions for the downstream compilers, though we do our best to signal where we know them. ------------------------------------------------------------------------------- *youcompleteme-macos* macOS ~ ------------------------------------------------------------------------------- *youcompleteme-quick-start-installing-all-completers* Quick start, installing all completers ~ - Install YCM plugin via Vundle [26] - Install CMake, MacVim and Python 3; Note that the pre-installed _macOS system_ Vim is not supported (due to it having broken Python integration). > $ brew install cmake python go nodejs < - Install mono from Mono Project [27] (NOTE: on Intel Macs you can also 'brew install mono'. On arm Macs, you may require Rosetta) - For Java support you must install a JDK, one way to do this is with Homebrew: > $ brew install java $ sudo ln -sfn $(brew --prefix java)/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk < - Pre-installed macOS _system_ Vim does not support Python 3. So you need to install either a Vim that supports Python 3 OR MacVim [28] with Homebrew [29]: - Option 1: Installing a Vim that supports Python 3 > brew install vim < - Option 2: Installing MacVim [28] > brew install macvim < - Compile YCM. - For Intel and arm64 Macs, the bundled libclang/clangd work: > cd ~/.vim/bundle/YouCompleteMe python3 install.py --all < - If you have troubles with finding system frameworks or C++ standard library, try using the homebrew llvm: > brew install llvm cd ~/.vim/bundle/YouCompleteMe python3 install.py --system-libclang --all < And edit your vimrc to add the following line to use the Homebrew llvm's clangd: > " Use homebrew's clangd let g:ycm_clangd_binary_path = trim(system('brew --prefix llvm')).'/bin/clangd' < - For using an arbitrary LSP server, check the relevant section ------------------------------------------------------------------------------- *youcompleteme-explanation-for-quick-start* Explanation for the quick start ~ These instructions (using 'install.py') are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide. A supported Vim version with Python 3 is required. MacVim [28] is a good option, even if you only use the terminal. YCM won't work with the pre-installed Vim from Apple as its Python support is broken. If you don't already use a Vim that supports Python 3 or MacVim [28], install it with Homebrew [29]. Install CMake as well: > brew install vim cmake < OR > brew install macvim cmake < Install YouCompleteMe with Vundle [26]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the 'ycm_core' library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. **NOTE:** If you want C-family completion, you MUST have the latest Xcode installed along with the latest Command Line Tools (they are installed automatically when you run 'clang' for the first time, or manually by running 'xcode-select --install') Compiling YCM **with** semantic support for C-family languages through **clangd**: > cd ~/.vim/bundle/YouCompleteMe ./install.py --clangd-completer < Compiling YCM **without** semantic support for C-family languages: > cd ~/.vim/bundle/YouCompleteMe ./install.py < The following additional language support options are available: - C# support: install by downloading the Mono macOS package [30] and add '--cs-completer' when calling 'install.py'. - Go support: install Go [31] and add '--go-completer' when calling 'install.py'. - JavaScript and TypeScript support: install Node.js 18+ and npm [32] and add '--ts-completer' when calling 'install.py'. - Rust support: add '--rust-completer' when calling 'install.py'. - Java support: install JDK 17 [33] and add '--java-completer' when calling 'install.py'. To simply compile with everything enabled, there's a '--all' flag. So, to install with all language features, ensure 'xbuild', 'go', 'node' and 'npm' tools are installed and in your 'PATH', then simply run: > cd ~/.vim/bundle/YouCompleteMe ./install.py --all < That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ------------------------------------------------------------------------------- *youcompleteme-linux-64-bit* Linux 64-bit ~ The following assume you're using Ubuntu 24.04. ------------------------------------------------------------------------------- Quick start, installing all completers ~ - Install YCM plugin via Vundle [26] - Install CMake, Vim and Python > apt install build-essential cmake vim-nox python3-dev < - Install mono-complete, go, node, java, and npm > apt install mono-complete golang nodejs openjdk-17-jdk openjdk-17-jre npm < - Compile YCM > cd ~/.vim/bundle/YouCompleteMe python3 install.py --all < - For plugging an arbitrary LSP server, check the relevant section ------------------------------------------------------------------------------- Explanation for the quick start ~ These instructions (using 'install.py') are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide. Make sure you have a supported version of Vim with Python 3 support and a supported compiler. The latest LTS of Ubuntu is the minimum platform for simple installation. For earlier releases or other distributions, you may have to do some work to acquire the dependencies. If your Vim version is too old, you may need to compile Vim from source [34] (don't worry, it's easy). Install YouCompleteMe with Vundle [26]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the 'ycm_core' library APIs have changed (which happens rarely), YCM will notify you to recompile it. You should then rerun the installation process. Install development tools, CMake, and Python headers: - Fedora-like distributions: > sudo dnf install cmake gcc-c++ make python3-devel < - Ubuntu LTS: > sudo apt install build-essential cmake3 python3-dev < Compiling YCM **with** semantic support for C-family languages through **clangd**: > cd ~/.vim/bundle/YouCompleteMe python3 install.py --clangd-completer < Compiling YCM **without** semantic support for C-family languages: > cd ~/.vim/bundle/YouCompleteMe python3 install.py < The following additional language support options are available: - C# support: install Mono [35] and add '--cs-completer' when calling 'install.py'. - Go support: install Go [31] and add '--go-completer' when calling 'install.py'. - JavaScript and TypeScript support: install Node.js 18+ and npm [32] and add '--ts-completer' when calling 'install.py'. - Rust support: add '--rust-completer' when calling 'install.py'. - Java support: install JDK 17 [33] and add '--java-completer' when calling 'install.py'. To simply compile with everything enabled, there's a '--all' flag. So, to install with all language features, ensure 'xbuild', 'go', 'node', and 'npm' tools are installed and in your 'PATH', then simply run: > cd ~/.vim/bundle/YouCompleteMe python3 install.py --all < That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ------------------------------------------------------------------------------- *youcompleteme-windows* Windows ~ **_NOTE_**: Windows support is _deprecated_ and _unmaintained_. We will do our best to keep it working, but we no longer test it in CI and there is a high likelihood of breakages. ------------------------------------------------------------------------------- Quick start, installing all completers ~ - Install YCM plugin via Vundle [26] - Install Visual Studio Build Tools 2019 [36] - Install CMake, Vim and Python - Install go, node and npm - Compile YCM > cd YouCompleteMe python3 install.py --all < - Add 'set encoding=utf-8' to your vimrc [37] - For plugging an arbitrary LSP server, check the relevant section ------------------------------------------------------------------------------- Explanation for the quick start ~ These instructions (using 'install.py') are the quickest way to install YouCompleteMe, however they may not work for everyone. If the following instructions don't work for you, check out the full installation guide. **Important:** we assume that you are using the 'cmd.exe' command prompt and that you know how to add an executable to the PATH environment variable. Make sure you have a supported Vim version with Python 3 support. You can check the version and which Python is supported by typing ':version' inside Vim. Look at the features included: '+python3/dyn' for Python 3. Take note of the Vim architecture, i.e. 32 or 64-bit. It will be important when choosing the Python installer. We recommend using a 64-bit client. Daily updated installers of 32-bit and 64-bit Vim with Python 3 support [38] are available. Add the following line to your vimrc [37] if not already present.: > set encoding=utf-8 < This option is required by YCM. Note that it does not prevent you from editing a file in another encoding than UTF-8. You can do that by specifying the '|++enc|' argument to the ':e' command. Install YouCompleteMe with Vundle [26]. **Remember:** YCM is a plugin with a compiled component. If you **update** YCM using Vundle and the 'ycm_core' library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process. Download and install the following software: - Python 3 [39]. Be sure to pick the version corresponding to your Vim architecture. It is _Windows x86_ for a 32-bit Vim and _Windows x86-64_ for a 64-bit Vim. We recommend installing Python 3. Additionally, the version of Python you install must match up exactly with the version of Python that Vim is looking for. Type ':version' and look at the bottom of the page at the list of compiler flags. Look for flags that look similar to '-DDYNAMIC_PYTHON3_DLL=\"python36.dll\"'. This indicates that Vim is looking for Python 3.6. You'll need one or the other installed, matching the version number exactly. - CMake [40]. Add CMake executable to the PATH environment variable. - Build Tools for Visual Studio 2019 [36]. During setup, select _C++ build tools_ in _Workloads_. Compiling YCM **with** semantic support for C-family languages through **clangd**: > cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py --clangd-completer < Compiling YCM **without** semantic support for C-family languages: > cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py < The following additional language support options are available: - C# support: add '--cs-completer' when calling 'install.py'. Be sure that the build utility 'msbuild' is in your PATH [41]. - Go support: install Go [31] and add '--go-completer' when calling 'install.py'. - JavaScript and TypeScript support: install Node.js 18+ and npm [32] and add '--ts-completer' when calling 'install.py'. - Rust support: add '--rust-completer' when calling 'install.py'. - Java support: install JDK 17 [33] and add '--java-completer' when calling 'install.py'. To simply compile with everything enabled, there's a '--all' flag. So, to install with all language features, ensure 'msbuild', 'go', 'node' and 'npm' tools are installed and in your 'PATH', then simply run: > cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe python install.py --all < You can specify the Microsoft Visual C++ (MSVC) version using the '--msvc' option. YCM officially supports MSVC 15 (2017), MSVC 16 (Visual Studio 2019) and MSVC 17 (Visual Studio 17 2022). That's it. You're done. Refer to the _User Guide_ section on how to use YCM. Don't forget that if you want the C-family semantic completion engine to work, you will need to provide the compilation flags for your project to YCM. It's all in the User Guide. YCM comes with sane defaults for its options, but you still may want to take a look at what's available for configuration. There are a few interesting options that are conservatively turned off by default that you may want to turn on. ------------------------------------------------------------------------------- *youcompleteme-full-installation-guide* Full Installation Guide ~ The full installation guide [42] has been moved to the wiki. ------------------------------------------------------------------------------- *youcompleteme-quick-feature-summary* Quick Feature Summary ~ ------------------------------------------------------------------------------- *youcompleteme-general* General (all languages) ~ - Super-fast identifier completer including tags files and syntax elements - Intelligent suggestion ranking and filtering - File and path suggestions - Suggestions from Vim's omnifunc - UltiSnips snippet suggestions ------------------------------------------------------------------------------- *youcompleteme-c-family-languages* C-family languages (C, C++, Objective C, Objective C++, CUDA) ~ - Semantic auto-completion with automatic fixes - Signature help - Real-time diagnostic display - Go to include/declaration/definition (|GoTo|, etc.) - Go to alternate file (e.g. associated header |GoToAlternateFile|) - Find Symbol ('GoToSymbol'), with interactive search - Document outline (|GoToDocumentOutline|), with interactive search - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Automatically fix certain errors (|FixIt|) - Perform refactoring (|FixIt|) - Reference finding (|GoToReferences|) - Renaming symbols ('RefactorRename ') - Code formatting (|Format|) - Semantic highlighting - Inlay hints - Type hierarchy - Call hierarchy ------------------------------------------------------------------------------- *youcompleteme-c* C♯ ~ - Semantic auto-completion - Signature help - Real-time diagnostic display - Go to declaration/definition (|GoTo|, etc.) - Go to implementation (|GoToImplementation|) - Find Symbol ('GoToSymbol'), with interactive search - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Automatically fix certain errors (|FixIt|) - Perform refactoring (|FixIt|) - Management of OmniSharp-Roslyn server instance - Renaming symbols ('RefactorRename ') - Code formatting (|Format|) ------------------------------------------------------------------------------- *youcompleteme-python* Python ~ - Semantic auto-completion - Signature help - Go to definition (|GoTo|) - Find Symbol ('GoToSymbol'), with interactive search - Reference finding (|GoToReferences|) - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Renaming symbols ('RefactorRename ') ------------------------------------------------------------------------------- *youcompleteme-go* Go ~ - Semantic auto-completion - Signature help - Real-time diagnostic display - Go to declaration/definition (|GoTo|, etc.) - Go to type definition (|GoToType|) - Go to implementation (|GoToImplementation|) - Document outline (|GoToDocumentOutline|), with interactive search - Automatically fix certain errors (|FixIt|) - Perform refactoring (|FixIt|) - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Code formatting (|Format|) - Management of 'gopls' server instance - Inlay hints - Call hierarchy ------------------------------------------------------------------------------- *youcompleteme-javascript-typescript* JavaScript and TypeScript ~ - Semantic auto-completion with automatic import insertion - Signature help - Real-time diagnostic display - Go to definition (|GoTo|, |GoToDefinition|, and |GoToDeclaration| are identical) - Go to type definition (|GoToType|) - Go to implementation (|GoToImplementation|) - Find Symbol ('GoToSymbol'), with interactive search - Reference finding (|GoToReferences|) - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Automatically fix certain errors and perform refactoring (|FixIt|) - Perform refactoring (|FixIt|) - Renaming symbols ('RefactorRename ') - Code formatting (|Format|) - Organize imports (|OrganizeImports|) - Management of 'TSServer' server instance - Inlay hints - Call hierarchy ------------------------------------------------------------------------------- *youcompleteme-rust* Rust ~ - Semantic auto-completion - Real-time diagnostic display - Go to declaration/definition (|GoTo|, etc.) - Go to implementation (|GoToImplementation|) - Reference finding (|GoToReferences|) - Document outline (|GoToDocumentOutline|), with interactive search - View documentation comments for identifiers (|GetDoc|) - Automatically fix certain errors (|FixIt|) - Perform refactoring (|FixIt|) - Type information for identifiers (|GetType|) - Renaming symbols ('RefactorRename ') - Code formatting (|Format|) - Management of 'rust-analyzer' server instance - Semantic highlighting - Inlay hints - Call hierarchy ------------------------------------------------------------------------------- *youcompleteme-java* Java ~ - Semantic auto-completion with automatic import insertion - Signature help - Real-time diagnostic display - Go to definition (|GoTo|, |GoToDefinition|, and |GoToDeclaration| are identical) - Go to type definition (|GoToType|) - Go to implementation (|GoToImplementation|) - Find Symbol ('GoToSymbol'), with interactive search - Reference finding (|GoToReferences|) - Document outline (|GoToDocumentOutline|), with interactive search - View documentation comments for identifiers (|GetDoc|) - Type information for identifiers (|GetType|) - Automatically fix certain errors including code generation (|FixIt|) - Renaming symbols ('RefactorRename ') - Code formatting (|Format|) - Organize imports (|OrganizeImports|) - Detection of Java projects - Execute custom server command ('ExecuteCommand ') - Management of 'jdt.ls' server instance - Semantic highlighting - Inlay hints - Type hierarchy - Call hierarchy ------------------------------------------------------------------------------- *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" and "smart-diacritic [43]" 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). On top of that, a letter with no diacritic marks will match that letter with or without marks: --------------------------------------------- | _matches_ | _foo_ | _fôo_ | _fOo_ | _fÔo_ | --------------------------------------------- | _foo_ | ✔️ | ✔️ | ✔️ | ✔️ | --------------------------------------------- | _fôo_ | ❌ | ✔️ | ❌ | ✔️ | --------------------------------------------- | _fOo_ | ❌ | ❌ | ✔️ | ✔️ | --------------------------------------------- | _fÔo_ | ❌ | ❌ | ❌ | ✔️ | --------------------------------------------- Use the TAB key to accept a completion and continue pressing TAB to cycle through the completions. Use Shift-TAB to cycle backward. 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 are libclang-based and clangd-based completers that provide 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 [44] 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 that 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). Word-boundary characters are all capital characters, characters preceded by an underscore, and the first letter character in the completion string. ------------------------------------------------------------------------------- *youcompleteme-signature-help* Signature Help ~ Valid signatures are displayed in a second popup menu and the current signature is highlighted along with the current argument. Signature help is triggered in insert mode automatically when |g:ycm_auto_trigger| is enabled and is not supported when it is not enabled. The signatures popup is hidden when there are no matching signatures or when you leave insert mode. If you want to manually control when it is visible, you can map something to 'YCMToggleSignatureHelp' (see below). For more details on this feature and a few demos, check out the PR that proposed it [45]. ------------------------------------------------------------------------------- *youcompleteme-dismiss-signature-help* Dismiss signature help ~ The signature help popup sometimes gets in the way. You can toggle its visibility with a mapping. YCM provides the "Plug" mapping '(YCMToggleSignatureHelp)' for this. For example, to hide/show the signature help popup by pressing Ctrl+l in insert mode: 'imap (YCMToggleSignatureHelp)'. _NOTE_: No default mapping is provided because insert mappings are very difficult to create without breaking or overriding some existing functionality. Ctrl-l is not a suggestion, just an example. ------------------------------------------------------------------------------- *youcompleteme-semantic-highlighting* Semantic highlighting ~ Semantic highlighting is the process where the buffer text is coloured according to the underlying semantic type of the word, rather than classic syntax highlighting based on regular expressions. This can be powerful additional data that we can process very quickly. This feature is only supported in Vim. For example, here is a function with classic highlighting: Image: highliting-classic (see reference [46]) And here is the same function with semantic highlighting: Image: highliting-semantic (see reference [47]) As you can see, the function calls, macros, etc. are correctly identified. This can be enabled globally with 'let g:ycm_enable_semantic_highlighting=1' or per buffer, by setting 'b:ycm_enable_semantic_highlighting'. ------------------------------------------------------------------------------- *youcompleteme-customising-highlight-groups* Customising the highlight groups ~ YCM uses text properties (see ':help text-prop-intro') for semantic highlighting. In order to customise the coloring, you can define the text properties that are used. If you define a text property named 'YCM_HL_', then it will be used in place of the defaults. The '' is defined as the Language Server Protocol semantic token type, defined in the LSP Spec [48]. Some servers also use custom values. In this case, YCM prints a warning including the token type name that you can customise. For example, to render 'parameter' tokens using the 'Normal' highlight group, you can do this: > call prop_type_add( 'YCM_HL_parameter', { 'highlight': 'Normal' } ) < More generally, this pattern can be useful for customising the groups: > let MY_YCM_HIGHLIGHT_GROUP = { \ 'typeParameter': 'PreProc', \ 'parameter': 'Normal', \ 'variable': 'Normal', \ 'property': 'Normal', \ 'enumMember': 'Normal', \ 'event': 'Special', \ 'member': 'Normal', \ 'method': 'Normal', \ 'class': 'Special', \ 'namespace': 'Special', \ } for tokenType in keys( MY_YCM_HIGHLIGHT_GROUP ) call prop_type_add( 'YCM_HL_' . tokenType, \ { 'highlight': MY_YCM_HIGHLIGHT_GROUP[ tokenType ] } ) endfor < ------------------------------------------------------------------------------- *youcompleteme-inlay-hints* Inlay hints ~ **NOTE**: Highly experimental feature, requiring Vim 9.0.214 or later (not supported in NeoVim). When 'g:ycm_enable_inlay_hints' (globally) or 'b:ycm_enable_inlay_hints' (for a specific buffer) is set to '1', then YCM will insert inlay hints as supported by the language semantic engine. An inlay hint is text that is rendered on the screen that is not part of the buffer and is often used to mark up the type or name of arguments, parameters, etc. which help the developer understand the semantics of the code. Here are some examples: - C Image: c-inlay (see reference [49]) - TypeScript Image: ts-inlay (see reference [50]) - Go Image: go-inlay (see reference [51]) ------------------------------------------------------------------------------- *youcompleteme-highlight-groups* Highlight groups ~ By default, YCM renders the inlay hints with the 'NonText' highlight group. To override this, define the 'YcmInlayHint' highlight yourself, e.g. in your '.vimrc': > hi link YcmInlayHint Comment < Similar to semantic highlighting above, you can override specific highlighting for different inlay hint types by defining text properties named after the kind of inlay hint, for example: > call prop_type_add( 'YCM_INLAY_Type', #{ highlight: 'Comment' } ) < The list of inlay hint kinds can be found in 'python/ycm/inlay_hints.py' ------------------------------------------------------------------------------- *youcompleteme-options* Options ~ - 'g:ycm_enable_inlay_hints' or 'b:ycm_enable_inlay_hints' - enable/disable globally or for local buffer - 'g:ycm_clear_inlay_hints_in_insert_mode' - set to '1' to remove all inlay hints when entering insert mode and reinstate them when leaving insert mode ------------------------------------------------------------------------------- *youcompleteme-toggling* Toggling ~ Inlay hints can add a lot of text to the screen and may be distracting. You can toggle them on/off instantly, by mapping something to '(YCMToggleInlayHints)', for example: > nnoremap h (YCMToggleInlayHints) < No default mapping is provided for this due to the personal nature of mappings. ------------------------------------------------------------------------------- *youcompleteme-general-semantic-completion* General Semantic Completion ~ You can use Ctrl+Space to trigger the completion suggestions anywhere, even without a string prefix. This is useful to see which top-level functions are available for use. ------------------------------------------------------------------------------- *youcompleteme-c-family-semantic-completion* C-family Semantic Completion ~ **NOTE:** YCM originally used the 'libclang' based engine for C-family, but users should migrate to clangd, as it provides more features and better performance. Users who rely on 'override_filename' in their '.ycm_extra_conf.py' will need to stay on the old 'libclang' engine. Instructions on how to stay on the old engine are available on the wiki [52]. Some of the features of clangd: - **Project wide indexing**: Clangd has both dynamic and static index support. The dynamic index stores up-to-date symbols coming from any files you are currently editing, whereas static index contains project-wide symbol information. This symbol information is used for code completion and code navigation. Whereas libclang is limited to the current translation unit(TU). - **Code navigation**: Clangd provides all the GoTo requests libclang provides and it improves those using the above-mentioned index information to contain project-wide information rather than just the current TU. - **Rename**: Clangd can perform semantic rename operations on the current file, whereas libclang doesn't support such functionality. - **Code Completion**: Clangd can perform code completions at a lower latency than libclang; also, it has information about all the symbols in your project so it can suggest items outside your current TU and also provides proper '#include' insertions for those items. - **Signature help**: Clangd provides signature help so that you can see the names and types of arguments when calling functions. - **Format Code**: Clangd provides code formatting either for the selected lines or the whole file, whereas libclang doesn't have such functionality. - **Performance**: Clangd has faster re-parse and code completion times compared to libclang. ------------------------------------------------------------------------------- Installation ~ On supported architectures, the 'install.py' script will download a suitable clangd ('--clangd-completer') or libclang ('--clang-completer') for you. Supported architectures are: - Linux glibc >= 2.39 (Intel, armv7-a, aarch64) - built on ubuntu 24.04 - MacOS >=10.15 (Intel, arm64) - For Intel, compatibility per clang.llvm.org downloads - For arm64, macOS 10.15+ - Windows (Intel) - compatibility per clang.llvm.org downloads **_clangd_**: Typically, clangd is installed by the YCM installer (either with '--all' or with '--clangd-completer'). This downloads a pre-built 'clangd' binary for your architecture. If your OS or architecture is not supported or is too old, you can install a compatible 'clangd' and use |g:ycm_clangd_binary_path| to point to it. **_libclang_**: 'libclang' can be enabled also with '--all' or '--clang-completer'. As with 'clangd', YCM will try and download a version of 'libclang' that is suitable for your environment, but again if your environment can't be supported, you can build or acquire 'libclang' for yourself and specify it when building, as: > $ EXTRA_CMAKE_ARGS='-DPATH_TO_LLVM_ROOT=/path/to/your/llvm' ./install.py --clang-completer --system-libclang < Please note that if using custom 'clangd' or 'libclang' it _must_ match the version that YCM requires. Currently YCM requires **_clang 17.0.1_**. ------------------------------------------------------------------------------- *youcompleteme-compile-flags* Compile flags ~ In order to perform semantic analysis such as code completion, |GoTo|, and diagnostics, YouCompleteMe uses 'clangd', which makes use of clang compiler, sometimes also referred to as LLVM. Like any compiler, clang also requires a set of compile flags in order to parse your code. Simply put: If clang can't parse your code, YouCompleteMe can't provide semantic analysis. There are 2 methods that can be used to provide compile flags to clang: ------------------------------------------------------------------------------- *youcompleteme-option-1-use-compilation-database-53* Option 1: Use a compilation database [53] ~ The easiest way to get YCM to compile your code is to use a compilation database. A compilation database is usually generated by your build system (e.g. 'CMake') and contains the compiler invocation for each compilation unit in your project. For information on how to generate a compilation database, see the clang documentation [53]. In short: - If using CMake, add '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON' when configuring (or add 'set( CMAKE_EXPORT_COMPILE_COMMANDS ON )' to 'CMakeLists.txt') and copy or symlink the generated database to the root of your project. - If using Ninja, check out the 'compdb' tool ('-t compdb') in its docs [54]. - If using GNU make, check out compiledb [55] or Bear [56]. - For other build systems, check out '.ycm_extra_conf.py' below. If no '.ycm_extra_conf.py' is found, YouCompleteMe automatically tries to load a compilation database if there is one. YCM looks for a file named 'compile_commands.json' in the directory of the opened file or in any directory above it in the hierarchy (recursively); when the file is found before a local '.ycm_extra_conf.py', YouCompleteMe stops searching the directories and lets clangd take over and handle the flags. ------------------------------------------------------------------------------- *youcompleteme-option-2-provide-flags-manually* Option 2: Provide the flags manually ~ If you don't have a compilation database or aren't able to generate one, you have to tell YouCompleteMe how to compile your code some other way. Every C-family project is different. It is not possible for YCM to guess what compiler flags to supply for your project. Fortunately, YCM provides a mechanism for you to generate the flags for a particular file with _arbitrary complexity_. This is achieved by requiring you to provide a Python module that implements a trivial function that, given the file name as an argument, returns a list of compiler flags to use to compile that file. 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 'Settings' 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 configuration file with the |g:ycm_global_ycm_extra_conf| option, 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 |g:ycm_confirm_extra_conf| and |g:ycm_extra_conf_globlist| options respectively. 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. **NOTE**: It is highly recommended to include '-x ' flag to libclang. This is so that the correct language is detected, particularly for header files. Common values are '-x c' for C, '-x c++' for C++, '-x objc' for Objective-C, and '-x cuda' for CUDA. To give you an impression, if your C++ project is trivial, and your usual compilation command is: 'g++ -Wall -Wextra -Werror -o FILE.o FILE.cc', then the following '.ycm_extra_conf.py' is enough to get semantic analysis from YouCompleteMe: > def Settings( **kwargs ): return { 'flags': [ '-x', 'c++', '-Wall', '-Wextra', '-Werror' ], } < As you can see from the trivial example, YCM calls the 'Settings' method which returns a dictionary with a single element "'flags'". This element is a 'list' of compiler flags to pass to libclang for the current file. The absolute path of that file is accessible under the 'filename' key of the 'kwargs' dictionary. That's it! This is actually enough for most projects, but for complex projects it is not uncommon to integrate directly with an existing build system using the full power of the Python language. For a more elaborate example, see ycmd's own '.ycm_extra_conf.py' [57]. 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. You could also consider using YCM-Generator [58] to generate the 'ycm_extra_conf.py' file. ------------------------------------------------------------------------------- *youcompleteme-errors-during-compilation* Errors during compilation ~ 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-java-semantic-completion* Java Semantic Completion ~ ------------------------------------------------------------------------------- *youcompleteme-java-quick-start* Java Quick Start ~ 1. Ensure that you have enabled the Java completer. See the installation guide for details. 2. Create a project file (gradle or maven) file in the root directory of your Java project, by following the instructions below. 3. (Optional) Configure the LSP server. The jdt.ls configuration options [59] can be found in their codebase. 4. If you previously used Eclim or Syntastic for Java, disable them for Java. 5. Edit a Java file from your project. ------------------------------------------------------------------------------- *youcompleteme-java-project-files* Java Project Files ~ In order to provide semantic analysis, the Java completion engine requires knowledge of your project structure. In particular, it needs to know the class path to use, when compiling your code. Fortunately jdt.ls [17] supports eclipse project files [60], maven projects [61] and gradle projects [62]. **NOTE:** Our recommendation is to use either Maven or Gradle projects. ------------------------------------------------------------------------------- *youcompleteme-diagnostic-display-syntastic* Diagnostic display - Syntastic ~ The native support for Java includes YCM's native real-time diagnostics display. This can conflict with other diagnostics plugins like Syntastic, so when enabling Java support, please **manually disable Syntastic Java diagnostics**. Add the following to your 'vimrc': > let g:syntastic_java_checkers = [] < ------------------------------------------------------------------------------- *youcompleteme-diagnostic-display-eclim* Diagnostic display - Eclim ~ The native support for Java includes YCM's native real-time diagnostics display. This can conflict with other diagnostics plugins like Eclim, so when enabling Java support, please **manually disable Eclim Java diagnostics**. Add the following to your 'vimrc': > let g:EclimFileTypeValidate = 0 < **NOTE**: We recommend disabling Eclim entirely when editing Java with YCM's native Java support. This can be done temporarily with ':EclimDisable'. ------------------------------------------------------------------------------- *youcompleteme-eclipse-projects* Eclipse Projects ~ Eclipse-style projects require two files: .project [60] and .classpath [63]. If your project already has these files due to previously being set up within Eclipse, then no setup is required. jdt.ls [17] should load the project just fine (it's basically eclipse after all). However, if not, it is possible (easy in fact) to craft them manually, though it is not recommended. You're better off using Gradle or Maven (see below). A simple eclipse style project example [64] can be found in the ycmd test directory. Normally all that is required is to copy these files to the root of your project and to edit the '.classpath' to add additional libraries, such as: > < It may also be necessary to change the directory in which your source files are located (paths are relative to the .project file itself): > < **NOTE**: The eclipse project and classpath files are not a public interface and it is highly recommended to use Maven or Gradle project definitions if you don't already use Eclipse to manage your projects. ------------------------------------------------------------------------------- *youcompleteme-maven-projects* Maven Projects ~ Maven needs a file named pom.xml [61] in the root of the project. Once again a simple pom.xml [65] can be found in the ycmd source. The format of pom.xml [61] files is way beyond the scope of this document, but we do recommend using the various tools that can generate them for you, if you're not familiar with them already. ------------------------------------------------------------------------------- *youcompleteme-gradle-projects* Gradle Projects ~ Gradle projects require a build.gradle [62]. Again, there is a trivial example in ycmd's tests [66]. The format of build.gradle [62] files are way beyond the scope of this document, but we do recommend using the various tools that can generate them for you if you're not familiar with them already. Some users have experienced issues with their jdt.ls when using the Groovy language for their build.gradle. As such, try using Kotlin [67] instead. ------------------------------------------------------------------------------- *youcompleteme-troubleshooting* Troubleshooting ~ If you're not getting completions or diagnostics, check the server health: - The Java completion engine takes a while to start up and parse your project. You should be able to see its progress in the command line, and |:YcmDebugInfo|. Ensure that the following lines are present: > -- jdt.ls Java Language Server running -- jdt.ls Java Language Server Startup Status: Ready < - If the above lines don't appear after a few minutes, check the jdt.ls and ycmd log files using |:YcmToggleLogs|. The jdt.ls log file is called '.log' (for some reason). If you get a message about "classpath is incomplete", then make sure you have correctly configured the project files. If you get messages about unresolved imports, then make sure you have correctly configured the project files, in particular check that the classpath is set correctly. ------------------------------------------------------------------------------- *youcompleteme-c-semantic-completion* C# Semantic Completion ~ YCM relies on OmniSharp-Roslyn [13] to provide completion and code navigation. OmniSharp-Roslyn needs a solution file for a C# project and there are two ways of letting YCM know about your solution files. ------------------------------------------------------------------------------- *youcompleteme-automatically-discovered-solution-files* Automatically discovered solution files ~ YCM will scan all parent directories of the file currently being edited and look for a file with '.sln' extension. ------------------------------------------------------------------------------- *youcompleteme-manually-specified-solution-files* Manually specified solution files ~ If YCM loads '.ycm_extra_conf.py' which contains 'CSharpSolutionFile' function, YCM will try to use that to determine the solution file. This is useful when one wants to override the default behaviour and specify a solution file that is not in any of the parent directories of the currently edited file. Example: > def CSharpSolutionFile( filepath ): # `filepath` is the path of the file user is editing return '/path/to/solution/file' # Can be relative to the `.ycm_extra_conf.py` < If the path returned by 'CSharpSolutionFile' is not an actual file, YCM will fall back to the other way of finding the file. ------------------------------------------------------------------------------- *youcompleteme-use-with-.net-6.0-.net-sdks* Use with .NET 6.0 and .NET SDKs ~ YCM ships with older version of OmniSharp-Roslyn based on Mono runtime. It is possible to use it with .NET 6.0 and newer, but it requires manual setup. 1. Download NET 6.0 version of the OmniSharp server for your system from releases [68] 2. Set |g:ycm_roslyn_binary_path| to the unpacked executable 'OmniSharp' 3. Create a solution file if one doesn't already exist, it is currently required by YCM for internal bookkeeping 1. Run 'dotnet new sln' at the root of your project 2. Run 'dotnet sln add ...' for all of your projects 4. Run |:YcmRestartServer| ------------------------------------------------------------------------------- *youcompleteme-python-semantic-completion* Python Semantic Completion ~ YCM relies on the Jedi [12] engine to provide completion and code navigation. By default, it will pick the version of Python running the ycmd server [44] and use its 'sys.path'. While this is fine for simple projects, this needs to be configurable when working with virtual environments or in a project with third-party packages. The next sections explain how to do that. ------------------------------------------------------------------------------- *youcompleteme-working-with-virtual-environments* Working with virtual environments ~ A common practice when working on a Python project is to install its dependencies in a virtual environment and develop the project inside that environment. To support this, YCM needs to know the interpreter path of the virtual environment. You can specify it by creating a '.ycm_extra_conf.py' file at the root of your project with the following contents: > def Settings( **kwargs ): return { 'interpreter_path': '/path/to/virtual/environment/python' } < Here, '/path/to/virtual/environment/python' is the path to the Python used by the virtual environment you are working in. Typically, the executable can be found in the 'Scripts' folder of the virtual environment directory on Windows and in the 'bin' folder on other platforms. If you don't like having to create a '.ycm_extra_conf.py' file at the root of your project and would prefer to specify the interpreter path with a Vim option, read the Configuring through Vim options section. ------------------------------------------------------------------------------- *youcompleteme-working-with-third-party-packages* Working with third-party packages ~ Another common practice is to put the dependencies directly into the project and add their paths to 'sys.path' at runtime in order to import them. YCM needs to be told about this path manipulation to support those dependencies. This can be done by creating a '.ycm_extra_conf.py' file at the root of the project. This file must define a 'Settings( **kwargs )' function returning a dictionary with the list of paths to prepend to 'sys.path' under the 'sys_path' key. For instance, the following '.ycm_extra_conf.py' adds the paths '/path/to/some/third_party/package' and '/path/to/another/third_party/package' at the start of 'sys.path': > def Settings( **kwargs ): return { 'sys_path': [ '/path/to/some/third_party/package', '/path/to/another/third_party/package' ] } < If you would rather prepend paths to 'sys.path' with a Vim option, read the Configuring through Vim options section. If you need further control on how to add paths to 'sys.path', you should define the 'PythonSysPath( **kwargs )' function in the '.ycm_extra_conf.py' file. Its keyword arguments are 'sys_path' which contains the default 'sys.path', and 'interpreter_path' which is the path to the Python interpreter. Here's a trivial example that inserts the '/path/to/third_party/package' path at the second position of 'sys.path': > def PythonSysPath( **kwargs ): sys_path = kwargs[ 'sys_path' ] sys_path.insert( 1, '/path/to/third_party/package' ) return sys_path < A more advanced example can be found in YCM's own '.ycm_extra_conf.py' [69]. ------------------------------------------------------------------------------- *youcompleteme-configuring-through-vim-options* Configuring through Vim options ~ You may find it inconvenient to have to create a '.ycm_extra_conf.py' file at the root of each one of your projects in order to set the path to the Python interpreter and/or add paths to 'sys.path' and would prefer to be able to configure those through Vim options. Don't worry, this is possible by using the |g:ycm_extra_conf_vim_data| option and creating a global extra configuration file. Let's take an example. Suppose that you want to set the interpreter path with the 'g:ycm_python_interpreter_path' option and prepend paths to 'sys.path' with the 'g:ycm_python_sys_path' option. Suppose also that you want to name the global extra configuration file 'global_extra_conf.py' and that you want to put it in your HOME folder. You should then add the following lines to your vimrc: > let g:ycm_python_interpreter_path = '' let g:ycm_python_sys_path = [] let g:ycm_extra_conf_vim_data = [ \ 'g:ycm_python_interpreter_path', \ 'g:ycm_python_sys_path' \] let g:ycm_global_ycm_extra_conf = '~/global_extra_conf.py' < Then, create the '~/global_extra_conf.py' file with the following contents: > def Settings( **kwargs ): client_data = kwargs[ 'client_data' ] return { 'interpreter_path': client_data[ 'g:ycm_python_interpreter_path' ], 'sys_path': client_data[ 'g:ycm_python_sys_path' ] } < That's it. You are done. Note that you don't need to restart the server when setting one of the options. YCM will automatically pick the new values. ------------------------------------------------------------------------------- *youcompleteme-rust-semantic-completion* Rust Semantic Completion ~ YCM uses rust-analyzer [16] for Rust semantic completion. NOTE: Previously, YCM used rls [70] for rust completion. This is no longer supported, as the Rust community has decided on rust-analyzer [16] as the future of Rust tooling. Completions and GoTo commands within the current crate and its dependencies should work out of the box with no additional configuration (provided that you built YCM with the '--rust-completer' flag; see the _Installation_ section for details). The install script takes care of installing the Rust source code [71], so no configuration is necessary. 'rust-analyzer' supports a myriad of options. These are configured using LSP configuration, and are documented here [72]. ------------------------------------------------------------------------------- *youcompleteme-go-semantic-completion* Go Semantic Completion ~ Completions and GoTo commands should work out of the box (provided that you built YCM with the '--go-completer' flag; see the _Installation_ section for details). The server only works for projects with the "canonical" layout. 'gopls' also has a load of documented options [73]. You can set these in your '.ycm_extra_conf.py'. For example, to set the build tags: > def Settings( **kwargs ): if kwargs[ 'language' ] == 'go': return { 'ls': { 'build.buildFlags': [ '-tags=debug' ] } } } < ------------------------------------------------------------------------------- *youcompleteme-javascript-typescript-semantic-completion* JavaScript and TypeScript Semantic Completion ~ **NOTE:** YCM originally used the Tern [74] engine for JavaScript but due to Tern [74] not being maintained anymore by its main author and the TSServer [15] engine offering more features, YCM is moving to TSServer [15]. This won't affect you if you were already using Tern [74] but you are encouraged to do the switch by deleting the 'third_party/ycmd/third_party/tern_runtime/node_modules' directory in YCM folder. If you are a new user but still want to use Tern [74], you should pass the '--js-completer' option to the 'install.py' script during installation. Further instructions on how to set up YCM with Tern [74] are available on the wiki [75]. All JavaScript and TypeScript features are provided by the TSServer [15] engine, which is included in the TypeScript SDK. To enable these features, install Node.js 18+ and npm [32] and call the 'install.py' script with the '--ts-completer' flag. TSServer [15] relies on the 'jsconfig.json' file [76] for JavaScript and the 'tsconfig.json' file [77] for TypeScript to analyze your project. Ensure the file exists at the root of your project. To get diagnostics in JavaScript, set the 'checkJs' option to 'true' in your 'jsconfig.json' file: > { "compilerOptions": { "checkJs": true } } < ------------------------------------------------------------------------------- *youcompleteme-semantic-completion-for-other-languages* Semantic Completion for Other Languages ~ C-family, C#, Go, Java, Python, Rust, and JavaScript/TypeScript languages are supported natively by YouCompleteMe using the Clang [78], OmniSharp-Roslyn [13], Gopls [14], jdt.ls [17], Jedi [12], rust-analyzer [16], and TSServer [15] engines, respectively. Check the installation section for instructions to enable these features if desired. ------------------------------------------------------------------------------- *youcompleteme-plugging-an-arbitrary-lsp-server* Plugging an arbitrary LSP server ~ Similar to other LSP clients, YCM can use an arbitrary LSP server with the help of |g:ycm_language_server| option. An example of a value of this option would be: > let g:ycm_language_server = \ [ \ { \ 'name': 'yaml', \ 'cmdline': [ '/path/to/yaml/server/yaml-language-server', '--stdio' ], \ 'filetypes': [ 'yaml' ] \ }, \ { \ 'name': 'csharp', \ 'cmdline': [ 'OmniSharp', '-lsp' ], \ 'filetypes': [ 'csharp' ], \ 'project_root_files': [ '*.csproj', '*.sln' ] \ }, \ { \ 'name': 'godot', \ 'filetypes': [ 'gdscript' ], \ 'port': 6008, \ 'project_root_files': [ 'project.godot' ] \ } \ ] < Each dictionary contains the following keys: 'name', 'cmdline', 'port', 'filetypes', 'capabilities', 'project_root_files', 'additional_workspace_dirs', 'triggerCharacters', and 'settings'. The full description of each key can be found in the ycmd [79] repository. See the LSP Examples [80] project for more examples of configuring the likes of PHP, Ruby, Kotlin, and D. ------------------------------------------------------------------------------- *youcompleteme-lsp-configuration* LSP Configuration ~ Many LSP servers allow some level of user configuration. YCM enables this with the help of '.ycm_extra_conf.py' files. Here's an example of jdt.ls user examples of configuring the likes of PHP, Ruby, Kotlin, D, and many, many more. > def Settings( **kwargs ): if kwargs[ 'language' ] == 'java': return { 'ls': { 'java.format.onType.enabled': True } } < The 'ls' key tells YCM that the dictionary should be passed to the LSP server. For each of the LSP server's configuration, you should look up the respective server's documentation. Some servers request settings from arbitrary 'sections' of configuration. There is no concept of configuration sections in Vim, so you can specify an additional 'config_sections' dictionary which maps section to a dictionary of config required by the server. For example: > def Settings( **kwargs ): if kwargs[ 'language' ] == 'java': return { 'ls': { 'java.format.onType.enabled': True }, 'config_sections': { 'some section': { 'some option': 'some value' } } < The sections and options/values are completely server-specific and rarely well documented. ------------------------------------------------------------------------------- *youcompleteme-using-omnifunc-for-semantic-completion* Using 'omnifunc' for semantic completion ~ 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 rudimentary omnifuncs for various languages like Ruby, PHP, etc. It depends on the language. You can get a stellar omnifunc for Ruby with Eclim [81]. 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' 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 [82]. 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 [82]. If you want to upstream your completer into YCM's source, you should use the Completer API. ------------------------------------------------------------------------------- *youcompleteme-diagnostic-display* Diagnostic Display ~ YCM will display diagnostic notifications for the C-family, C#, Go, Java, JavaScript, Rust, and TypeScript languages. 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 [83] (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 Finally, you can also style the popup for the detailed diagnostics (it is shown if |g:ycm_show_detailed_diag_in_popup| is set) using the group 'YcmErrorPopup', which falls back to 'ErrorMsg'. Note that the line highlighting groups only work when the |g:ycm_enable_diagnostic_signs| option is set. If you want highlighted lines but no signs in the Vim gutter, set the 'signcolumn' option to 'no' in your vimrc: > set signcolumn=no < The syntax groups used to highlight regions of text with errors/warnings: - 'YcmErrorSection', which falls back to group 'SyntasticError' if it exists and then 'SpellBad' - 'YcmWarningSection', which falls back to group 'SyntasticWarning' if it exists and then 'SpellCap' Here's how you'd change the style for a group: > highlight YcmErrorLine guibg=#3f0000 < ------------------------------------------------------------------------------- *youcompleteme-symbol-search* Symbol Search ~ **_This feature requires Vim and is not supported in Neovim_** YCM provides a way to search for and jump to a symbol in the current project or document when using supported languages. You can search for symbols in the current workspace when the 'GoToSymbol' request is supported and the current document when |GoToDocumentOutline| is supported. Here's a quick demo: Image: asciicast [84] As you can see, you can type and YCM filters down the list as you type. The current set of matches are displayed in a popup window in the centre of the screen and you can select an entry with the keyboard, to jump to that position. Any matches are then added to the quickfix list. To enable: - 'nmap (YCMFindSymbolInWorkspace)' - 'nmap (YCMFindSymbolInDocument)' e.g. - 'nmap yfw (YCMFindSymbolInWorkspace)' - 'nmap yfd (YCMFindSymbolInDocument)' When searching, YCM opens a prompt buffer at the top of the screen for the input and puts you in insert mode. This means that you can hit '' to go into normal mode and use any other input commands that are supported in prompt buffers. As you type characters, the search is updated. Initially, results are queried from all open filetypes. You can hit '' to switch to just the current filetype while the popup is open. While the popup is open, the following keys are intercepted: - '', '', '', '' - select the next item - '', '', '', '' - select the previous item - '', '' - jump up one screenful of items - '', '' - jump down one screenful of items - '', '' - jump to first item - '', '' - jump to last item - '' - jump to the selected item - '' cancel/dismiss the popup - '' - toggle results from all file types or just the current filetype The search is also cancelled if you leave the prompt buffer window at any time, so you can use window commands '...' for example. ------------------------------------------------------------------------------- *youcompleteme-closing-popup* Closing the popup ~ **_NOTE_**: Pressing '' does not close the popup - you must use 'Ctrl-c' for that, or use a window command (e.g. 'j') or the mouse to leave the prompt buffer window. ------------------------------------------------------------------------------- *youcompleteme-type-call-hierarchy* Type/Call Hierarchy ~ **_This feature requires Vim and is not supported in Neovim_** **NOTE**: This feature is highly experimental and offered in the hope that it is useful. Please help us by reporting issues and offering feedback. YCM provides a way to view and navigate hierarchies. The following hierarchies are supported: - Type hierachy '(YCMTypeHierarchy)': Display subtypes and supertypes of the symbol under cursor. Expand down to subtypes and up to supertypes. - Call hierarchy '(YCMCallHierarchy)': Display callees and callers of the symbol under cursor. Expand down to callers and up to callees. Take a look at this Image: asciicast [86] for brief demo. Hierarchy UI can be initiated by mapping something to the indicated plug mappings, for example: > nmap yth (YCMTypeHierarchy) nmap ych (YCMCallHierarchy) < This opens a "modal" popup showing the current element in the hierarchy tree. The current tree root is aligned to the left and child and parent nodes are expanded to the right. Expand the tree "down" with '' and "up" with ''. The "root" of the tree can be re-focused to the selected item with '' and further '' will show the parents of the selected item. This can take a little getting used to, but it's particularly important with multiple inheritance where a "child" of the current root may actually have other, invisible, parent links. '' on that row will show these by setting the display root to the selected item. When the hierarchy is displayed, the following keys are intercepted: - '': Drill into the hierarchy at the selected item: expand and show children of the selected item. - '': Show parents of the selected item. When applied to sub-types, this will re-root the tree at that type, so that all parent types (are displayed). Similar for callers. - '': Jump to the symbol currently selected. - '', '', '', 'j': Select the next item - '', '', '', 'k'; Select the previous item - Any other key: closes the popup without jumping to any location **Note:** you might think the call hierarchy tree is inverted, but we think this way round is more intuitive because this is the typical way that call stacks are displayed (with the current function at the top, and its callers below). ------------------------------------------------------------------------------- *youcompleteme-commands* Commands ~ ------------------------------------------------------------------------------- The *:YcmRestartServer* command If the ycmd completion server [44] 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. If a given error or warning can be fixed by a call to ':YcmCompleter FixIt', then '(FixIt available)' is appended to the error or warning text. See the |FixIt| completer subcommand for more information. **NOTE:** The absence of '(FixIt available)' does not strictly imply a fix-it is not available as not all completers are able to provide this indication. For example, the c-sharp completer provides many fix-its but does not add this additional indication. The |g:ycm_open_loclist_on_ycm_diags| option can be used to prevent the location list from opening, but still have it filled with new diagnostic data. See the _Options_ section for details. ------------------------------------------------------------------------------- The *:YcmShowDetailedDiagnostic* command This command shows the full diagnostic text when the user's cursor is on the line with the diagnostic. An options argument can be passed. If the argument is 'popup' the diagnostic text will be displayed in a popup at the cursor position. If you prefer the detailed diagnostic to always be shown in a popup, then 'let g:ycm_show_detailed_diag_in_popup=1'. ------------------------------------------------------------------------------- The *:YcmDebugInfo* command This will print out various debug information for the current file. Useful to see what compile commands will be used for the file if you're using the semantic completion engine. ------------------------------------------------------------------------------- The *:YcmToggleLogs* command This command presents the list of logfiles created by YCM, the ycmd server [44], and the semantic engine server for the current filetype, if any. One of these logfiles can be opened in the editor (or closed if already open) by entering the corresponding number or by clicking on it with the mouse. Additionally, this command can take the logfile names as arguments. Use the '' key (or any other key defined by the 'wildchar' option) to complete the arguments or to cycle through them (depending on the value of the 'wildmode' option). Each logfile given as an argument is directly opened (or closed if already open) in the editor. Only for debugging purposes. ------------------------------------------------------------------------------- The *:YcmCompleter* command This command gives access to a number of additional IDE-like features in YCM, for things like semantic GoTo, type information, FixIt, and refactoring. This command accepts a range that can either be specified through a selection in one of Vim's visual modes (see ':h visual-use') or on the command line. For instance, ':2,5YcmCompleter' will apply the command from line 2 to line 5. This is useful for the |Format| subcommand. Call 'YcmCompleter' without further arguments for a list of the commands you can call for the current completer. See the file type feature summary for an overview of the features available for each file type. See the _YcmCompleter subcommands_ section for more information on the available subcommands and their usage. Some commands, like |Format| accept a range, like ':%YcmCompleter Format'. Some commands like |GetDoc| and the various |GoTo| commands respect modifiers, like ':rightbelow YcmCompleter GetDoc', ':vertical YcmCompleter GoTo'. ------------------------------------------------------------------------------- *youcompleteme-ycmcompleter-subcommands* YcmCompleter Subcommands ~ **NOTE:** See the docs for the 'YcmCompleter' command before tackling this section. The invoked subcommand is automatically routed to the currently active semantic completer, so ':YcmCompleter GoToDefinition' will invoke the |GoToDefinition| subcommand on the Python semantic completer if the currently active file is a Python one and on the Clang completer if the currently active file is a C-family language one. You may also want to map the subcommands to something less verbose; for instance, 'nnoremap jd :YcmCompleter GoTo' maps the 'jd' sequence to the longer subcommand invocation. ------------------------------------------------------------------------------- *youcompleteme-goto-commands* GoTo Commands ~ These commands are useful for jumping around and exploring code. When moving the cursor, the subcommands add entries to Vim's 'jumplist' so you can use 'CTRL-O' to jump back to where you were before invoking the command (and 'CTRL-I' to jump forward; see ':h jumplist' for details). If there is more than one destination, the quickfix list (see ':h quickfix') is populated with the available locations and opened to the full width at the bottom of the screen. You can change this behavior by using the |YcmQuickFixOpened| autocommand. ------------------------------------------------------------------------------- The *GoToInclude* subcommand Looks up the current line for a header and jumps to it. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' ------------------------------------------------------------------------------- The *GoToAlternateFile* subcommand Jump to the associated file, as defined by the language server. Typically this will jump you to the associated header file for a C or C++ translation unit. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' (clangd only) ------------------------------------------------------------------------------- The *GoToDeclaration* subcommand Looks up the symbol under the cursor and jumps to its declaration. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript' ------------------------------------------------------------------------------- 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, cuda, cs, go, java, javascript, python, rust, typescript' ------------------------------------------------------------------------------- The *GoTo* subcommand This command tries to perform the "most sensible" GoTo operation it can. Currently, this means that it tries to look up the symbol under the cursor and jumps to its definition if possible; if the definition is not accessible from the current translation unit, jumps to the symbol's declaration. For C-family languages, it first tries to look up the current line for a header and jump to it. For C#, implementations are also considered and preferred. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, rust, typescript' ------------------------------------------------------------------------------- The *GoToImprecise* subcommand WARNING: This command trades correctness for speed! Same as the |GoTo| command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take time to compile but you know that you haven't made any changes since the last parse that would lead to incorrect jumps. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' ------------------------------------------------------------------------------- *GoToSymbol-symbol-query* The 'GoToSymbol ' subcommand ~ Finds the definition of all symbols matching a specified string. Note that this does not use any sort of smart/fuzzy matching. However, an interactive symbol search is also available. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, java, javascript, python, typescript' ------------------------------------------------------------------------------- The *GoToReferences* subcommand This command attempts to find all of the references within the project to the identifier under the cursor and populates the quickfix list with those locations. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust' ------------------------------------------------------------------------------- The *GoToImplementation* subcommand Looks up the symbol under the cursor and jumps to its implementation (i.e. non-interface). If there are multiple implementations, instead provides a list of implementations to choose from. Supported in filetypes: 'cs, go, java, rust, typescript, javascript' ------------------------------------------------------------------------------- The *GoToImplementationElseDeclaration* subcommand Looks up the symbol under the cursor and jumps to its implementation if one, else jump to its declaration. If there are multiple implementations, instead provides a list of implementations to choose from. Supported in filetypes: 'cs' ------------------------------------------------------------------------------- The *GoToType* subcommand Looks up the symbol under the cursor and jumps to the definition of its type e.g. if the symbol is an object, go to the definition of its class. Supported in filetypes: 'go, java, javascript, typescript' ------------------------------------------------------------------------------- The *GoToDocumentOutline* subcommand Provides a list of symbols in the current document, in the quickfix list. See also interactive symbol search. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, go, java, rust' ------------------------------------------------------------------------------- The *GoToCallers* and 'GoToCallees' subcommands Note: A much more powerful call and type hierarchy can be viewd interactively. See interactive type and call hierarchy. Populate the quickfix list with the callers, or callees respectively, of the function associated with the current cursor position. The semantics of this differ depending on the filetype and language server. Only supported for LSP servers that provide the 'callHierarchyProvider' capability. ------------------------------------------------------------------------------- *youcompleteme-semantic-information-commands* Semantic Information Commands ~ These commands are useful for finding static information about the code, such as the types of variables, viewing declarations, and documentation strings. ------------------------------------------------------------------------------- The *GetType* subcommand Echos the type of the variable or method under the cursor, and where it differs, the derived type. For example: > std::string s; < Invoking this command on 's' returns 'std::string => std::basic_string' **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, java, javascript, go, python, typescript, rust' ------------------------------------------------------------------------------- The *GetTypeImprecise* subcommand WARNING: This command trades correctness for speed! Same as the |GetType| command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take time to compile but you know that you haven't made any changes since the last parse that would lead to incorrect type. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' ------------------------------------------------------------------------------- The *GetParent* subcommand Echos the semantic parent of the point under the cursor. The semantic parent is the item that semantically contains the given position. For example: > class C { void f(); }; void C::f() { } < In the out-of-line definition of 'C::f', the semantic parent is the class 'C', of which this function is a member. In the example above, both declarations of 'C::f' have 'C' as their semantic context, while the lexical context of the first 'C::f' is 'C' and the lexical context of the second 'C::f' is the translation unit. For global declarations, the semantic parent is the translation unit. **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' ------------------------------------------------------------------------------- The *GetDoc* subcommand Displays the preview window populated with quick info about the identifier under the cursor. Depending on the file type, this includes things like: - The type or declaration of identifier, - Doxygen/javadoc comments, - Python docstrings, - etc. The documentation is opened in the preview window, and options like 'previewheight' are respected. If you would like to customise the height and position of this window, we suggest a custom command that: - Sets 'previewheight' temporarily - Runs the |GetDoc| command with supplied modifiers - Restores 'previewheight'. For example: > command -count ShowDocWithSize \ let g:ph=&previewheight \ set previewheight= \ YcmCompleter GetDoc \ let &previewheight=g:ph < You can then use something like ':botright vertical 80ShowDocWithSize'. Here's an example of that: https://asciinema.org/a/hE6Pi1gU6omBShwFna8iwGEe9 Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, go, java, javascript, python, typescript, rust' ------------------------------------------------------------------------------- The *GetDocImprecise* subcommand WARNING: This command trades correctness for speed! Same as the |GetDoc| command except that it doesn't recompile the file with libclang before looking up nodes in the AST. This can be very useful when you're editing files that take long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect docs. When you're just browsing around your codebase, this command can spare you quite a bit of latency. Supported in filetypes: 'c, cpp, objc, objcpp, cuda' ------------------------------------------------------------------------------- *youcompleteme-refactoring-commands* Refactoring Commands ~ These commands make changes to your source code in order to perform refactoring or code correction. YouCompleteMe does not perform any action which cannot be undone, and never saves or writes files to the disk. ------------------------------------------------------------------------------- The *FixIt* subcommand Where available, attempts to make changes to the buffer to correct diagnostics, or perform refactoring, on the current line or selection. Where multiple suggestions are available (such as when there are multiple ways to resolve a given warning, or where multiple diagnostics are reported for the current line, or multiple refactoring tweaks are available), the options are presented and one can be selected. Completers that provide diagnostics may also provide trivial modifications to the source in order to correct the diagnostic. Examples include syntax errors such as missing trailing semi-colons, spurious characters, or other errors which the semantic engine can deterministically suggest corrections. A small demo presenting how diagnostics can be fixed with clangd: Image: YcmCompleter-FixIt-OnDiagnostic (see reference [88]) Completers (LSPs) may also provide refactoring tweaks, which may be available even when no diagnostic is presented for the current line. These include function extraction, variable extraction, 'switch' population, constructor generation, ... The tweaks work for a selection as well. Consult your LSP for available refactorings. A demonstration of refactoring capabilities with clangd: Image: YouCompleter-FixIt-Refactoring (see reference [89]) If no fix-it is available for the current line, or there is no diagnostic on the current line, this command has no effect on the current buffer. If any modifications are made, the number of changes made to the buffer is echo'd and the user may use the editor's undo command to revert. When a diagnostic is available, and |g:ycm_echo_current_diagnostic| is enabled, then the text '(FixIt)' is appended to the echo'd diagnostic when the completer is able to add this indication. The text '(FixIt available)' is also appended to the diagnostic text in the output of the |:YcmDiags| command for any diagnostics with available fix-its (where the completer can provide this indication). **NOTE:** Causes re-parsing of the current translation unit. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript' ------------------------------------------------------------------------------- *RefactorRename-new-name* The 'RefactorRename ' subcommand ~ In supported file types, this command attempts to perform a semantic rename of the identifier under the cursor. This includes renaming declarations, definitions, and usages of the identifier, or any other language-appropriate action. The specific behavior is defined by the semantic engine in use. Similar to |FixIt|, this command applies automatic modifications to your source files. Rename operations may involve changes to multiple files, which may or may not be open in Vim buffers at the time. YouCompleteMe handles all of this for you. The behavior is described in the following section. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust, cs' ------------------------------------------------------------------------------- *youcompleteme-python-refactorings* Python refactorings ~ The following additional commands are supported for Python: - 'RefactorInline' - 'RefactorExtractVariable' - 'RefactorExtractFunction' See the jedi docs [90] for what they do. Supported in filetypes: 'python' ------------------------------------------------------------------------------- *youcompleteme-multi-file-refactor* Multi-file Refactor ~ When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts to apply those modifications to any existing open, visible buffer in the current tab. If no such buffer can be found, YouCompleteMe opens the file in a new small horizontal split at the top of the current window, applies the change, and then _hides_ the window. **NOTE:** The buffer remains open, and must be manually saved. A confirmation dialog is opened prior to doing this to remind you that this is about to happen. Once the modifications have been made, the quickfix list (see ':help quickfix') is populated with the locations of all modifications. This can be used to review all automatic changes made by using ':copen'. Typically, use the 'CTRL-W ' combination to open the selected file in a new split. It is possible to customize how the quickfix window is opened by using the |YcmQuickFixOpened| autocommand. The buffers are _not_ saved automatically. That is, you must save the modified buffers manually after reviewing the changes from the quickfix list. Changes can be undone using Vim's powerful undo features (see ':help undo'). Note that Vim's undo is per-buffer, so to undo all changes, the undo commands must be applied in each modified buffer separately. **NOTE:** While applying modifications, Vim may find files that are already open and have a swap file. The command is aborted if you select Abort or Quit in any such prompts. This leaves the Refactor operation partially complete and must be manually corrected using Vim's undo features. The quickfix list is _not_ populated in this case. Inspect ':buffers' or equivalent (see ':help buffers') to see the buffers that were opened by the command. ------------------------------------------------------------------------------- The *Format* subcommand This command formats the whole buffer or some part of it according to the value of the Vim options 'shiftwidth' and 'expandtab' (see ":h 'sw'" and ':h et' respectively). To format a specific part of your document, you can either select it in one of Vim's visual modes (see ':h visual-use') and run the command or directly enter the range on the command line, e.g. ':2,5YcmCompleter Format' to format it from line 2 to line 5. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, java, javascript, go, typescript, rust, cs' ------------------------------------------------------------------------------- The *OrganizeImports* subcommand This command removes unused imports and sorts imports in the current file. It can also group imports from the same module in TypeScript and resolve imports in Java. Supported in filetypes: 'java, javascript, typescript' ------------------------------------------------------------------------------- *youcompleteme-miscellaneous-commands* Miscellaneous Commands ~ These commands are for general administration, rather than IDE-like features. They cover things like the semantic engine server instance and compilation flags. ------------------------------------------------------------------------------- *ExecuteCommand-args* The 'ExecuteCommand ' subcommand ~ Some LSP completers (currently only Java completers) support executing server-specific commands. Consult the jdt.ls [17] documentation to find out what commands are supported and which arguments are expected. The support for 'ExecuteCommand' was implemented to support plugins like Vimspector [91] to debug java, but isn't limited to that specific use case. ------------------------------------------------------------------------------- The *RestartServer* subcommand Restarts the downstream semantic engine server for those semantic engines that work as separate servers that YCM talks to. Supported in filetypes: 'c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript' ------------------------------------------------------------------------------- The *ReloadSolution* subcommand Instruct the Omnisharp-Roslyn server to clear its cache and reload all files from the disk. This is useful when files are added, removed, or renamed in the solution, files are changed outside of Vim, or whenever Omnisharp-Roslyn cache is out-of-sync. Supported in filetypes: 'cs' ------------------------------------------------------------------------------- *youcompleteme-functions* Functions ~ ------------------------------------------------------------------------------- The *youcompleteme#GetErrorCount* function Get the number of YCM Diagnostic errors. If no errors are present, this function returns 0. For example: > call youcompleteme#GetErrorCount() < Both this function and |youcompleteme#GetWarningCount| can be useful when integrating YCM with other Vim plugins. For example, a lightline [92] user could add a diagnostics section to their statusline which would display the number of errors and warnings. ------------------------------------------------------------------------------- The *youcompleteme#GetWarningCount* function Get the number of YCM Diagnostic warnings. If no warnings are present, this function returns 0. For example: > call youcompleteme#GetWarningCount() < ------------------------------------------------------------------------------- *youcompleteme#GetCommandResponse()* The 'youcompleteme#GetCommandResponse( ... )' function ~ Run a completer subcommand and return the result as a string. This can be useful for example to display the |GetDoc| output in a popup window, e.g.: > let s:ycm_hover_popup = -1 function s:Hover() let response = youcompleteme#GetCommandResponse( 'GetDoc' ) if response == '' return endif call popup_hide( s:ycm_hover_popup ) let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} ) endfunction " CursorHold triggers in normal mode after a delay autocmd CursorHold * call s:Hover() " Or, if you prefer, a mapping: nnoremap D :call Hover() < **NOTE**: This is only an example, for real hover support, see |g:ycm_auto_hover|. If the completer subcommand result is not a string (for example, it's a FixIt or a Location), or if the completer subcommand raises an error, an empty string is returned, so that calling code does not have to check for complex error conditions. The arguments to the function are the same as the arguments to the |:YcmCompleter| ex command, e.g. the name of the subcommand, followed by any additional subcommand arguments. As with the 'YcmCompleter' command, if the first argument is 'ft=' the request is targeted at the specified filetype completer. This is an advanced usage and not necessary in most cases. NOTE: The request is run synchronously and blocks Vim until the response is received, so we do not recommend running this as part of an autocommand that triggers frequently. ------------------------------------------------------------------------------- *youcompleteme#GetCommandResponseAsync()* The 'youcompleteme#GetCommandResponseAsync( callback, ... )' function ~ This works exactly like 'youcompleteme#GetCommandResponse', except that instead of returning the result, you supply a 'callback' argument. This argument must be a 'FuncRef' to a function taking a single argument 'response'. This callback will be called with the command response at some point later, or immediately. As with |youcompleteme#GetCommandResponse()|, this function will call the callback with "''" (an empty string) if the request is not sent, or if there was some sort of error. Here's an example that's similar to the one above: > let s:ycm_hover_popup = -1 function! s:ShowDataPopup( response ) abort if response == '' return endif call popup_hide( s:ycm_hover_popup ) let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} ) endfunction function! s:GetData() abort call youcompleteme#GetCommandResponseAsync( \ function( 's:ShowDataPopup' ), \ 'GetDoc' ) endfunction autocommand CursorHold * call s:GetData() < Again, see |g:ycm_auto_hover| for proper hover support. **NOTE**: The callback may be called immediately, in the stack frame that called this function. **NOTE**: Only one command request can be outstanding at once. Attempting to request a second response while the first is outstanding will result in the second callback being immediately called with "''". ------------------------------------------------------------------------------- *youcompleteme-autocommands* Autocommands ~ ------------------------------------------------------------------------------- The *YcmLocationOpened* autocommand This 'User' autocommand is fired when YCM opens the location list window in response to the 'YcmDiags' command. By default, the location list window is opened to the bottom of the current window and its height is set to fit all entries. This behavior can be overridden by using the |YcmLocationOpened| autocommand which is triggered while the cursor is in the location list window. For instance: > function! s:CustomizeYcmLocationWindow() " Move the window to the top of the screen. wincmd K " Set the window height to 5. 5wincmd _ " Switch back to the working window. wincmd p endfunction autocmd User YcmLocationOpened call s:CustomizeYcmLocationWindow() < ------------------------------------------------------------------------------- The *YcmQuickFixOpened* autocommand This 'User' autocommand is fired when YCM opens the quickfix window in response to the 'GoTo*' and 'RefactorRename' subcommands. By default, the quickfix window is opened to full width at the bottom of the screen and its height is set to fit all entries. This behavior can be overridden by using the |YcmQuickFixOpened| autocommand which is triggered while the cursor is in the quickfix window. For instance: > function! s:CustomizeYcmQuickFixWindow() " Move the window to the top of the screen. wincmd K " Set the window height to 5. 5wincmd _ endfunction autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow() < ------------------------------------------------------------------------------- Options ~ All options have reasonable defaults so if the plug-in works after installation you don't need to change any options. These options can be configured in your vimrc script [37] 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 [37] you have to restart ycmd [44] with the |:YcmRestartServer| command 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_max_num_candidates* option This option controls the maximum number of semantic completion suggestions shown in the completion menu. This only applies to suggestions from semantic completion engines; see the 'g:ycm_max_identifier_candidates' option to limit the number of suggestions from the identifier-based engine. A special value of '0' means there is no limit. **NOTE:** Setting this option to '0' or to a value greater than '100' is not recommended as it will slow down completion when there is a very large number of suggestions. Default: '50' > let g:ycm_max_num_candidates = 50 < ------------------------------------------------------------------------------- The *g:ycm_max_num_candidates_to_detail* option Some completion engines require completion candidates to be 'resolved' in order to get detailed info such as inline documentation, method signatures, etc. This information is displayed by YCM in the preview window, or if 'completeopt' contains 'popup', in the info popup next to the completion menu. By default, if the info popup is in use, and there are more than 10 candidates, YCM will defer resolving candidates until they are selected in the completion menu. Otherwise, YCM must resolve the details upfront, which can be costly. If neither 'popup' nor 'preview' are in 'completeopt', YCM disables resolving altogether as the information would not be displayed. This setting can be used to override these defaults and controls the number of completion candidates that should be resolved upfront. Typically users do not need to change this, as YCM will work out an appropriate value based on your 'completeopt' and |g:ycm_add_preview_to_completeopt| settings. However, you may override this calculation by setting this value to a number: - '-1' - Resolve all candidates upfront - '0' - Never resolve any candidates upfront. - '> 0' - Resolve up to this many candidates upfront. If the number of candidates is greater than this value, no candidates are resolved. In the latter two cases, if 'completeopt' contains 'popup', then candidates are resolved on demand asynchronously. Default: - '0' if neither 'popup' nor 'preview' are in 'completeopt'. - '10' if 'popup' is in completeopt. - '-1' if 'preview' is in completeopt. Example: > let g:ycm_max_num_candidates_to_detail = 0 < ------------------------------------------------------------------------------- The *g:ycm_max_num_identifier_candidates* option This option controls the maximum number of completion suggestions from the identifier-based engine shown in the completion menu. A special value of '0' means there is no limit. **NOTE:** Setting this option to '0' or to a value greater than '100' is not recommended as it will slow down completion when there is a very large number of suggestions. Default: '10' > let g:ycm_max_num_identifier_candidates = 10 < ------------------------------------------------------------------------------- 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'. When |g:ycm_auto_trigger| is '0', YCM sets the 'completefunc', so that you can manually trigger normal completion using 'C-x C-u'. If you want to map something else to trigger completion, such as 'C-d', then you can map it to '(YCMComplete)'. For example: > let g:ycm_auto_trigger = 0 imap (YCMComplete) < NOTE: It's not possible to map one of the keys in |g:ycm_key_list_select_completion| (or similar) to '(YCMComplete)'. In practice that means that you can't use '' for this. 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 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} < ** Completion in buffers with no filetype ** There is one exception to the above rule. YCM supports completion in buffers with no filetype set, but this must be _explicitly_ whitelisted. To identify buffers with no filetype, we use the 'ycm_nofiletype' pseudo-filetype. To enable completion in buffers with no filetype, set: > let g:ycm_filetype_whitelist = { \ '*': 1, \ 'ycm_nofiletype': 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, \ 'notes': 1, \ 'markdown': 1, \ 'netrw': 1, \ 'unite': 1, \ 'text': 1, \ 'vimwiki': 1, \ 'pandoc': 1, \ 'infolog': 1, \ 'leaderf': 1, \ 'mail': 1 \} < In addition, 'ycm_nofiletype' (representing buffers with no filetype set) is blacklisted if 'ycm_nofiletype' is not _explicitly_ whitelisted (using |g:ycm_filetype_whitelist|). ------------------------------------------------------------------------------- The *g:ycm_filetype_specific_completion_to_disable* option This option controls for which Vim filetypes (see ':h filetype') should the YCM semantic completion engine be turned off. The option value should be a Vim dictionary with keys being filetype strings (like 'python', 'cpp', etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter). The listed filetypes will be ignored by the YCM semantic completion engine, but the identifier-based completion engine will still trigger in files of those filetypes. Note that even if semantic completion is not turned off for a specific filetype, you will not get semantic completion if the semantic engine does not support that filetype. You can get the filetype of the current file in Vim with ':set ft?'. Default: '[see next line]' > let g:ycm_filetype_specific_completion_to_disable = { \ 'gitcommit': 1 \} < ------------------------------------------------------------------------------- The *g:ycm_filepath_blacklist* option This option controls for which Vim filetypes (see ':h filetype') should filepath completion be disabled. 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. Use this key if you want to completely disable filepath completion: > let g:ycm_filepath_blacklist = {'*': 1} < You can get the filetype of the current file in Vim with ':set ft?'. Default: '[see next line]' > let g:ycm_filepath_blacklist = { \ 'html': 1, \ 'jsx': 1, \ 'xml': 1, \} < ------------------------------------------------------------------------------- The *g:ycm_show_diagnostics_ui* option When set, this option turns on YCM's diagnostic display features. See the _Diagnostic display_ section in the _User Manual_ for more details. Specific parts of the diagnostics UI (like the gutter signs, text highlighting, diagnostic echo, and auto location list population) can be individually turned on or off. See the other options below for details. Note that YCM's diagnostics UI is only supported for C-family languages. When set, this option also makes YCM remove all Syntastic checkers set for the 'c', 'cpp', 'objc', 'objcpp', and 'cuda' 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 to 1, YCM will echo the text of the diagnostic present on the current line when you move your cursor to that line. If a |FixIt| is available for the current diagnostic, then '(FixIt)' is appended. If you have a Vim that supports virtual text, you can set this option to the string 'virtual-text', and the diagnostic will be displayed inline with the text, right aligned in the window and wrapping to the next line if there is not enough space, for example: Image: Virtual text diagnostic demo (see reference [93]) Image: Virtual text diagnostic demo (see reference [94]) **NOTE**: It's _strongly_ recommended to also set |g:ycm_update_diagnostics_in_insert_mode| to '0' when using 'virtual-text' for diagnostics. This is due to the increased amount of distraction provided by drawing diagnostics next to your input position. 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' Valid values: - '0' - disabled - '1' - echo diagnostic to the command area - "'virtual-text'" - display the dignostic to the right of the line in the window using virtual text > let g:ycm_echo_current_diagnostic = 1 " Or, when you have Vim supporting virtual text let g:ycm_echo_current_diagnostic = 'virtual-text' < ------------------------------------------------------------------------------- The *g:ycm_auto_hover* option This option controls whether or not YCM shows documentation in a popup at the cursor location after a short delay. Only supported in Vim. When this option is set to "'CursorHold'", the popup is displayed on the 'CursorHold' autocommand. See ':help CursorHold' for the details, but this means that it is displayed after 'updatetime' milliseconds. When set to an empty string, the popup is not automatically displayed. In addition to this setting, there is the '(YCMHover)' mapping, which can be used to manually trigger or hide the popup (it works like a toggle). For example: > nmap D (YCMHover) < After dismissing the popup with this mapping, it will not be automatically triggered again until the cursor is moved (i.e. 'CursorMoved' autocommand). The displayed documentation depends on what the completer for the current language supports. It's selected heuristically in this order of preference: 1. 'GetHover' with 'markdown' syntax 2. |GetDoc| with no syntax 3. |GetType| with the syntax of the current file. You can customise this by manually setting up 'b:ycm_hover' to your liking. This buffer-local variable can be set to a dictionary with the following keys: - 'command': The YCM completer subcommand which should be run on hover - 'syntax': The syntax to use (as in 'set syntax=') in the popup window for highlighting. - 'popup_params': The params passed to a popup window which gets opened. For example, to use C/C++ syntax highlighting in the popup for C-family languages, add something like this to your vimrc: > augroup MyYCMCustom autocmd! autocmd FileType c,cpp let b:ycm_hover = { \ 'command': 'GetDoc', \ 'syntax': &filetype \ } augroup END < You can also modify the opened popup with 'popup_params' key. For example, you can limit the popup's maximum width and add a border to it: > augroup MyYCMCustom autocmd! autocmd FileType c,cpp let b:ycm_hover = { \ 'command': 'GetDoc', \ 'syntax': &filetype \ 'popup_params': { \ 'maxwidth': 80, \ 'border': [], \ 'borderchars': ['─', '│', '─', '│', '┌', '┐', '┘', '└'], \ }, \ } augroup END < See ':help popup_create-arguments' for the list of available popup window options. Default: "'CursorHold'" ------------------------------------------------------------------------------- The *g:ycm_filter_diagnostics* option This option controls which diagnostics will be rendered by YCM. This option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are dictionaries describing the filter. A filter is a dictionary of key-values, where the keys are the type of filter, and the value is a list of arguments to that filter. In the case of just a single item in the list, you may omit the brackets and just provide the argument directly. If any filter matches a diagnostic, it will be dropped and YCM will not render it. The following filter types are supported: - "regex": Accepts a string regular expression [95]. This type matches when the regex (treated as case-insensitive) is found anywhere in the diagnostic text ('re.search', not 're.match') - "level": Accepts a string level, either "warning" or "error." This type matches when the diagnostic has the same level, that is, specifying 'level: "error"' will remove **all** errors from the diagnostics. **NOTE:** The regex syntax is **NOT** Vim's, it's Python's [95]. Default: '{}' The following example will do, for Java filetype only: - Remove **all** error level diagnostics, and, - Also remove anything that contains 'taco' > let g:ycm_filter_diagnostics = { \ "java": { \ "regex": [ "ta.+co", ... ], \ "level": "error", \ ... \ } \ } < ------------------------------------------------------------------------------- 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. Note: if YCM's errors aren't visible, it might be that YCM is updating an older location list. See ':help :lhistory' and ':lolder'. 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_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 [96]. 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 'Settings' 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 [44] and then passed to your 'Settings' function as a 'client_data' keyword argument. For instance, if you set this option to "['v:version']", your 'Settings' function will be called like this: > # The '801' value is of course contingent on Vim 8.1; in 8.0 it would be '800' Settings( ..., client_data = { 'v:version': 801 } ) < 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 'Settings' function: > def Settings( **kwargs ): < You can then get to 'client_data' with "kwargs['client_data']". Default: '[]' > let g:ycm_extra_conf_vim_data = [] < ------------------------------------------------------------------------------- The *g:ycm_server_python_interpreter* option YCM will by default search for an appropriate Python interpreter on your system. You can use this option to override that behavior and force the use of a specific interpreter of your choosing. **NOTE:** This interpreter is only used for the ycmd server [44]. The YCM client running inside Vim always uses the Python interpreter that's embedded inside Vim. Default: "''" > let g:ycm_server_python_interpreter = '' < ------------------------------------------------------------------------------- The *g:ycm_keep_logfiles* option When this option is set to '1', YCM and the ycmd completion server [44] will keep the logfiles around after shutting down (they are deleted on shutdown by default). To see where the log files are, call |:YcmDebugInfo|. Default: '0' > let g:ycm_keep_logfiles = 0 < ------------------------------------------------------------------------------- The *g:ycm_log_level* option The logging level that YCM and the ycmd completion server [44] use. 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_log_level = 'info' < ------------------------------------------------------------------------------- The *g:ycm_auto_start_csharp_server* option When set to '1', the OmniSharp-Roslyn 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-Roslyn server will be automatically stopped upon closing Vim. Default: '1' > let g:ycm_auto_stop_csharp_server = 1 < ------------------------------------------------------------------------------- The *g:ycm_csharp_server_port* option When g:ycm_auto_start_csharp_server is set to '1', specifies the port for the OmniSharp-Roslyn server to listen on. When set to '0' uses an unused port provided by the OS. Default: '0' > let g:ycm_csharp_server_port = 0 < ------------------------------------------------------------------------------- The *g:ycm_csharp_insert_namespace_expr* option By default, when YCM inserts a namespace, it will insert the 'using' statement under the nearest 'using' statement. You may prefer that the 'using' statement is inserted somewhere, for example, to preserve sorting. If so, you can set this option to override this behavior. When this option is set, instead of inserting the 'using' statement itself, YCM will set the global variable 'g:ycm_namespace_to_insert' to the namespace to insert, and then evaluate this option's value as an expression. The option's expression is responsible for inserting the namespace - the default insertion will not occur. Default: '' > let g:ycm_csharp_insert_namespace_expr = '' < ------------------------------------------------------------------------------- The *g:ycm_add_preview_to_completeopt* option When this option is set to '1', YCM will add the 'preview' string to Vim's 'completeopt' option (see ':h completeopt'). If your 'completeopt' option already has 'preview' set, there will be no effect. Alternatively, when set to 'popup' and your version of Vim supports popup windows (see ':help popup'), the 'popup' string will be used instead. 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. When 'popup' is present in 'completeopt', YCM will instead use a 'popup' window to the side of the completion popup for storing detailed information about the current completion candidate. In addition, YCM may truncate the detailed completion information in order to give the popup sufficient room to display that detailed information. 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 for the C-family, C#, Java, JavaScript, and TypeScript languages. A special value of '0' means there is no limit. 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 backward 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_list_stop_completion* option This option controls the key mappings used to close the completion menu. This is useful when the menu is blocking the view, when you need to insert the '' character, or when you want to expand a snippet from UltiSnips [25] and navigate through it. Default: "['']" > let g:ycm_key_list_stop_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 triggered automatically after typing characters appropriate for the language, such as '.', '->', '::', etc. 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 the 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. If you prefer the detailed diagnostic to be shown in a popup, then 'let g:ycm_show_detailed_diag_in_popup=1'. Default: 'd' > let g:ycm_key_detailed_diagnostics = 'd' < ------------------------------------------------------------------------------- The *g:ycm_show_detailed_diag_in_popup* option Makes |:YcmShowDetailedDiagnostic| always show in a popup rather than echoing to the command line. Default: 0 > let g:ycm_show_detailed_diag_in_popup = 0 < ------------------------------------------------------------------------------- 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 the execution of malicious code from a '.ycm_extra_conf.py' file you didn't write. To selectively get YCM to ask/not ask about loading certain '.ycm_extra_conf.py' files, see the |g:ycm_extra_conf_globlist| option. Default: '1' > let g:ycm_confirm_extra_conf = 1 < ------------------------------------------------------------------------------- The *g:ycm_extra_conf_globlist* option This option is a list that may contain several globbing patterns. If a pattern starts with a '!' all '.ycm_extra_conf.py' files matching that pattern will be blacklisted, that is they won't be loaded and no confirmation dialog will be shown. If a pattern does not start with a '!' all files matching that pattern will be whitelisted. Note that this option is not used when confirmation is disabled using |g:ycm_confirm_extra_conf| and that items earlier in the list will take precedence over the later ones. Rules: - '*' matches everything - '?' matches any single character - '[seq]' matches any character in seq - '[!seq]' matches any char not in seq Example: > let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*'] < - The first rule will match everything contained in the '~/dev' directory so '.ycm_extra_conf.py' files from there will be loaded. - The second rule will match everything in the home directory so a '.ycm_extra_conf.py' file from there won't be loaded. - As the first rule takes precedence everything in the home directory excluding the '~/dev' directory will be blacklisted. **NOTE:** The glob pattern is first expanded with Python's 'os.path.expanduser()' and then resolved with 'os.path.abspath()' before being matched against the filename. Default: '[]' > let g:ycm_extra_conf_globlist = [] < ------------------------------------------------------------------------------- The *g:ycm_filepath_completion_use_working_dir* option By default, YCM's filepath completion will interpret relative paths like '../' as being relative to the folder of the file of the currently active buffer. Setting this option will force YCM to always interpret relative paths as being relative to Vim's current working directory. Default: '0' > let g:ycm_filepath_completion_use_working_dir = 0 < ------------------------------------------------------------------------------- The *g:ycm_semantic_triggers* option This option controls the character-based triggers for the various semantic completion engines. The option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are lists of strings, where the strings are the triggers. Setting key-value pairs on the dictionary _adds_ semantic triggers to the internal default set (listed below). You cannot remove the default triggers, only add new ones. A "trigger" is a sequence of one or more characters that trigger semantic completion when typed. For instance, C++ ('cpp' filetype) has '.' listed as a trigger. So when the user types 'foo.', the semantic engine will trigger and serve 'foo''s list of member functions and variables. Since C++ also has '->' listed as a trigger, the same thing would happen when the user typed 'foo->'. It's also possible to use a regular expression as a trigger. You have to prefix your trigger with 're!' to signify it's a regex trigger. For instance, 're!\w+\.' would only trigger after the '\w+\.' regex matches. **NOTE:** The regex syntax is **NOT** Vim's, it's Python's [95]. Default: '[see next line]' > let g:ycm_semantic_triggers = { \ 'c': ['->', '.'], \ 'objc': ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s', \ 're!\[.*\]\s'], \ 'ocaml': ['.', '#'], \ 'cpp,cuda,objcpp': ['->', '.', '::'], \ 'perl': ['->'], \ 'php': ['->', '::'], \ 'cs,d,elixir,go,groovy,java,javascript,julia,perl6,python,scala,typescript,vb': ['.'], \ 'ruby,rust': ['.', '::'], \ 'lua': ['.', ':'], \ 'erlang': [':'], \ } < ------------------------------------------------------------------------------- The *g:ycm_cache_omnifunc* option Some omnicompletion engines do not work well with the YCM cache—in particular, they might not produce all possible results for a given prefix. By unsetting this option you can ensure that the omnicompletion engine is re-queried on every keypress. That will ensure all completions will be presented but might cause stuttering and lag if the omnifunc is slow. Default: '1' > let g:ycm_cache_omnifunc = 1 < ------------------------------------------------------------------------------- The *g:ycm_use_ultisnips_completer* option By default, YCM will query the UltiSnips plugin for possible completions of snippet triggers. This option can turn that behavior off. Default: '1' > let g:ycm_use_ultisnips_completer = 1 < ------------------------------------------------------------------------------- The *g:ycm_goto_buffer_command* option Defines where 'GoTo*' commands result should be opened. Can take one of the following values: "'same-buffer'", "'split'", or "'split-or-existing-window'". If this option is set to the "'same-buffer'" but current buffer can not be switched (when buffer is modified and 'nohidden' option is set), then result will be opened in a split. When the option is set to "'split-or-existing-window'", if the result is already open in a window of the current tab page (or any tab pages with the ':tab' modifier; see below), it will jump to that window. Otherwise, the result will be opened in a split as if the option was set to "'split'". To customize the way a new window is split, prefix the 'GoTo*' command with one of the following modifiers: ':aboveleft', ':belowright', ':botright', ':leftabove', ':rightbelow', ':topleft', and ':vertical'. For instance, to split vertically to the right of the current window, run the command: > :rightbelow vertical YcmCompleter GoTo < To open in a new tab page, use the ':tab' modifier with the "'split'" or "'split-or-existing-window'" options e.g.: > :tab YcmCompleter GoTo < Default: "'same-buffer'" > let g:ycm_goto_buffer_command = 'same-buffer' < ------------------------------------------------------------------------------- The *g:ycm_disable_for_files_larger_than_kb* option Defines the max size (in Kb) for a file to be considered for completion. If this option is set to 0 then no check is made on the size of the file you're opening. Default: 1000 > let g:ycm_disable_for_files_larger_than_kb = 1000 < ------------------------------------------------------------------------------- The *g:ycm_use_clangd* option This option controls whether **clangd** should be used as a completion engine for C-family languages. Can take one of the following values: '1', '0', with meanings: - '1': YCM will use clangd if clangd binary exists in third party or it was provided with 'ycm_clangd_binary_path' option. - '0': YCM will never use clangd completer. Default: '1' > let g:ycm_use_clangd = 1 < ------------------------------------------------------------------------------- The *g:ycm_clangd_binary_path* option When 'ycm_use_clangd' option is set to '1', this option sets the path to **clangd** binary. Default: "''" > let g:ycm_clangd_binary_path = '' < ------------------------------------------------------------------------------- The *g:ycm_clangd_args* option This option controls the command line arguments passed to the clangd binary. It appends new options and overrides the existing ones. Default: '[]' > let g:ycm_clangd_args = [] < ------------------------------------------------------------------------------- The *g:ycm_clangd_uses_ycmd_caching* option This option controls which ranking and filtering algorithm to use for completion items. It can take values: - '1': Uses ycmd's caching and filtering logic. - '0': Uses clangd's caching and filtering logic. Default: '1' > let g:ycm_clangd_uses_ycmd_caching = 1 < ------------------------------------------------------------------------------- The *g:ycm_language_server* option This option lets YCM use an arbitrary Language Server Protocol (LSP) server, not unlike many other completion systems. The officially supported completers are favoured over custom LSP ones, so overriding an existing completer means first making sure YCM won't choose that existing completer in the first place. A simple working example of this option can be found in the section called "Semantic Completion for Other Languages". Many working examples can be found in the YCM lsp-examples [80] repository. Default: '[]' > let g:ycm_language_server = [] < ------------------------------------------------------------------------------- The *g:ycm_disable_signature_help* option This option allows you to disable all signature help for all completion engines. There is no way to disable it per-completer. Default: '0' > " Disable signature help let g:ycm_disable_signature_help = 1 < ------------------------------------------------------------------------------- The *g:ycm_signature_help_disable_syntax* option Set this to 1 to disable syntax highlighting in the signature help popup. Thiis can help if your colourscheme doesn't work well with the default highliting and inverse video. Default: '0' > " Disable signature help syntax highliting let g:ycm_signature_help_disable_syntax = 1 < ------------------------------------------------------------------------------- The *g:ycm_gopls_binary_path* option In case the system-wide 'gopls' binary is newer than the bundled one, setting this option to the path of the system-wide 'gopls' would make YCM use that one instead. If the path is just 'gopls', YCM will search in '$PATH'. ------------------------------------------------------------------------------- The *g:ycm_gopls_args* option Similar to the |g:ycm_clangd_args|, this option allows passing additional flags to the 'gopls' command line. Default: '[]' > let g:ycm_gopls_args = [] < ------------------------------------------------------------------------------- The *g:ycm_rls_binary_path* and 'g:ycm_rustc_binary_path' options YCM no longer uses RLS for rust, and these options are therefore no longer supported. To use a custom rust-analyzer, see |g:ycm_rust_toolchain_root|. ------------------------------------------------------------------------------- The *g:ycm_rust_toolchain_root* option Optionally specify the path to a custom rust toolchain including at least a supported version of 'rust-analyzer'. ------------------------------------------------------------------------------- The *g:ycm_tsserver_binary_path* option Similar to the 'gopls' path, this option tells YCM where is the TSServer executable located. ------------------------------------------------------------------------------- The *g:ycm_roslyn_binary_path* option Similar to the 'gopls' path, this option tells YCM where is the Omnisharp-Roslyn executable located. ------------------------------------------------------------------------------- The *g:ycm_update_diagnostics_in_insert_mode* option With async diagnostics, LSP servers might send new diagnostics mid-typing. If seeing these new diagnostics while typing is not desired, this option can be set to 0. When this option is set to '0', diagnostic signs, virtual text, and highlights are cleared when entering insert mode and replaced when leaving insert mode. This reduces visual noise while editing. In addition, this option is recommended when |g:ycm_echo_current_diagnostic| is set to 'virtual-text' as it prevents updating the virtual text while you are typing. Default: '1' > let g:ycm_update_diagnostics_in_insert_mode = 1 < ------------------------------------------------------------------------------- *youcompleteme-faq* FAQ ~ The FAQ section has been moved to the wiki [8]. ------------------------------------------------------------------------------- *youcompleteme-contributor-code-of-conduct* Contributor Code of Conduct ~ Please note that this project is released with a Contributor Code of Conduct [97]. By participating in this project you agree to abide by its terms. ------------------------------------------------------------------------------- *youcompleteme-contact* Contact ~ If you have questions about the plugin or need help, please join the Gitter room [1] or use the ycm-users [98] mailing list. If you have bug reports or feature suggestions, please use the issue tracker [99]. Before you do, please carefully read CONTRIBUTING.md [100] as this asks for important diagnostics which the team will use to help get you going. The latest version of the plugin is available at https://ycm-core.github.io/YouCompleteMe/. The author's homepage is https://val.markovic.io. Please do **NOT** go to #vim, Reddit, or Stack Overflow for support. Please contact the YouCompleteMe maintainers directly using the contact details. ------------------------------------------------------------------------------- *youcompleteme-license* License ~ This software is licensed under the GPL v3 license [101]. © 2015-2018 YouCompleteMe contributors ------------------------------------------------------------------------------- *youcompleteme-sponsorship* Sponsorship ~ If you like YCM so much that you're willing to part with your hard-earned cash, please consider donating to one of the following charities, which are meaningful to the current maintainers (in no particular order): - Hector's Greyhound Rescue [102] - Be Humane [103] - Cancer Research UK [104] - ICCF Holland [105] - Any charity of your choosing. Please note: The YCM maintainers do not specifically endorse nor necessarily have any relationship with the above charities. Disclosure: It is noted that one key maintainer is a family with Trustees of Greyhound Rescue Wales. =============================================================================== *youcompleteme-references* References ~ [1] https://gitter.im/Valloric/YouCompleteMe [2] https://img.shields.io/gitter/room/Valloric/YouCompleteMe.svg [3] https://dev.azure.com/YouCompleteMe/YCM/_build?definitionId=3&branchName=master [4] https://dev.azure.com/YouCompleteMe/YCM/_apis/build/status/ycm-core.YouCompleteMe?branchName=master [5] https://codecov.io/gh/ycm-core/YouCompleteMe [6] https://img.shields.io/codecov/c/github/ycm-core/YouCompleteMe/master.svg [7] https://github.com/ycm-core/YouCompleteMe/wiki/Troubleshooting-steps-for-ycmd-server-SHUT-DOWN [8] https://github.com/ycm-core/YouCompleteMe/wiki/FAQ [9] https://github.com/ycm-core/YouCompleteMe/issues/4134#issuecomment-1446235584 [10] https://www.vim.org/ [11] https://clang.llvm.org/extra/clangd.html [12] https://github.com/davidhalter/jedi [13] https://github.com/OmniSharp/omnisharp-roslyn [14] https://github.com/golang/go/wiki/gopls [15] https://github.com/Microsoft/TypeScript/tree/master/src/server [16] https://rust-analyzer.github.io [17] https://github.com/eclipse/eclipse.jdt.ls [18] https://i.imgur.com/0OP4ood.gif [19] https://en.wikipedia.org/wiki/Subsequence [20] https://github.com/scrooloose/syntastic [21] https://user-images.githubusercontent.com/10026824/34471853-af9cf32a-ef53-11e7-8229-de534058ddc4.gif [22] https://user-images.githubusercontent.com/10584846/58738348-5060da80-83fd-11e9-9537-d07fdbf4554c.gif [23] https://i.imgur.com/nmUUbdl.gif [24] https://user-images.githubusercontent.com/10584846/80312146-91af6500-87db-11ea-996b-7396f3134d1f.gif [25] https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt [26] https://github.com/VundleVim/Vundle.vim#about [27] mono-install-macos [28] https://macvim-dev.github.io/macvim/ [29] https://brew.sh [30] https://www.mono-project.com/download/stable/ [31] https://golang.org/doc/install [32] https://docs.npmjs.com/getting-started/installing-node#1-install-nodejs--npm [33] https://adoptium.net/en-GB/temurin/releases [34] https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source [35] https://www.mono-project.com/download/stable/#download-lin [36] https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16 [37] https://vimhelp.appspot.com/starting.txt.html#vimrc [38] https://github.com/vim/vim-win32-installer/releases [39] https://www.python.org/downloads/windows/ [40] https://cmake.org/download/ [41] https://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1 [42] https://github.com/ycm-core/YouCompleteMe/wiki/Full-Installation-Guide [43] https://www.unicode.org/glossary/#diacritic [44] https://github.com/ycm-core/ycmd [45] https://github.com/ycm-core/ycmd/pull/1255 [46] https://user-images.githubusercontent.com/10584846/173137003-a265e8b0-84db-4993-98f0-03ee81b9de94.png [47] https://user-images.githubusercontent.com/10584846/173137012-7547de0b-145f-45fa-ace3-18943acd2141.png [48] https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens [49] https://user-images.githubusercontent.com/10584846/185708054-68074fc0-e50c-4a65-887c-da6f372b8982.png [50] https://user-images.githubusercontent.com/10584846/185708156-b52970ce-005f-4f0b-97e7-bdf8feeefedc.png [51] https://user-images.githubusercontent.com/10584846/185708242-e42dab6f-1847-46f1-8585-2d9f2c8a76dc.png [52] https://github.com/ycm-core/YouCompleteMe/wiki/C-family-Semantic-Completion-through-libclang [53] https://clang.llvm.org/docs/JSONCompilationDatabase.html [54] https://ninja-build.org/manual.html [55] https://pypi.org/project/compiledb/ [56] https://github.com/rizsotto/Bear [57] https://raw.githubusercontent.com/ycm-core/ycmd/66030cd94299114ae316796f3cad181cac8a007c/.ycm_extra_conf.py [58] https://github.com/rdnetto/YCM-Generator [59] https://github.com/eclipse/eclipse.jdt.ls/blob/master/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/preferences/Preferences.java [60] https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html [61] https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html [62] https://docs.gradle.org/current/userguide/tutorial_java_projects.html [63] https://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIClasspathEntry.html [64] https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_eclipse_project [65] https://github.com/ycm-core/ycmd/blob/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_maven_project/pom.xml [66] https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_gradle_project [67] https://github.com/ycm-core/lsp-examples#kotlin [68] https://github.com/OmniSharp/omnisharp-roslyn/releases/ [69] https://github.com/ycm-core/YouCompleteMe/blob/master/.ycm_extra_conf.py [70] https://github.com/rust-lang/rls [71] https://www.rust-lang.org/downloads.html [72] https://rust-analyzer.github.io/manual.html#configuration] [73] https://github.com/golang/tools/blob/master/gopls/doc/settings.md [74] https://ternjs.net [75] https://github.com/ycm-core/YouCompleteMe/wiki/JavaScript-Semantic-Completion-through-Tern [76] https://code.visualstudio.com/docs/languages/jsconfig [77] https://www.typescriptlang.org/docs/handbook/tsconfig-json.html [78] https://clang.llvm.org/ [79] https://github.com/ycm-core/ycmd#language_server-configuration [80] https://github.com/ycm-core/lsp-examples [81] http://eclim.org/ [82] https://github.com/ycm-core/ycmd/blob/master/ycmd/completers/completer.py [83] https://github.com/Valloric/ListToggle [84] https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C [85] https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C.svg [86] https://asciinema.org/a/659925 [87] https://asciinema.org/a/659925.svg [88] https://user-images.githubusercontent.com/17928698/206855014-9131a49b-87e8-4ed4-8d91-f2fe7808a0b9.gif [89] https://user-images.githubusercontent.com/17928698/206855713-3588c8de-d0f5-4725-b65e-bc51110252cc.gif [90] https://jedi.readthedocs.io/en/latest/docs/api.html#jedi.Script.extract_variable [91] https://github.com/puremourning/vimspector [92] https://github.com/itchyny/lightline.vim [93] https://user-images.githubusercontent.com/10584846/185707973-39703699-0263-47d3-82ac-639d52259bea.png [94] https://user-images.githubusercontent.com/10584846/185707993-14ff5fd7-c082-4e5a-b825-f1364e619b6a.png [95] https://docs.python.org/2/library/re.html#regular-expression-syntax [96] http://ctags.sourceforge.net/FORMAT [97] https://github.com/ycm-core/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md [98] https://groups.google.com/forum/?hl=en#!forum/ycm-users [99] https://github.com/ycm-core/YouCompleteMe/issues?state=open [100] https://github.com/ycm-core/YouCompleteMe/blob/master/CONTRIBUTING.md [101] https://www.gnu.org/copyleft/gpl.html [102] https://www.hectorsgreyhoundrescue.org [103] https://www.budihuman.rs/en [104] https://www.cancerresearchuk.org [105] https://iccf.nl vim: ft=help ================================================ FILE: install.py ================================================ #!/usr/bin/env python3 from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import import os import subprocess import sys import os.path as p import glob version = sys.version_info[ 0 : 3 ] if version < ( 3, 12, 0 ): sys.exit( 'YouCompleteMe requires Python >= 3.12.0; ' 'your version of Python is ' + sys.version ) DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) DIR_OF_OLD_LIBS = p.join( DIR_OF_THIS_SCRIPT, 'python' ) def CheckCall( args, **kwargs ): try: subprocess.check_call( args, **kwargs ) except subprocess.CalledProcessError as error: sys.exit( error.returncode ) def Main(): build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ) if not p.isfile( build_file ): sys.exit( 'File {0} does not exist; you probably forgot to run:\n' '\tgit submodule update --init --recursive\n'.format( build_file ) ) CheckCall( [ sys.executable, build_file ] + sys.argv[ 1: ] ) # Remove old YCM libs if present so that YCM can start. old_libs = ( glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_core.*' ) ) + glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_client_support.*' ) ) + glob.glob( p.join( DIR_OF_OLD_LIBS, '*clang*.*' ) ) ) for lib in old_libs: os.remove( lib ) if __name__ == "__main__": Main() ================================================ FILE: install.sh ================================================ #!/bin/sh echo "WARNING: this script is deprecated. Use the install.py script instead." 1>&2 SCRIPT_DIR=$(dirname $0 || exit $?) python3 "$SCRIPT_DIR/install.py" "$@" || exit $? ================================================ FILE: plugin/youcompleteme.vim ================================================ " 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 function! s:restore_cpo() let &cpo = s:save_cpo unlet s:save_cpo endfunction " NOTE: The minimum supported version is 8.2.3995, but neovim always reports as " v:version 800, but will largely work. let s:is_neovim = has( 'nvim' ) if exists( "g:loaded_youcompleteme" ) call s:restore_cpo() finish elseif ( v:version < 901 || (v:version == 901 && !has( 'patch0016' )) ) && \ !s:is_neovim echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires Vim 9.1.0016+." | \ echohl None call s:restore_cpo() finish elseif !has( 'timers' ) echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires Vim compiled with " . \ "the timers feature." | \ echohl None call s:restore_cpo() finish elseif !has( 'python3_compiled' ) echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires Vim compiled with " . \ "Python (3.12.0+) support." | \ echohl None call s:restore_cpo() finish " These calls try to load the Python 3 libraries when Vim is " compiled dynamically against them. Since only one can be loaded at a time on " some platforms, we first check if Python 3 is available. elseif !has( 'python3' ) echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: unable to load Python." | \ echohl None call s:restore_cpo() finish elseif &encoding !~? 'utf-\?8' echohl WarningMsg | \ echomsg "YouCompleteMe unavailable: requires UTF-8 encoding. " . \ "Put the line 'set encoding=utf-8' in your vimrc." | \ echohl None call s:restore_cpo() finish endif let g:loaded_youcompleteme = 1 " " List of YCM options. " let g:ycm_filetype_whitelist = \ get( g:, 'ycm_filetype_whitelist', { "*": 1 } ) let g:ycm_filetype_blacklist = \ get( g:, 'ycm_filetype_blacklist', { \ 'tagbar': 1, \ 'notes': 1, \ 'markdown': 1, \ 'netrw': 1, \ 'unite': 1, \ 'text': 1, \ 'vimwiki': 1, \ 'pandoc': 1, \ 'infolog': 1, \ 'leaderf': 1, \ 'mail': 1 \ } ) " Blacklist empty buffers unless explicity whitelisted; workaround for " https://github.com/ycm-core/YouCompleteMe/issues/3781 if !has_key( g:ycm_filetype_whitelist, 'ycm_nofiletype' ) let g:ycm_filetype_blacklist.ycm_nofiletype = 1 endif 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_list_stop_completion = \ get( g:, 'ycm_key_list_stop_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_log_level = \ get( g:, 'ycm_log_level', \ get( g:, 'ycm_server_log_level', 'info' ) ) let g:ycm_keep_logfiles = \ get( g:, 'ycm_keep_logfiles', \ get( g:, 'ycm_server_keep_logfiles', 0 ) ) let g:ycm_extra_conf_vim_data = \ get( g:, 'ycm_extra_conf_vim_data', [] ) let g:ycm_server_python_interpreter = \ get( g:, 'ycm_server_python_interpreter', \ get( g:, 'ycm_path_to_python_interpreter', '' ) ) let g:ycm_show_diagnostics_ui = \ get( g:, 'ycm_show_diagnostics_ui', 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_filter_diagnostics = \ get( g:, 'ycm_filter_diagnostics', {} ) let g:ycm_always_populate_location_list = \ get( g:, 'ycm_always_populate_location_list', \ get( g:, 'syntastic_always_populate_loc_list', 0 ) ) let g:ycm_error_symbol = \ get( g:, 'ycm_error_symbol', \ get( g:, 'syntastic_error_symbol', '>>' ) ) let g:ycm_warning_symbol = \ get( g:, 'ycm_warning_symbol', \ get( g:, 'syntastic_warning_symbol', '>>' ) ) let g:ycm_complete_in_comments = \ get( g:, 'ycm_complete_in_comments', 0 ) let g:ycm_complete_in_strings = \ get( g:, 'ycm_complete_in_strings', 1 ) let g:ycm_collect_identifiers_from_tags_files = \ get( g:, 'ycm_collect_identifiers_from_tags_files', 0 ) let g:ycm_seed_identifiers_with_syntax = \ get( g:, 'ycm_seed_identifiers_with_syntax', 0 ) let g:ycm_goto_buffer_command = \ get( g:, 'ycm_goto_buffer_command', 'same-buffer' ) let g:ycm_disable_for_files_larger_than_kb = \ get( g:, 'ycm_disable_for_files_larger_than_kb', 1000 ) let g:ycm_auto_hover = \ get( g:, 'ycm_auto_hover', 'CursorHold' ) let g:ycm_update_diagnostics_in_insert_mode = \ get( g:, 'ycm_update_diagnostics_in_insert_mode', 1 ) " " List of ycmd options. " let g:ycm_filepath_completion_use_working_dir = \ get( g:, 'ycm_filepath_completion_use_working_dir', 0 ) let g:ycm_auto_trigger = \ get( g:, 'ycm_auto_trigger', 1 ) let g:ycm_min_num_of_chars_for_completion = \ get( g:, 'ycm_min_num_of_chars_for_completion', 2 ) let g:ycm_min_identifier_candidate_chars = \ get( g:, 'ycm_min_num_identifier_candidate_chars', 0 ) let g:ycm_semantic_triggers = \ get( g:, 'ycm_semantic_triggers', {} ) let g:ycm_filetype_specific_completion_to_disable = \ get( g:, 'ycm_filetype_specific_completion_to_disable', \ { 'gitcommit': 1 } ) let g:ycm_collect_identifiers_from_comments_and_strings = \ get( g:, 'ycm_collect_identifiers_from_comments_and_strings', 0 ) let g:ycm_max_num_identifier_candidates = \ get( g:, 'ycm_max_num_identifier_candidates', 10 ) let g:ycm_max_num_candidates = \ get( g:, 'ycm_max_num_candidates', 50 ) let g:ycm_extra_conf_globlist = \ get( g:, 'ycm_extra_conf_globlist', [] ) let g:ycm_global_ycm_extra_conf = \ get( g:, 'ycm_global_ycm_extra_conf', '' ) let g:ycm_confirm_extra_conf = \ get( g:, 'ycm_confirm_extra_conf', 1 ) let g:ycm_max_diagnostics_to_display = \ get( g:, 'ycm_max_diagnostics_to_display', 30 ) let g:ycm_filepath_blacklist = \ get( g:, 'ycm_filepath_blacklist', { \ 'html': 1, \ 'jsx': 1, \ 'xml': 1 \ } ) let g:ycm_auto_start_csharp_server = \ get( g:, 'ycm_auto_start_csharp_server', 1 ) let g:ycm_auto_stop_csharp_server = \ get( g:, 'ycm_auto_stop_csharp_server', 1 ) let g:ycm_use_ultisnips_completer = \ get( g:, 'ycm_use_ultisnips_completer', 1 ) let g:ycm_csharp_server_port = \ get( g:, 'ycm_csharp_server_port', 0 ) let g:ycm_use_clangd = \ get( g:, 'ycm_use_clangd', 1 ) let g:ycm_clangd_binary_path = \ get( g:, 'ycm_clangd_binary_path', '' ) let g:ycm_clangd_args = \ get( g:, 'ycm_clangd_args', [] ) let g:ycm_clangd_uses_ycmd_caching = \ get( g:, 'ycm_clangd_uses_ycmd_caching', 1 ) " These options are not documented. let g:ycm_java_jdtls_extension_path = \ get( g:, 'ycm_java_jdtls_extension_path', [] ) let g:ycm_java_jdtls_use_clean_workspace = \ get( g:, 'ycm_java_jdtls_use_clean_workspace', 1 ) let g:ycm_java_jdtls_workspace_root_path = \ get( g:, 'ycm_java_jdtls_workspace_root_path', '' ) " This option is deprecated. let g:ycm_python_binary_path = \ get( g:, 'ycm_python_binary_path', '' ) let g:ycm_refilter_workspace_symbols = \ get( g:, 'ycm_refilter_workspace_symbols', 1 ) if has( 'vim_starting' ) " Loading at startup. " We defer loading until after VimEnter to allow the gui to fork (see " `:h gui-fork`) and avoid a deadlock situation, as explained here: " https://github.com/Valloric/YouCompleteMe/pull/2473#issuecomment-267716136 augroup youcompletemeStart autocmd! autocmd VimEnter * call youcompleteme#Enable() augroup END else " Manual loading with :packadd. call youcompleteme#Enable() endif " This is basic vim plugin boilerplate call s:restore_cpo() ================================================ FILE: print_todos.sh ================================================ #!/bin/bash ag \ --ignore gmock \ --ignore jedi/ \ --ignore OmniSharpServer \ --ignore testdata \ TODO \ third_party/ycmd/cpp/ycm python autoload plugin ================================================ FILE: python/test_requirements.txt ================================================ flake8 >= 3.0.0 flake8-comprehensions >= 1.4.1 flake8-ycm >= 0.1.0 PyHamcrest >= 1.10.1 # Use the updated fork git+https://github.com/bstaletic/covimerage ================================================ FILE: python/ycm/__init__.py ================================================ ================================================ FILE: python/ycm/base.py ================================================ # 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 json from ycm import vimsupport, paths from ycmd import identifier_utils YCM_VAR_PREFIX = 'ycm_' def GetUserOptions( default_options = {} ): """Builds a dictionary mapping YCM Vim user options to values. Option names don't have the 'ycm_' prefix.""" user_options = {} # First load the default settings from ycmd. We do this to ensure that any # client-side code that assumes all options are loaded (such as the # omnicompleter) don't have to constantly check for values being present, and # so that we don't jave to dulicate the list of server settings in # youcomplete.vim defaults_file = os.path.join( paths.DIR_OF_YCMD, 'ycmd', 'default_settings.json' ) if os.path.exists( defaults_file ): with open( defaults_file ) as defaults_file_handle: user_options = json.load( defaults_file_handle ) # Override the server defaults with any client-generated defaults user_options.update( default_options ) # Finally, override with any user-specified values in the g: dict # We only evaluate the keys of the vim globals and not the whole dictionary # to avoid unicode issues. # See https://github.com/Valloric/YouCompleteMe/pull/2151 for details. keys = vimsupport.GetVimGlobalsKeys() for key in keys: if not key.startswith( YCM_VAR_PREFIX ): continue new_key = key[ len( YCM_VAR_PREFIX ): ] new_value = vimsupport.VimExpressionToPythonType( 'g:' + key ) user_options[ new_key ] = new_value return user_options def CurrentIdentifierFinished(): line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn() previous_char_index = current_column - 1 if previous_char_index < 0: return True filetype = vimsupport.CurrentFiletypes()[ 0 ] regex = identifier_utils.IdentifierRegexForFiletype( filetype ) for match in regex.finditer( line ): if match.end() == previous_char_index: return True # If the whole line is whitespace, that means the user probably finished an # identifier on the previous line. return line[ : current_column ].isspace() def LastEnteredCharIsIdentifierChar(): line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn() if current_column - 1 < 0: return False filetype = vimsupport.CurrentFiletypes()[ 0 ] return ( identifier_utils.StartOfLongestIdentifierEndingAtIndex( line, current_column, filetype ) != current_column ) def AdjustCandidateInsertionText( candidates ): """This function adjusts the candidate insertion text to take into account the text that's currently in front of the cursor. For instance ('|' represents the cursor): 1. Buffer state: 'foo.|bar' 2. A completion candidate of 'zoobar' is shown and the user selects it. 3. Buffer state: 'foo.zoobar|bar' instead of 'foo.zoo|bar' which is what the user wanted. This function changes candidates to resolve that issue. It could be argued that the user actually wants the final buffer state to be 'foo.zoobar|' (the cursor at the end), but that would be much more difficult to implement and is probably not worth doing. """ def NewCandidateInsertionText( to_insert, text_after_cursor ): overlap_len = OverlapLength( to_insert, text_after_cursor ) if overlap_len: return to_insert[ :-overlap_len ] return to_insert text_after_cursor = vimsupport.TextAfterCursor() if not text_after_cursor: return candidates new_candidates = [] for candidate in candidates: new_candidate = candidate.copy() if not new_candidate.get( 'abbr' ): new_candidate[ 'abbr' ] = new_candidate[ 'word' ] new_candidate[ 'word' ] = NewCandidateInsertionText( new_candidate[ 'word' ], text_after_cursor ) new_candidates.append( new_candidate ) 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 ================================================ FILE: python/ycm/buffer.py ================================================ # Copyright (C) 2016, Davit Samvelyan # # 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.client.event_notification import EventNotification from ycm.diagnostic_interface import DiagnosticInterface from ycm.semantic_highlighting import SemanticHighlighting from ycm.inlay_hints import InlayHints # Emulates Vim buffer # Used to store buffer related information like diagnostics, latest parse # request. Stores buffer change tick at the parse request moment, allowing # to effectively determine whether reparse is needed for the buffer. class Buffer: def __init__( self, bufnr, user_options, filetypes ): self._number = bufnr self._parse_tick = 0 self._handled_tick = 0 self._parse_request = None self._should_resend = False self._diag_interface = DiagnosticInterface( bufnr, user_options ) self._open_loclist_on_ycm_diags = user_options[ 'open_loclist_on_ycm_diags' ] self.semantic_highlighting = SemanticHighlighting( bufnr ) self.inlay_hints = InlayHints( bufnr ) self.UpdateFromFileTypes( filetypes ) def FileParseRequestReady( self, block = False ): return ( bool( self._parse_request ) and ( block or self._parse_request.Done() ) ) def SendParseRequest( self, extra_data ): # Don't send a parse request if one is in progress if self._parse_request is not None and not self._parse_request.Done(): self._should_resend = True return self._should_resend = False self._parse_request = EventNotification( 'FileReadyToParse', extra_data = extra_data ) self._parse_request.Start() # Decrement handled tick to ensure correct handling when we are forcing # reparse on buffer visit and changed tick remains the same. self._handled_tick -= 1 self._parse_tick = self._ChangedTick() def ParseRequestPending( self ): return bool( self._parse_request ) and not self._parse_request.Done() def NeedsReparse( self ): return self._parse_tick != self._ChangedTick() def ShouldResendParseRequest( self ): return ( self._should_resend or ( bool( self._parse_request ) and self._parse_request.ShouldResend() ) ) def UpdateDiagnostics( self, force = False ): if force or not self._async_diags: self.UpdateWithNewDiagnostics( self._parse_request.Response(), False ) else: # We need to call the response method, because it might throw an exception # or require extra config confirmation, even if we don't actually use the # diagnostics. self._parse_request.Response() def UpdateWithNewDiagnostics( self, diagnostics, async_message ): self._async_diags = async_message self._diag_interface.UpdateWithNewDiagnostics( diagnostics, not self._async_diags and self._open_loclist_on_ycm_diags ) def UpdateMatches( self ): self._diag_interface.UpdateMatches() def PopulateLocationList( self, open_on_edit = False ): return self._diag_interface.PopulateLocationList( open_on_edit ) def GetResponse( self ): return self._parse_request.Response() def IsResponseHandled( self ): return self._handled_tick == self._parse_tick def MarkResponseHandled( self ): self._handled_tick = self._parse_tick def OnCursorMoved( self ): self._diag_interface.OnCursorMoved() def GetErrorCount( self ): return self._diag_interface.GetErrorCount() def GetWarningCount( self ): return self._diag_interface.GetWarningCount() def RefreshDiagnosticsUI( self ): return self._diag_interface.RefreshDiagnosticsUI() def ClearDiagnosticsUI( self ): return self._diag_interface.ClearDiagnosticsUI() def DiagnosticsForLine( self, line_number ): return self._diag_interface.DiagnosticsForLine( line_number ) def UpdateFromFileTypes( self, filetypes ): self._filetypes = filetypes # We will set this to true if we ever receive any diagnostics asyncronously. self._async_diags = False def _ChangedTick( self ): return vimsupport.GetBufferChangedTick( self._number ) class BufferDict( dict ): def __init__( self, user_options ): self._user_options = user_options def __missing__( self, key ): # Python does not allow to return assignment operation result directly new_value = self[ key ] = Buffer( key, self._user_options, vimsupport.GetBufferFiletypes( key ) ) return new_value ================================================ FILE: python/ycm/client/__init__.py ================================================ ================================================ FILE: python/ycm/client/base_request.py ================================================ # Copyright (C) 2013-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import logging import json import vim from base64 import b64decode, b64encode from hmac import compare_digest from urllib.parse import urljoin, urlparse, urlencode from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError from ycm import vimsupport from ycmd.utils import ToBytes, GetCurrentDirectory, ToUnicode from ycmd.hmac_utils import CreateRequestHmac, CreateHmac from ycmd.responses import ServerError, UnknownExtraConf HTTP_SERVER_ERROR = 500 _HEADERS = { 'content-type': 'application/json' } _CONNECT_TIMEOUT_SEC = 0.01 # Setting this to None seems to screw up the Requests/urllib3 libs. _READ_TIMEOUT_SEC = 30 _HMAC_HEADER = 'x-ycm-hmac' _logger = logging.getLogger( __name__ ) class BaseRequest: def __init__( self ): self._should_resend = False def Start( self ): pass def Done( self ): return True def Response( self ): return {} def ShouldResend( self ): return self._should_resend def HandleFuture( self, future, display_message = True, truncate_message = False ): """Get the server response from a |future| object and catch any exception while doing so. If an exception is raised because of a unknown .ycm_extra_conf.py file, load the file or ignore it after asking the user. An identical request should be sent again to the server. For other exceptions, log the exception and display its message to the user on the Vim status line. Unset the |display_message| parameter to hide the message from the user. Set the |truncate_message| parameter to avoid hit-enter prompts from this message.""" try: try: return _JsonFromFuture( future ) except UnknownExtraConf as e: if vimsupport.Confirm( str( e ) ): _LoadExtraConfFile( e.extra_conf_file ) else: _IgnoreExtraConfFile( e.extra_conf_file ) self._should_resend = True except URLError as e: # We don't display this exception to the user since it is likely to happen # for each subsequent request (typically if the server crashed) and we # don't want to spam the user with it. _logger.error( e ) except Exception as e: _logger.exception( 'Error while handling server response' ) if display_message: DisplayServerException( e, truncate_message ) return None # 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). # See the HandleFuture method for the |display_message| and |truncate_message| # parameters. def GetDataFromHandler( self, handler, timeout = _READ_TIMEOUT_SEC, display_message = True, truncate_message = False, payload = None ): return self.HandleFuture( self.GetDataFromHandlerAsync( handler, timeout, payload ), display_message, truncate_message ) def GetDataFromHandlerAsync( self, handler, timeout = _READ_TIMEOUT_SEC, payload = None ): return BaseRequest._TalkToHandlerAsync( '', handler, 'GET', timeout, payload ) # 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). # See the HandleFuture method for the |display_message| and |truncate_message| # parameters. def PostDataToHandler( self, data, handler, timeout = _READ_TIMEOUT_SEC, display_message = True, truncate_message = False ): return self.HandleFuture( BaseRequest.PostDataToHandlerAsync( data, handler, timeout ), display_message, truncate_message ) # This returns a future! Use HandleFuture 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 = _READ_TIMEOUT_SEC ): return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout ) # This returns a future! Use HandleFuture 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 = _READ_TIMEOUT_SEC, payload = None ): def _MakeRequest( data, handler, method, timeout, payload ): request_uri = _BuildUri( handler ) if method == 'POST': sent_data = _ToUtf8Json( data ) headers = BaseRequest._ExtraHeaders( method, request_uri, sent_data ) _logger.debug( 'POST %s\n%s\n%s', request_uri, headers, sent_data ) else: headers = BaseRequest._ExtraHeaders( method, request_uri ) if payload: request_uri += ToBytes( f'?{ urlencode( payload ) }' ) _logger.debug( 'GET %s (%s)\n%s', request_uri, payload, headers ) return urlopen( Request( ToUnicode( request_uri ), data = sent_data if data else None, headers = headers, method = method ), timeout = max( _CONNECT_TIMEOUT_SEC, timeout ) ) return BaseRequest.Executor().submit( _MakeRequest, data, handler, method, timeout, payload ) @staticmethod def _ExtraHeaders( method, request_uri, request_body = None ): if not request_body: request_body = bytes( b'' ) headers = dict( _HEADERS ) headers[ _HMAC_HEADER ] = b64encode( CreateRequestHmac( ToBytes( method ), ToBytes( urlparse( request_uri ).path ), request_body, BaseRequest.hmac_secret ) ) return headers # This method exists to avoid importing the requests module at startup; # reducing loading time since this module is slow to import. @classmethod def Executor( cls ): try: return cls.executor except AttributeError: from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor cls.executor = UnsafeThreadPoolExecutor( max_workers = 30 ) return cls.executor server_location = '' hmac_secret = '' def BuildRequestData( buffer_number = None ): """Build request for the current buffer or the buffer with number |buffer_number| if specified.""" working_dir = GetCurrentDirectory() current_buffer = vim.current.buffer if buffer_number and current_buffer.number != buffer_number: # Cursor position is irrelevant when filepath is not the current buffer. buffer_object = vim.buffers[ buffer_number ] filepath = vimsupport.GetBufferFilepath( buffer_object ) return { 'filepath': filepath, 'line_num': 1, 'column_num': 1, 'working_dir': working_dir, 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object, filepath ) } current_filepath = vimsupport.GetBufferFilepath( current_buffer ) line, column = vimsupport.CurrentLineAndColumn() return { 'filepath': current_filepath, 'line_num': line + 1, 'column_num': column + 1, 'working_dir': working_dir, 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer, current_filepath ) } def BuildRequestDataForLocation( file : str, line : int, column : int ): buffer_number = vimsupport.GetBufferNumberForFilename( file, create_buffer_if_needed = True ) try: vim.eval( f'bufload( "{ file }" )' ) except vim.error as e: if 'E325' not in str( e ): raise buffer = vim.buffers[ buffer_number ] file_data = vimsupport.GetUnsavedAndSpecifiedBufferData( buffer, file ) return { 'filepath': file, 'line_num': line, 'column_num': column, 'working_dir': GetCurrentDirectory(), 'file_data': file_data } def _JsonFromFuture( future ): try: response = future.result() response_text = response.read() _ValidateResponseObject( response, response_text ) response.close() if response_text: return json.loads( response_text ) return None except HTTPError as response: if response.code == HTTP_SERVER_ERROR: response_text = response.read() response.close() if response_text: raise MakeServerException( json.loads( response_text ) ) else: return None raise def _LoadExtraConfFile( filepath ): BaseRequest().PostDataToHandler( { 'filepath': filepath }, 'load_extra_conf_file' ) def _IgnoreExtraConfFile( filepath ): BaseRequest().PostDataToHandler( { 'filepath': filepath }, 'ignore_extra_conf_file' ) def DisplayServerException( exception, truncate_message = False ): serialized_exception = str( exception ) # We ignore the exception about the file already being parsed since it comes # up often and isn't something that's actionable by the user. if 'already being parsed' in serialized_exception: return vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message ) def _ToUtf8Json( data ): return ToBytes( json.dumps( data ) if data else None ) def _ValidateResponseObject( response, response_text ): if not response_text: return our_hmac = CreateHmac( response_text, BaseRequest.hmac_secret ) their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) ) if not compare_digest( our_hmac, their_hmac ): raise RuntimeError( 'Received invalid HMAC for response!' ) def _BuildUri( handler ): return ToBytes( urljoin( BaseRequest.server_location, handler ) ) def MakeServerException( data ): _logger.debug( 'Server exception: %s', data ) if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__: return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] ) return ServerError( f'{ data[ "exception" ][ "TYPE" ] }: ' f'{ data[ "message" ] }' ) ================================================ FILE: python/ycm/client/command_request.py ================================================ # 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.base_request import ( BaseRequest, BuildRequestData, BuildRequestDataForLocation ) from ycm import vimsupport DEFAULT_BUFFER_COMMAND = 'same-buffer' def _EnsureBackwardsCompatibility( arguments ): if arguments and arguments[ 0 ] == 'GoToDefinitionElseDeclaration': arguments[ 0 ] = 'GoTo' return arguments class CommandRequest( BaseRequest ): def __init__( self, arguments, extra_data = None, silent = False, location = None ): super( CommandRequest, self ).__init__() self._arguments = _EnsureBackwardsCompatibility( arguments ) self._command = arguments and arguments[ 0 ] self._extra_data = extra_data self._response = None self._request_data = None self._response_future = None self._silent = silent self._bufnr = extra_data.pop( 'bufnr', None ) if extra_data else None self._location = location def Start( self ): if self._location is not None: self._request_data = BuildRequestDataForLocation( *self._location ) elif self._bufnr is not None: self._request_data = BuildRequestData( self._bufnr ) else: self._request_data = BuildRequestData() if self._extra_data: self._request_data.update( self._extra_data ) self._request_data.update( { 'command_arguments': self._arguments } ) self._response_future = self.PostDataToHandlerAsync( self._request_data, 'run_completer_command' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def Response( self ): if self._response is None and self._response_future is not None: # Block self._response = self.HandleFuture( self._response_future, display_message = not self._silent ) return self._response def RunPostCommandActionsIfNeeded( self, modifiers, buffer_command = DEFAULT_BUFFER_COMMAND ): # This is a blocking call if not Done() self.Response() if self._response is None: # An exception was raised and handled. return # If not a dictionary or a list, the response is necessarily a # scalar: boolean, number, string, etc. In this case, we print # it to the user. if not isinstance( self._response, ( dict, list ) ): return self._HandleBasicResponse() if 'fixits' in self._response: return self._HandleFixitResponse() if 'message' in self._response: return self._HandleMessageResponse() if 'detailed_info' in self._response: return self._HandleDetailedInfoResponse( modifiers ) # The only other type of response we understand is GoTo, and that is the # only one that we can't detect just by inspecting the response (it should # either be a single location or a list) return self._HandleGotoResponse( buffer_command, modifiers ) def StringResponse( self ): # Retuns a supporable public API version of the response. The reason this # exists is that the ycmd API here is wonky as it originally only supported # text-responses and now has things like fixits and such. # # The supportable public API is basically any text-only response. All other # response types are returned as empty strings # This is a blocking call if not Done() self.Response() # Completer threw an error ? if self._response is None: return "" # If not a dictionary or a list, the response is necessarily a # scalar: boolean, number, string, etc. In this case, we print # it to the user. if not isinstance( self._response, ( dict, list ) ): return str( self._response ) if 'message' in self._response: return self._response[ 'message' ] if 'detailed_info' in self._response: return self._response[ 'detailed_info' ] # The only other type of response we understand is 'fixits' and GoTo. We # don't provide string versions of them. return "" def _HandleGotoResponse( self, buffer_command, modifiers ): if isinstance( self._response, list ): vimsupport.SetQuickFixList( [ vimsupport.BuildQfListItem( x ) for x in self._response ] ) vimsupport.OpenQuickFixList( focus = True, autoclose = True ) elif self._response.get( 'file_only' ): vimsupport.JumpToLocation( self._response[ 'filepath' ], None, None, modifiers, buffer_command ) else: vimsupport.JumpToLocation( self._response[ 'filepath' ], self._response[ 'line_num' ], self._response[ 'column_num' ], modifiers, buffer_command ) def _HandleFixitResponse( self ): if not len( self._response[ 'fixits' ] ): vimsupport.PostVimMessage( 'No fixits found for current line', warning = False ) else: try: fixit_index = 0 # If there is more than one fixit, we need to ask the user which one # should be applied. # # If there's only one, triggered by the FixIt subcommand (as opposed to # `RefactorRename`, for example) and whose `kind` is not `quicfix`, we # still need to as the user for confirmation. fixits = self._response[ 'fixits' ] if ( len( fixits ) > 1 or ( len( fixits ) == 1 and self._command == 'FixIt' and fixits[ 0 ].get( 'kind' ) != 'quickfix' ) ): fixit_index = vimsupport.SelectFromList( "FixIt suggestion(s) available at this location. " "Which one would you like to apply?", [ fixit[ 'text' ] for fixit in fixits ] ) chosen_fixit = fixits[ fixit_index ] if chosen_fixit[ 'resolve' ]: self._request_data.update( { 'fixit': chosen_fixit } ) response = self.PostDataToHandler( self._request_data, 'resolve_fixit' ) if response is None: return fixits = response[ 'fixits' ] assert len( fixits ) == 1 chosen_fixit = fixits[ 0 ] vimsupport.ReplaceChunks( chosen_fixit[ 'chunks' ], silent = self._command == 'Format' ) except RuntimeError as e: vimsupport.PostVimMessage( str( e ) ) def _HandleBasicResponse( self ): vimsupport.PostVimMessage( self._response, warning = False ) def _HandleMessageResponse( self ): vimsupport.PostVimMessage( self._response[ 'message' ], warning = False ) def _HandleDetailedInfoResponse( self, modifiers ): vimsupport.WriteToPreviewWindow( self._response[ 'detailed_info' ], modifiers ) def SendCommandRequestAsync( arguments, extra_data = None, silent = True, location = None ): request = CommandRequest( arguments, extra_data = extra_data, silent = silent, location = location ) request.Start() # Don't block return request def SendCommandRequest( arguments, modifiers, buffer_command = DEFAULT_BUFFER_COMMAND, extra_data = None, skip_post_command_action = False ): request = SendCommandRequestAsync( arguments, extra_data = extra_data, silent = False ) # Block here to get the response if not skip_post_command_action: request.RunPostCommandActionsIfNeeded( modifiers, buffer_command ) return request.Response() def GetCommandResponse( arguments, extra_data = None ): request = SendCommandRequestAsync( arguments, extra_data = extra_data, silent = True ) # Block here to get the response return request.StringResponse() def GetRawCommandResponse( arguments, silent, location = None ): request = SendCommandRequestAsync( arguments, extra_data = None, silent = silent, location = location ) return request.Response() ================================================ FILE: python/ycm/client/completer_available_request.py ================================================ # 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.base_request import BaseRequest, BuildRequestData class CompleterAvailableRequest( BaseRequest ): def __init__( self, filetypes ): super( CompleterAvailableRequest, self ).__init__() self.filetypes = filetypes self._response = None def Start( self ): request_data = BuildRequestData() request_data.update( { 'filetypes': self.filetypes } ) self._response = self.PostDataToHandler( request_data, 'semantic_completion_available' ) def Response( self ): return self._response def SendCompleterAvailableRequest( filetypes ): request = CompleterAvailableRequest( filetypes ) # This is a blocking call. request.Start() return request.Response() ================================================ FILE: python/ycm/client/completion_request.py ================================================ # Copyright (C) 2013-2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import json import logging from ycmd.utils import ToUnicode from ycm.client.base_request import ( BaseRequest, DisplayServerException, MakeServerException ) from ycm import vimsupport, base from ycm.vimsupport import NO_COMPLETIONS _logger = logging.getLogger( __name__ ) class CompletionRequest( BaseRequest ): def __init__( self, request_data ): super().__init__() self.request_data = request_data self._response_future = None def Start( self ): self._response_future = self.PostDataToHandlerAsync( self.request_data, 'completions' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def _RawResponse( self ): if not self._response_future: return NO_COMPLETIONS response = self.HandleFuture( self._response_future, truncate_message = True ) if not response: return NO_COMPLETIONS # Vim may not be able to convert the 'errors' entry to its internal format # so we remove it from the response. errors = response.pop( 'errors', [] ) for e in errors: exception = MakeServerException( e ) _logger.error( exception ) DisplayServerException( exception, truncate_message = True ) response[ 'line' ] = self.request_data[ 'line_num' ] response[ 'column' ] = self.request_data[ 'column_num' ] return response def Response( self ): response = self._RawResponse() response[ 'completions' ] = _ConvertCompletionDatasToVimDatas( response[ 'completions' ] ) # FIXME: Do we really need to do this AdjustCandidateInsertionText ? I feel # like Vim should do that for us response[ 'completions' ] = base.AdjustCandidateInsertionText( response[ 'completions' ] ) return response def OnCompleteDone( self ): if not self.Done(): return if 'cs' in vimsupport.CurrentFiletypes(): self._OnCompleteDone_Csharp() else: self._OnCompleteDone_FixIt() def _GetExtraDataUserMayHaveCompleted( self ): completed_item = vimsupport.GetVariableValue( 'v:completed_item' ) # If Vim supports user_data (8.0.1493 or later), we actually know the # _exact_ element that was selected, having put its extra_data in the # user_data field. Otherwise, we have to guess by matching the values in the # completed item and the list of completions. Sometimes this returns # multiple possibilities, which is essentially unresolvable. if 'user_data' not in completed_item: completions = self._RawResponse()[ 'completions' ] return _FilterToMatchingCompletions( completed_item, completions ) if completed_item[ 'user_data' ]: return [ json.loads( completed_item[ 'user_data' ] ) ] return [] def _OnCompleteDone_Csharp( self ): extra_datas = self._GetExtraDataUserMayHaveCompleted() namespaces = [ _GetRequiredNamespaceImport( c ) for c in extra_datas ] namespaces = [ n for n in namespaces if n ] if not namespaces: return if len( namespaces ) > 1: choices = [ f"{ i + 1 } { n }" for i, n in enumerate( namespaces ) ] choice = vimsupport.PresentDialog( "Insert which namespace:", choices ) if choice < 0: return namespace = namespaces[ choice ] else: namespace = namespaces[ 0 ] vimsupport.InsertNamespace( namespace ) def _OnCompleteDone_FixIt( self ): extra_datas = self._GetExtraDataUserMayHaveCompleted() fixit_completions = [ _GetFixItCompletion( c ) for c in extra_datas ] fixit_completions = [ f for f in fixit_completions if f ] if not fixit_completions: return # If we have user_data in completions (8.0.1493 or later), then we would # only ever return max. 1 completion here. However, if we had to guess, it # is possible that we matched multiple completion items (e.g. for overloads, # or similar classes in multiple packages). In any case, rather than # prompting the user and disturbing her workflow, we just apply the first # one. This might be wrong, but the solution is to use a (very) new version # of Vim which supports user_data on completion items fixit_completion = fixit_completions[ 0 ] for fixit in fixit_completion: vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True ) def _GetRequiredNamespaceImport( extra_data ): return extra_data.get( 'required_namespace_import' ) def _GetFixItCompletion( extra_data ): return extra_data.get( 'fixits' ) def _FilterToMatchingCompletions( completed_item, completions ): """Filter to completions matching the item Vim said was completed""" match_keys = [ 'word', 'abbr', 'menu', 'info' ] matched_completions = [] for completion in completions: item = ConvertCompletionDataToVimData( completion ) def matcher( key ): return ( ToUnicode( completed_item.get( key, "" ) ) == ToUnicode( item.get( key, "" ) ) ) if all( matcher( i ) for i in match_keys ): matched_completions.append( completion.get( 'extra_data', {} ) ) return matched_completions def _GetCompletionInfoField( completion_data ): info = completion_data.get( 'detailed_info', '' ) if 'extra_data' in completion_data: docstring = completion_data[ 'extra_data' ].get( 'doc_string', '' ) if docstring: if info: info += '\n' + docstring else: info = docstring # This field may contain null characters e.g. \x00 in Python docstrings. Vim # cannot evaluate such characters so they are removed. return info.replace( '\x00', '' ) def ConvertCompletionDataToVimData( completion_data ): # See :h complete-items for a description of the dictionary fields. extra_menu_info = completion_data.get( 'extra_menu_info', '' ) preview_info = _GetCompletionInfoField( completion_data ) # When we are using a popup for the preview_info, it needs to fit on the # screen alongside the extra_menu_info. Let's use some heuristics. If the # length of the extra_menu_info is more than, say, 1/3 of screen, truncate it # and stick it in the preview_info. if vimsupport.UsingPreviewPopup(): max_width = max( int( vimsupport.DisplayWidth() / 3 ), 3 ) extra_menu_info_width = vimsupport.DisplayWidthOfString( extra_menu_info ) if extra_menu_info_width > max_width: if not preview_info.startswith( extra_menu_info ): preview_info = extra_menu_info + '\n\n' + preview_info extra_menu_info = extra_menu_info[ : ( max_width - 3 ) ] + '...' return { 'word' : completion_data[ 'insertion_text' ], 'abbr' : completion_data.get( 'menu_text', '' ), 'menu' : extra_menu_info, 'info' : preview_info, 'kind' : ToUnicode( completion_data.get( 'kind', '' ) )[ :1 ].lower(), # Disable Vim filtering. 'equal' : 1, 'dup' : 1, 'empty' : 1, # We store the completion item extra_data as a string in the completion # user_data. This allows us to identify the _exact_ item that was completed # in the CompleteDone handler, by inspecting this item from v:completed_item # # We convert to string because completion user data items must be strings. # # Note: Not all versions of Vim support this (added in 8.0.1483), but adding # the item to the dictionary is harmless in earlier Vims. # Note: Since 8.2.0084 we don't need to use json.dumps() here. 'user_data': json.dumps( completion_data.get( 'extra_data', {} ) ) } def _ConvertCompletionDatasToVimDatas( response_data ): return [ ConvertCompletionDataToVimData( x ) for x in response_data ] ================================================ FILE: python/ycm/client/debug_info_request.py ================================================ # Copyright (C) 2016-2017 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.base_request import BaseRequest, BuildRequestData class DebugInfoRequest( BaseRequest ): def __init__( self, extra_data = None ): super( DebugInfoRequest, self ).__init__() self._extra_data = extra_data self._response = None def Start( self ): request_data = BuildRequestData() if self._extra_data: request_data.update( self._extra_data ) self._response = self.PostDataToHandler( request_data, 'debug_info', display_message = False ) def Response( self ): return self._response def FormatDebugInfoResponse( response ): if not response: return 'Server errored, no debug info from server\n' message = _FormatYcmdDebugInfo( response ) completer = response[ 'completer' ] if completer: message += _FormatCompleterDebugInfo( completer ) return message def _FormatYcmdDebugInfo( ycmd ): python = ycmd[ 'python' ] clang = ycmd[ 'clang' ] message = ( f'Server Python interpreter: { python[ "executable" ] }\n' f'Server Python version: { python[ "version" ] }\n' f'Server has Clang support compiled in: { clang[ "has_support" ] }\n' f'Clang version: { clang[ "version" ] }\n' ) extra_conf = ycmd[ 'extra_conf' ] extra_conf_path = extra_conf[ 'path' ] if not extra_conf_path: message += 'No extra configuration file found\n' elif not extra_conf[ 'is_loaded' ]: message += ( 'Extra configuration file found but not loaded\n' f'Extra configuration path: { extra_conf_path }\n' ) else: message += ( 'Extra configuration file found and loaded\n' f'Extra configuration path: { extra_conf_path }\n' ) return message def _FormatCompleterDebugInfo( completer ): message = f'{ completer[ "name" ] } completer debug information:\n' for server in completer[ 'servers' ]: name = server[ 'name' ] if server[ 'is_running' ]: address = server[ 'address' ] port = server[ 'port' ] if address and port: message += f' { name } running at: http://{ address }:{ port }\n' else: message += f' { name } running\n' message += f' { name } process ID: { server[ "pid" ] }\n' else: message += f' { name } not running\n' message += f' { name } executable: { server[ "executable" ] }\n' logfiles = server[ 'logfiles' ] if logfiles: message += f' { name } logfiles:\n' for logfile in logfiles: message += f' { logfile }\n' else: message += ' No logfiles available\n' if 'extras' in server: for extra in server[ 'extras' ]: message += f' { name } { extra[ "key" ] }: { extra[ "value" ] }\n' for item in completer[ 'items' ]: message += f' { item[ "key" ].capitalize() }: { item[ "value" ] }\n' return message def SendDebugInfoRequest( extra_data = None ): request = DebugInfoRequest( extra_data ) # This is a blocking call. request.Start() return request.Response() ================================================ FILE: python/ycm/client/event_notification.py ================================================ # Copyright (C) 2013-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.base_request import BaseRequest, BuildRequestData class EventNotification( BaseRequest ): def __init__( self, event_name, buffer_number = None, extra_data = None ): super( EventNotification, self ).__init__() self._event_name = event_name self._buffer_number = buffer_number self._extra_data = extra_data self._response_future = None self._cached_response = None def Start( self ): request_data = BuildRequestData( self._buffer_number ) 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 bool( self._response_future ) and 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 [] self._cached_response = self.HandleFuture( self._response_future, truncate_message = True ) return self._cached_response if self._cached_response else [] def SendEventNotificationAsync( event_name, buffer_number = None, extra_data = None ): event = EventNotification( event_name, buffer_number, extra_data ) event.Start() ================================================ FILE: python/ycm/client/inlay_hints_request.py ================================================ # Copyright (C) 2022, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import logging from ycm.client.base_request import ( BaseRequest, DisplayServerException, MakeServerException ) _logger = logging.getLogger( __name__ ) # FIXME: This is copy/pasta from SemanticTokensRequest - abstract a # SimpleAsyncRequest base that does all of this generically class InlayHintsRequest( BaseRequest ): def __init__( self, request_data ): super().__init__() self.request_data = request_data self._response_future = None def Start( self ): self._response_future = self.PostDataToHandlerAsync( self.request_data, 'inlay_hints' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def Reset( self ): self._response_future = None def Response( self ): if not self._response_future: return [] response = self.HandleFuture( self._response_future, truncate_message = True ) if not response: return [] # Vim may not be able to convert the 'errors' entry to its internal format # so we remove it from the response. errors = response.pop( 'errors', [] ) for e in errors: exception = MakeServerException( e ) _logger.error( exception ) DisplayServerException( exception, truncate_message = True ) return response.get( 'inlay_hints' ) or [] ================================================ FILE: python/ycm/client/messages_request.py ================================================ # Copyright (C) 2017 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.base_request import BaseRequest, BuildRequestData from ycm.vimsupport import PostVimMessage import logging _logger = logging.getLogger( __name__ ) # Looooong poll TIMEOUT_SECONDS = 60 class MessagesPoll( BaseRequest ): def __init__( self, buff ): super( MessagesPoll, self ).__init__() self._request_data = BuildRequestData( buff.number ) self._response_future = None def _SendRequest( self ): self._response_future = self.PostDataToHandlerAsync( self._request_data, 'receive_messages', timeout = TIMEOUT_SECONDS ) return def Poll( self, diagnostics_handler ): """This should be called regularly to check for new messages in this buffer. Returns True if Poll should be called again in a while. Returns False when the completer or server indicated that further polling should not be done for the requested file.""" if self._response_future is None: # First poll self._SendRequest() return True if not self._response_future.done(): # Nothing yet... return True response = self.HandleFuture( self._response_future, display_message = False ) if response is None: # Server returned an exception. return False poll_again = _HandlePollResponse( response, diagnostics_handler ) if poll_again: self._SendRequest() return True return False def _HandlePollResponse( response, diagnostics_handler ): if isinstance( response, list ): for notification in response: if 'message' in notification: PostVimMessage( notification[ 'message' ], warning = False, truncate = True ) elif 'diagnostics' in notification: diagnostics_handler.UpdateWithNewDiagnosticsForFile( notification[ 'filepath' ], notification[ 'diagnostics' ] ) elif response is False: # Don't keep polling for this file return False # else any truthy response means "nothing to see here; poll again in a # while" # Start the next poll (only if the last poll didn't raise an exception) return True ================================================ FILE: python/ycm/client/omni_completion_request.py ================================================ # 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, request_data ): super( OmniCompletionRequest, self ).__init__( request_data ) self._omni_completer = omni_completer def Start( self ): self._results = self._omni_completer.ComputeCandidates( self.request_data ) def Done( self ): return True def Response( self ): return { 'line': self.request_data[ 'line_num' ], 'column': self.request_data[ 'column_num' ], 'completion_start_column': self.request_data[ 'start_column' ], 'completions': self._results } def OnCompleteDone( self ): pass ================================================ FILE: python/ycm/client/resolve_completion_request.py ================================================ # Copyright (C) 2020 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.base_request import ( BaseRequest, DisplayServerException, MakeServerException ) from ycm.client.completion_request import ( CompletionRequest, ConvertCompletionDataToVimData ) import logging import json _logger = logging.getLogger( __name__ ) class ResolveCompletionRequest( BaseRequest ): def __init__( self, completion_request: CompletionRequest, request_data ): super().__init__() self.request_data = request_data self.completion_request = completion_request def Start( self ): self._response_future = self.PostDataToHandlerAsync( self.request_data, 'resolve_completion' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def OnCompleteDone( self ): # This is required to be compatible with the "CompletionRequest" API. We're # not really a CompletionRequest, but we are mutually exclusive with # completion requests, so we implement this API by delegating to the # original completion request, which contains all of the code for actually # handling things like automatic imports etc. self.completion_request.OnCompleteDone() def Response( self ): response = self.HandleFuture( self._response_future, truncate_message = True, display_message = True ) if not response or not response[ 'completion' ]: return { 'completion': [] } # Vim may not be able to convert the 'errors' entry to its internal format # so we remove it from the response. errors = response.pop( 'errors', [] ) for e in errors: exception = MakeServerException( e ) _logger.error( exception ) DisplayServerException( exception, truncate_message = True ) response[ 'completion' ] = ConvertCompletionDataToVimData( response[ 'completion' ] ) return response def ResolveCompletionItem( completion_request, item ): if not completion_request.Done(): return None try: completion_extra_data = json.loads( item[ 'user_data' ] ) except KeyError: return None except ( TypeError, json.JSONDecodeError ): # Can happen with the omni completer return None request_data = completion_request.request_data try: # Note: We mutate the request_data inside the original completion request # and pass it into the new request object. this is just a big efficiency # saving. The request_data for a Done() request is almost certainly no # longer needed. request_data[ 'resolve' ] = completion_extra_data[ 'resolve' ] except KeyError: return None resolve_request = ResolveCompletionRequest( completion_request, request_data ) resolve_request.Start() return resolve_request ================================================ FILE: python/ycm/client/semantic_tokens_request.py ================================================ # Copyright (C) 2020, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import logging from ycm.client.base_request import ( BaseRequest, DisplayServerException, MakeServerException ) _logger = logging.getLogger( __name__ ) # FIXME: This is copy/pasta from SignatureHelpRequest - abstract a # SimpleAsyncRequest base that does all of this generically class SemanticTokensRequest( BaseRequest ): def __init__( self, request_data ): super().__init__() self.request_data = request_data self._response_future = None def Start( self ): self._response_future = self.PostDataToHandlerAsync( self.request_data, 'semantic_tokens' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def Reset( self ): self._response_future = None def Response( self ): if not self._response_future: return {} response = self.HandleFuture( self._response_future, truncate_message = True ) if not response: return {} # Vim may not be able to convert the 'errors' entry to its internal format # so we remove it from the response. errors = response.pop( 'errors', [] ) for e in errors: exception = MakeServerException( e ) _logger.error( exception ) DisplayServerException( exception, truncate_message = True ) return response.get( 'semantic_tokens' ) or {} ================================================ FILE: python/ycm/client/shutdown_request.py ================================================ # Copyright (C) 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.base_request import BaseRequest TIMEOUT_SECONDS = 0.1 class ShutdownRequest( BaseRequest ): def __init__( self ): super( ShutdownRequest, self ).__init__() def Start( self ): self.PostDataToHandler( {}, 'shutdown', TIMEOUT_SECONDS, display_message = False ) def SendShutdownRequest(): request = ShutdownRequest() # This is a blocking call. request.Start() ================================================ FILE: python/ycm/client/signature_help_request.py ================================================ # Copyright (C) 2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import logging from ycm.client.base_request import ( BaseRequest, DisplayServerException, MakeServerException ) _logger = logging.getLogger( __name__ ) class SigHelpAvailableByFileType( dict ): def __missing__( self, filetype ): request = SignatureHelpAvailableRequest( filetype ) self[ filetype ] = request return request class SignatureHelpRequest( BaseRequest ): def __init__( self, request_data ): super( SignatureHelpRequest, self ).__init__() self.request_data = request_data self._response_future = None self._response = None def Start( self ): self._response_future = self.PostDataToHandlerAsync( self.request_data, 'signature_help' ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def Reset( self ): self._response_future = None def Response( self ): if self._response is None: self._response = self._Response() return self._response def _Response( self ): if not self._response_future: return {} response = self.HandleFuture( self._response_future, truncate_message = True ) if not response: return {} # Vim may not be able to convert the 'errors' entry to its internal format # so we remove it from the response. errors = response.pop( 'errors', [] ) for e in errors: exception = MakeServerException( e ) _logger.error( exception ) DisplayServerException( exception, truncate_message = True ) return response.get( 'signature_help' ) or {} class SignatureHelpAvailableRequest( BaseRequest ): def __init__( self, filetype ): super( SignatureHelpAvailableRequest, self ).__init__() self._response_future = None self.Start( filetype ) def Done( self ): return bool( self._response_future ) and self._response_future.done() def Response( self ): if not self._response_future: return None response = self.HandleFuture( self._response_future, truncate_message = True ) if not response: return None return response[ 'available' ] def Start( self, filetype ): self._response_future = self.GetDataFromHandlerAsync( 'signature_help_available', payload = { 'subserver': filetype } ) ================================================ FILE: python/ycm/client/ycmd_keepalive.py ================================================ # 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: 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 ) BaseRequest().GetDataFromHandler( 'healthy', display_message = False ) ================================================ FILE: python/ycm/diagnostic_filter.py ================================================ # Copyright (C) 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import re class DiagnosticFilter: def __init__( self, config_or_filters ): self._filters : list = config_or_filters def IsAllowed( self, diagnostic ): return not any( filterMatches( diagnostic ) for filterMatches in self._filters ) @staticmethod def CreateFromOptions( user_options ): all_filters = user_options[ 'filter_diagnostics' ] compiled_by_type = {} for type_spec, filter_value in all_filters.items(): filetypes = type_spec.split( ',' ) for filetype in filetypes: compiled_by_type[ filetype ] = _CompileFilters( filter_value ) return _MasterDiagnosticFilter( compiled_by_type ) class _MasterDiagnosticFilter: def __init__( self, all_filters ): self._all_filters = all_filters self._cache = {} def SubsetForTypes( self, filetypes ): # check cache cache_key = ','.join( filetypes ) cached = self._cache.get( cache_key ) if cached is not None: return cached # build a new DiagnosticFilter merging all filters # for the provided filetypes spec = [] for filetype in filetypes: type_specific = self._all_filters.get( filetype, [] ) spec.extend( type_specific ) new_filter = DiagnosticFilter( spec ) self._cache[ cache_key ] = new_filter return new_filter def _ListOf( config_entry ): if isinstance( config_entry, list ): return config_entry return [ config_entry ] def CompileRegex( raw_regex ): pattern = re.compile( raw_regex, re.IGNORECASE ) def FilterRegex( diagnostic ): return pattern.search( diagnostic[ 'text' ] ) is not None return FilterRegex def CompileLevel( level ): # valid kinds are WARNING and ERROR; # expected input levels are `warning` and `error` # NOTE: we don't validate the input... expected_kind = level.upper() def FilterLevel( diagnostic ): return diagnostic[ 'kind' ] == expected_kind return FilterLevel FILTER_COMPILERS = { 'regex' : CompileRegex, 'level' : CompileLevel } def _CompileFilters( config ): """Given a filter config dictionary, return a list of compiled filters""" filters = [] for filter_type, filter_pattern in config.items(): compiler = FILTER_COMPILERS.get( filter_type ) if compiler is not None: for filter_config in _ListOf( filter_pattern ): compiledFilter = compiler( filter_config ) filters.append( compiledFilter ) return filters ================================================ FILE: python/ycm/diagnostic_interface.py ================================================ # Copyright (C) 2013-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from collections import defaultdict from ycm import vimsupport from ycm.diagnostic_filter import DiagnosticFilter, CompileLevel from ycm import text_properties as tp import vim YCM_VIM_PROPERTY_ID = 1 class DiagnosticInterface: def __init__( self, bufnr, user_options ): self._bufnr = bufnr self._user_options = user_options self._diagnostics = [] self._diag_filter = DiagnosticFilter.CreateFromOptions( user_options ) # Line and column numbers are 1-based self._line_to_diags = defaultdict( list ) self._previous_diag_line_number = -1 self._diag_message_needs_clearing = False def ShouldUpdateDiagnosticsUINow( self ): return ( self._user_options[ 'update_diagnostics_in_insert_mode' ] or 'i' not in vim.eval( 'mode()' ) ) def OnCursorMoved( self ): if self._user_options[ 'echo_current_diagnostic' ]: line, _ = vimsupport.CurrentLineAndColumn() line += 1 # Convert to 1-based if not self.ShouldUpdateDiagnosticsUINow(): # Clear any previously echo'd diagnostic in insert mode self._EchoDiagnosticText( line, None, None ) elif line != self._previous_diag_line_number: self._EchoDiagnosticForLine( line ) def GetErrorCount( self ): return self._DiagnosticsCount( _DiagnosticIsError ) def GetWarningCount( self ): return self._DiagnosticsCount( _DiagnosticIsWarning ) def PopulateLocationList( self, open_on_edit = False ): # Do nothing if loc list is already populated by diag_interface if not self._user_options[ 'always_populate_location_list' ]: self._UpdateLocationLists( open_on_edit ) return bool( self._diagnostics ) def UpdateWithNewDiagnostics( self, diags, open_on_edit = False ): self._diagnostics = [ _NormalizeDiagnostic( x ) for x in self._ApplyDiagnosticFilter( diags ) ] self._ConvertDiagListToDict() if self.ShouldUpdateDiagnosticsUINow(): self.RefreshDiagnosticsUI( open_on_edit ) def RefreshDiagnosticsUI( self, open_on_edit = False ): if self._user_options[ 'echo_current_diagnostic' ]: self._EchoDiagnostic() if self._user_options[ 'enable_diagnostic_signs' ]: self._UpdateSigns() self.UpdateMatches() if self._user_options[ 'always_populate_location_list' ]: self._UpdateLocationLists( open_on_edit ) def ClearDiagnosticsUI( self ): if self._user_options[ 'echo_current_diagnostic' ]: self._ClearCurrentDiagnostic() if self._user_options[ 'enable_diagnostic_signs' ]: self._ClearSigns() self._ClearMatches() def DiagnosticsForLine( self, line_number ): return self._line_to_diags[ line_number ] def _ApplyDiagnosticFilter( self, diags ): filetypes = vimsupport.GetBufferFiletypes( self._bufnr ) diag_filter = self._diag_filter.SubsetForTypes( filetypes ) return filter( diag_filter.IsAllowed, diags ) def _EchoDiagnostic( self ): line, _ = vimsupport.CurrentLineAndColumn() line += 1 # Convert to 1-based self._EchoDiagnosticForLine( line ) def _EchoDiagnosticForLine( self, line_num ): self._previous_diag_line_number = line_num diags = self._line_to_diags[ line_num ] text = None first_diag = None if diags: first_diag = diags[ 0 ] text = first_diag[ 'text' ] if first_diag.get( 'fixit_available', False ): text += ' (FixIt)' self._EchoDiagnosticText( line_num, first_diag, text ) def _ClearCurrentDiagnostic( self, will_be_replaced=False ): if not self._diag_message_needs_clearing: return if ( not vimsupport.VimIsNeovim() and self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ): tp.ClearTextProperties( self._bufnr, prop_types = [ 'YcmVirtDiagPadding', 'YcmVirtDiagError', 'YcmVirtDiagWarning' ] ) else: if not will_be_replaced: vimsupport.PostVimMessage( '', warning = False ) self._diag_message_needs_clearing = False def _EchoDiagnosticText( self, line_num, first_diag, text ): self._ClearCurrentDiagnostic( bool( text ) ) if ( not vimsupport.VimIsNeovim() and self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ): if not text: return def MakeVritualTextProperty( prop_type, text, position='after' ): vimsupport.AddTextProperty( self._bufnr, line_num, 0, prop_type, { 'text': text, 'text_align': position, 'text_wrap': 'wrap' } ) if vim.options[ 'ambiwidth' ] != 'double': marker = '⚠' else: marker = '>' MakeVritualTextProperty( 'YcmVirtDiagPadding', ' ' * vim.buffers[ self._bufnr ].options[ 'shiftwidth' ] ), MakeVritualTextProperty( 'YcmVirtDiagError' if _DiagnosticIsError( first_diag ) else 'YcmVirtDiagWarning', marker + ' ' + [ line for line in text.splitlines() if line ][ 0 ] ) else: if not text: # We already cleared it return vimsupport.PostVimMessage( text, warning = False, truncate = True ) self._diag_message_needs_clearing = True def _DiagnosticsCount( self, predicate ): count = 0 for diags in self._line_to_diags.values(): count += sum( 1 for d in diags if predicate( d ) ) return count def _UpdateLocationLists( self, open_on_edit = False ): vimsupport.SetLocationListsForBuffer( self._bufnr, vimsupport.ConvertDiagnosticsToQfList( self._diagnostics ), open_on_edit ) def _ClearMatches( self ): props_to_remove = vimsupport.GetTextProperties( self._bufnr ) for prop in props_to_remove: vimsupport.RemoveDiagnosticProperty( self._bufnr, prop ) def UpdateMatches( self ): if not self._user_options[ 'enable_diagnostic_highlighting' ]: return props_to_remove = vimsupport.GetTextProperties( self._bufnr ) for diags in self._line_to_diags.values(): # Insert squiggles in reverse order so that errors overlap warnings. for diag in reversed( diags ): for line, column, name, extras in _ConvertDiagnosticToTextProperties( self._bufnr, diag ): global YCM_VIM_PROPERTY_ID # Note the following .remove() works because the __eq__ on # DiagnosticProperty does not actually check the IDs match... diag_prop = vimsupport.DiagnosticProperty( YCM_VIM_PROPERTY_ID, name, line, column, extras[ 'end_col' ] - column if 'end_col' in extras else column ) try: props_to_remove.remove( diag_prop ) except ValueError: extras.update( { 'id': YCM_VIM_PROPERTY_ID } ) vimsupport.AddTextProperty( self._bufnr, line, column, name, extras ) YCM_VIM_PROPERTY_ID += 1 for prop in props_to_remove: vimsupport.RemoveDiagnosticProperty( self._bufnr, prop ) def _ClearSigns( self ): signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr ) vim.eval( f'sign_unplacelist( { signs_to_unplace } )' ) def _UpdateSigns( self ): signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr ) signs_to_place = [] for line, diags in self._line_to_diags.items(): if not diags: continue # We always go for the first diagnostic on the line because diagnostics # are sorted by errors in priority and Vim can only display one sign by # line. name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning' sign = { 'lnum': line, 'name': name, 'buffer': self._bufnr, 'group': 'ycm_signs' } try: signs_to_unplace.remove( sign ) except ValueError: signs_to_place.append( sign ) vim.eval( f'sign_placelist( { signs_to_place } )' ) vim.eval( f'sign_unplacelist( { signs_to_unplace } )' ) def _ConvertDiagListToDict( self ): self._line_to_diags = defaultdict( list ) for diag in self._diagnostics: location_extent = diag[ 'location_extent' ] start = location_extent[ 'start' ] end = location_extent[ 'end' ] bufnr = vimsupport.GetBufferNumberForFilename( start[ 'filepath' ] ) if bufnr == self._bufnr: for line_number in range( start[ 'line_num' ], end[ 'line_num' ] + 1 ): self._line_to_diags[ line_number ].append( diag ) for diags in self._line_to_diags.values(): # We also want errors to be listed before warnings so that errors aren't # hidden by the warnings; Vim won't place a sign over an existing one. diags.sort( key = lambda diag: ( diag[ 'kind' ], diag[ 'location' ][ 'column_num' ] ) ) _DiagnosticIsError = CompileLevel( 'error' ) _DiagnosticIsWarning = CompileLevel( 'warning' ) def _NormalizeDiagnostic( diag ): def ClampToOne( value ): return value if value > 0 else 1 location = diag[ 'location' ] location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] ) location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] ) return diag def _ConvertDiagnosticToTextProperties( bufnr, diagnostic ): properties = [] name = ( 'YcmErrorProperty' if _DiagnosticIsError( diagnostic ) else 'YcmWarningProperty' ) if vimsupport.VimIsNeovim(): name = name.replace( 'Property', 'Section' ) location_extent = diagnostic[ 'location_extent' ] if location_extent[ 'start' ][ 'line_num' ] <= 0: location = diagnostic[ 'location' ] line, column = vimsupport.LineAndColumnNumbersClamped( bufnr, location[ 'line_num' ], location[ 'column_num' ] ) properties.append( ( line, column, name, {} ) ) else: start_line, start_column = vimsupport.LineAndColumnNumbersClamped( bufnr, location_extent[ 'start' ][ 'line_num' ], location_extent[ 'start' ][ 'column_num' ] ) end_line, end_column = vimsupport.LineAndColumnNumbersClamped( bufnr, location_extent[ 'end' ][ 'line_num' ], location_extent[ 'end' ][ 'column_num' ] ) properties.append( ( start_line, start_column, name, { 'end_lnum': end_line, 'end_col': end_column } ) ) for diagnostic_range in diagnostic[ 'ranges' ]: if ( diagnostic_range[ 'start' ][ 'line_num' ] == 0 or diagnostic_range[ 'end' ][ 'line_num' ] == 0 ): continue start_line, start_column = vimsupport.LineAndColumnNumbersClamped( bufnr, diagnostic_range[ 'start' ][ 'line_num' ], diagnostic_range[ 'start' ][ 'column_num' ] ) end_line, end_column = vimsupport.LineAndColumnNumbersClamped( bufnr, diagnostic_range[ 'end' ][ 'line_num' ], diagnostic_range[ 'end' ][ 'column_num' ] ) if not _IsValidRange( start_line, start_column, end_line, end_column ): continue properties.append( ( start_line, start_column, name, { 'end_lnum': end_line, 'end_col': end_column } ) ) return properties def _IsValidRange( start_line, start_column, end_line, end_column ): # End line before start line - invalid if start_line > end_line: return False # End line after start line - valid if start_line < end_line: return True # Same line, start colum after end column - invalid if start_column > end_column: return False # Same line, start column before or equal to end column - valid return True ================================================ FILE: python/ycm/hierarchy_tree.py ================================================ # Copyright (C) 2024 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from typing import Optional, List from ycm import vimsupport import os class HierarchyNode: def __init__( self, data, distance : int ): self._references : Optional[ List[ int ] ] = None self._data = data self._distance_from_root = distance def ToRootLocation( self, subindex : int ): location = self._data.get( 'root_location' ) if location: file = location[ 'filepath' ] line = location[ 'line_num' ] column = location[ 'column_num' ] return file, line, column else: return self.ToLocation( subindex ) def ToLocation( self, subindex : int ): location = self._data[ 'locations' ][ subindex ] line = location[ 'line_num' ] column = location[ 'column_num' ] file = location[ 'filepath' ] return file, line, column MAX_HANDLES_PER_INDEX = 1000000 def handle_to_index( handle : int ): return abs( handle ) // MAX_HANDLES_PER_INDEX def handle_to_location_index( handle : int ): return abs( handle ) % MAX_HANDLES_PER_INDEX def make_handle( index : int, location_index : int ): return index * MAX_HANDLES_PER_INDEX + location_index class HierarchyTree: def __init__( self ): self._up_nodes : List[ HierarchyNode ] = [] self._down_nodes : List[ HierarchyNode ] = [] self._kind : str = '' def SetRootNode( self, items, kind : str ): if items: assert len( items ) == 1 self._root_node_indices = [ 0 ] self._down_nodes.append( HierarchyNode( items[ 0 ], 0 ) ) self._up_nodes.append( HierarchyNode( items[ 0 ], 0 ) ) self._kind = kind return self.HierarchyToLines() return [] def UpdateHierarchy( self, handle : int, items, direction : str ): current_index = handle_to_index( handle ) nodes = self._down_nodes if direction == 'down' else self._up_nodes if items: nodes.extend( [ HierarchyNode( item, nodes[ current_index ]._distance_from_root + 1 ) for item in items ] ) nodes[ current_index ]._references = list( range( len( nodes ) - len( items ), len( nodes ) ) ) else: nodes[ current_index ]._references = [] def Reset( self ): self._down_nodes = [] self._up_nodes = [] self._kind = '' def _HierarchyToLinesHelper( self, refs, use_down_nodes ): partial_result = [] nodes = self._down_nodes if use_down_nodes else self._up_nodes for index in refs: next_node = nodes[ index ] indent = 2 * next_node._distance_from_root if index == 0: can_expand = ( self._down_nodes[ 0 ]._references is None or self._up_nodes[ 0 ]._references is None ) else: can_expand = next_node._references is None symbol = '+' if can_expand else '-' name = next_node._data[ 'name' ] kind = next_node._data[ 'kind' ] if use_down_nodes: partial_result.extend( [ ( { 'indent': indent, 'icon': symbol, 'symbol': name, 'kind': kind, 'filepath': os.path.split( l[ 'filepath' ] )[ 1 ], 'line_num': str( l[ 'line_num' ] ), 'description': l.get( 'description', '' ).strip(), }, make_handle( index, location_index ) ) for location_index, l in enumerate( next_node._data[ 'locations' ] ) ] ) else: partial_result.extend( [ ( { 'indent': indent, 'icon': symbol, 'symbol': name, 'kind': kind, 'filepath': os.path.split( l[ 'filepath' ] )[ 1 ], 'line_num': str( l[ 'line_num' ] ), 'description': l.get( 'description', '' ).strip(), }, make_handle( index, location_index ) * -1 ) for location_index, l in enumerate( next_node._data[ 'locations' ] ) ] ) if next_node._references: partial_result.extend( self._HierarchyToLinesHelper( next_node._references, use_down_nodes ) ) return partial_result def HierarchyToLines( self ): down_lines = self._HierarchyToLinesHelper( [ 0 ], True ) up_lines = self._HierarchyToLinesHelper( [ 0 ], False ) up_lines.reverse() return up_lines + down_lines[ 1: ] def JumpToItem( self, handle : int, command ): node_index = handle_to_index( handle ) location_index = handle_to_location_index( handle ) if handle >= 0: node = self._down_nodes[ node_index ] else: node = self._up_nodes[ node_index ] file, line, column = node.ToLocation( location_index ) vimsupport.JumpToLocation( file, line, column, '', command ) def ShouldResolveItem( self, handle : int, direction : str ): node_index = handle_to_index( handle ) if ( ( handle >= 0 and direction == 'down' ) or ( handle <= 0 and direction == 'up' ) ): if direction == 'down': node = self._down_nodes[ node_index ] else: node = self._up_nodes[ node_index ] return node._references is None return True def ResolveArguments( self, handle : int, direction : str ): node_index = handle_to_index( handle ) if self._kind == 'call': direction = 'outgoing' if direction == 'up' else 'incoming' else: direction = 'supertypes' if direction == 'up' else 'subtypes' if handle >= 0: node = self._down_nodes[ node_index ] else: node = self._up_nodes[ node_index ] return [ f'Resolve{ self._kind.title() }HierarchyItem', node._data, direction ] def HandleToRootLocation( self, handle : int ): node_index = handle_to_index( handle ) if handle >= 0: node = self._down_nodes[ node_index ] else: node = self._up_nodes[ node_index ] location_index = handle_to_location_index( handle ) return node.ToRootLocation( location_index ) def UpdateChangesRoot( self, handle : int, direction : str ): return ( ( handle < 0 and direction == 'down' ) or ( handle > 0 and direction == 'up' ) ) ================================================ FILE: python/ycm/inlay_hints.py ================================================ # Copyright (C) 2022, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.inlay_hints_request import InlayHintsRequest from ycm.client.base_request import BuildRequestData from ycm import vimsupport from ycm import text_properties as tp from ycm import scrolling_range as sr HIGHLIGHT_GROUP = { 'Type': 'YcmInlayHint', 'Parameter': 'YcmInlayHint', 'Enum': 'YcmInlayHint', } REPORTED_MISSING_TYPES = set() def Initialise(): if vimsupport.VimIsNeovim(): return False props = tp.GetTextPropertyTypes() if 'YCM_INLAY_UNKNOWN' not in props: tp.AddTextPropertyType( 'YCM_INLAY_UNKNOWN', highlight = 'YcmInlayHint', start_incl = 1 ) if 'YCM_INLAY_PADDING' not in props: tp.AddTextPropertyType( 'YCM_INLAY_PADDING', highlight = 'YcmInvisible', start_incl = 1 ) for token_type, group in HIGHLIGHT_GROUP.items(): prop = f'YCM_INLAY_{ token_type }' if prop not in props and vimsupport.GetIntValue( f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ): tp.AddTextPropertyType( prop, highlight = group, start_incl = 1 ) return True class InlayHints( sr.ScrollingBufferRange ): """Stores the inlay hints state for a Vim buffer""" def _NewRequest( self, request_range ): request_data = BuildRequestData( self._bufnr ) request_data[ 'range' ] = request_range return InlayHintsRequest( request_data ) def Clear( self ): types = [ 'YCM_INLAY_UNKNOWN', 'YCM_INLAY_PADDING' ] + [ f'YCM_INLAY_{ prop_type }' for prop_type in HIGHLIGHT_GROUP.keys() ] tp.ClearTextProperties( self._bufnr, prop_types = types ) def _Draw( self ): self.Clear() for inlay_hint in self._latest_response: if 'kind' not in inlay_hint: prop_type = 'YCM_INLAY_UNKNOWN' elif inlay_hint[ 'kind' ] not in HIGHLIGHT_GROUP: prop_type = 'YCM_INLAY_UNKNOWN' else: prop_type = 'YCM_INLAY_' + inlay_hint[ 'kind' ] self.GrowRangeIfNeeded( { 'start': inlay_hint[ 'position' ], 'end': { 'line_num': inlay_hint[ 'position' ][ 'line_num' ], 'column_num': inlay_hint[ 'position' ][ 'column_num' ] + len( inlay_hint[ 'label' ] ) } } ) if inlay_hint.get( 'paddingLeft', False ): tp.AddTextProperty( self._bufnr, None, 'YCM_INLAY_PADDING', { 'start': inlay_hint[ 'position' ], }, { 'text': ' ' } ) tp.AddTextProperty( self._bufnr, None, prop_type, { 'start': inlay_hint[ 'position' ], }, { 'text': inlay_hint[ 'label' ] } ) if inlay_hint.get( 'paddingRight', False ): tp.AddTextProperty( self._bufnr, None, 'YCM_INLAY_PADDING', { 'start': inlay_hint[ 'position' ], }, { 'text': ' ' } ) ================================================ FILE: python/ycm/omni_completer.py ================================================ # Copyright (C) 2011-2019 ycmd contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import vim from ycm import vimsupport from ycmd import utils from ycmd.completers.completer import Completer from ycm.client.base_request import BaseRequest OMNIFUNC_RETURNED_BAD_VALUE = 'Omnifunc returned bad value to YCM!' OMNIFUNC_NOT_LIST = ( 'Omnifunc did not return a list or a dict with a "words" ' ' list when expected.' ) class OmniCompleter( Completer ): def __init__( self, user_options ): super( OmniCompleter, self ).__init__( user_options ) self._omnifunc = None def SupportedFiletypes( self ): return [] def ShouldUseCache( self ): return bool( self.user_options[ 'cache_omnifunc' ] ) def ShouldUseNow( self, request_data ): self._omnifunc = utils.ToUnicode( vim.eval( '&omnifunc' ) ) if not self._omnifunc: return False if self.ShouldUseCache(): return super( OmniCompleter, self ).ShouldUseNow( request_data ) return self.ShouldUseNowInner( request_data ) def ShouldUseNowInner( self, request_data ): if request_data[ 'force_semantic' ]: return True disabled_filetypes = self.user_options[ 'filetype_specific_completion_to_disable' ] if not vimsupport.CurrentFiletypesEnabled( disabled_filetypes ): return False return super( OmniCompleter, self ).ShouldUseNowInner( request_data ) def ComputeCandidates( self, request_data ): if self.ShouldUseCache(): return super( OmniCompleter, self ).ComputeCandidates( request_data ) if self.ShouldUseNowInner( request_data ): return self.ComputeCandidatesInner( request_data ) return [] def ComputeCandidatesInner( self, request_data ): if not self._omnifunc: return [] # Calling directly the omnifunc may move the cursor position. This is the # case with the default Vim omnifunc for C-family languages # (ccomplete#Complete) which calls searchdecl to find a declaration. This # function is supposed to move the cursor to the found declaration but it # doesn't when called through the omni completion mapping (CTRL-X CTRL-O). # So, we restore the cursor position after the omnifunc calls. line, column = vimsupport.CurrentLineAndColumn() try: start_column = vimsupport.GetIntValue( self._omnifunc + '(1,"")' ) # Vim only stops completion if the value returned by the omnifunc is -3 or # -2. In other cases, if the value is negative or greater than the current # column, the start column is set to the current column; otherwise, the # value is used as the start column. if start_column in ( -3, -2 ): return [] if start_column < 0 or start_column > column: start_column = column # Use the start column calculated by the omnifunc, rather than our own # interpretation. This is important for certain languages where our # identifier detection is either incorrect or not compatible with the # behaviour of the omnifunc. Note: do this before calling the omnifunc # because it affects the value returned by 'query'. request_data[ 'start_column' ] = start_column + 1 # Vim internally moves the cursor to the start column before calling again # the omnifunc. Some omnifuncs like the one defined by the # LanguageClient-neovim plugin depend on this behavior to compute the list # of candidates. vimsupport.SetCurrentLineAndColumn( line, start_column ) omnifunc_call = [ self._omnifunc, "(0,'", vimsupport.EscapeForVim( request_data[ 'query' ] ), "')" ] items = vim.eval( ''.join( omnifunc_call ) ) if isinstance( items, dict ) and 'words' in items: items = items[ 'words' ] if not hasattr( items, '__iter__' ): raise TypeError( OMNIFUNC_NOT_LIST ) # Vim allows each item of the list to be either a string or a dictionary # but ycmd only supports lists where items are all strings or all # dictionaries. Convert all strings into dictionaries. for index, item in enumerate( items ): # Set the 'equal' field to 1 to disable Vim filtering. if not isinstance( item, dict ): items[ index ] = { 'word': item, 'equal': 1 } else: item[ 'equal' ] = 1 return items except ( TypeError, ValueError, vim.error ) as error: vimsupport.PostVimMessage( OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) ) return [] finally: vimsupport.SetCurrentLineAndColumn( line, column ) def FilterAndSortCandidatesInner( self, candidates, sort_property, query ): request_data = { 'candidates': candidates, 'sort_property': sort_property, 'query': query } response = BaseRequest().PostDataToHandler( request_data, 'filter_and_sort_candidates' ) return response if response is not None else [] ================================================ FILE: python/ycm/paths.py ================================================ # Copyright (C) 2015-2017 YouCompleteMe contributors. # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import os import sys import vim import re # Can't import these from setup.py because it makes nosetests go crazy. DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) ) DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party', 'ycmd' ) WIN_PYTHON_PATH = os.path.join( sys.exec_prefix, 'python.exe' ) PYTHON_BINARY_REGEX = re.compile( r'python(3(\.[6-9])?)?(.exe)?$', re.IGNORECASE ) # Not caching the result of this function; users shouldn't have to restart Vim # after running the install script or setting the # `g:ycm_server_python_interpreter` option. def PathToPythonInterpreter(): # Not calling the Python interpreter to check its version as it significantly # impacts startup time. from ycmd import utils python_interpreter = vim.eval( 'g:ycm_server_python_interpreter' ) if python_interpreter: python_interpreter = utils.FindExecutable( python_interpreter ) if python_interpreter: return python_interpreter raise RuntimeError( "Path in 'g:ycm_server_python_interpreter' option " "does not point to a valid Python 3.6+." ) python_interpreter = _PathToPythonUsedDuringBuild() if python_interpreter and utils.GetExecutable( python_interpreter ): return python_interpreter # On UNIX platforms, we use sys.executable as the Python interpreter path. # We cannot use sys.executable on Windows because for unknown reasons, it # returns the Vim executable. Instead, we use sys.exec_prefix to deduce the # interpreter path. python_interpreter = ( WIN_PYTHON_PATH if utils.OnWindows() else sys.executable ) if _EndsWithPython( python_interpreter ): return python_interpreter python_interpreter = utils.PathToFirstExistingExecutable( [ 'python3', 'python' ] ) if python_interpreter: return python_interpreter raise RuntimeError( "Cannot find Python 3.6+. " "Set the 'g:ycm_server_python_interpreter' option " "to a Python interpreter path." ) def _PathToPythonUsedDuringBuild(): from ycmd import utils try: filepath = os.path.join( DIR_OF_YCMD, 'PYTHON_USED_DURING_BUILDING' ) return utils.ReadFile( filepath ).strip() except OSError: return None def _EndsWithPython( path ): """Check if given path ends with a python 3.6+ name.""" return path and PYTHON_BINARY_REGEX.search( path ) is not None def PathToServerScript(): return os.path.join( DIR_OF_YCMD, 'ycmd' ) ================================================ FILE: python/ycm/scrolling_range.py ================================================ # Copyright (C) 2023, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import abc from ycm import vimsupport class ScrollingBufferRange( object ): """Abstraction used by inlay hints and semantic tokens to only request visible ranges""" # FIXME: Send a request per-disjoint range for this buffer rather than the # maximal range. then collaate the results when all responses are returned def __init__( self, bufnr ): self._bufnr = bufnr self._tick = -1 self._request = None self._last_requested_range = None def Ready( self ): return self._request is not None and self._request.Done() def Request( self, force=False ): if self._request and not self.Ready(): return True # Check to see if the buffer ranges would actually change anything visible. # This avoids a round-trip for every single line scroll event if ( not force and self._tick == vimsupport.GetBufferChangedTick( self._bufnr ) and vimsupport.VisibleRangeOfBufferOverlaps( self._bufnr, self._last_requested_range ) ): return False # don't poll # FIXME: This call is duplicated in the call to VisibleRangeOfBufferOverlaps # - remove the expansion param # - look up the actual visible range, then call this function # - if not overlapping, do the factor expansion and request self._last_requested_range = vimsupport.RangeVisibleInBuffer( self._bufnr ) # If this is false, either the self._bufnr is not a valid buffer number or # the buffer is not visible in any window. # Since this is called asynchronously, a user may bwipeout a buffer with # self._bufnr number between polls. if self._last_requested_range is None: return False self._tick = vimsupport.GetBufferChangedTick( self._bufnr ) # We'll never use the last response again, so clear it self._latest_response = None self._request = self._NewRequest( self._last_requested_range ) self._request.Start() return True def Update( self ): if not self._request: # Nothing to update return True assert self.Ready() # We're ready to use this response. Clear the request (to avoid repeatedly # re-polling). self._latest_response = self._request.Response() self._request = None if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ): # Buffer has changed, we should ignore the data and retry self.Request( force=True ) return False # poll again self._Draw() # No need to re-poll return True def Refresh( self ): if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ): # stale data return if self._request is not None: # request in progress; we''l handle refreshing when it's done. return self._Draw() def GrowRangeIfNeeded( self, rng ): """When processing results, we may receive a wider range than requested. In that case, grow our 'last requested' range to minimise requesting more frequently than we need to.""" # Note: references (pointers) so no need to re-assign rmin = self._last_requested_range[ 'start' ] rmax = self._last_requested_range[ 'end' ] start = rng[ 'start' ] end = rng[ 'end' ] if rmin[ 'line_num' ] is None or start[ 'line_num' ] < rmin[ 'line_num' ]: rmin[ 'line_num' ] = start[ 'line_num' ] rmin[ 'column_num' ] = start[ 'column_num' ] elif start[ 'line_num' ] == rmin[ 'line_num' ]: rmin[ 'column_num' ] = min( start[ 'column_num' ], rmin[ 'column_num' ] ) if rmax[ 'line_num' ] is None or end[ 'line_num' ] > rmax[ 'line_num' ]: rmax[ 'line_num' ] = end[ 'line_num' ] rmax[ 'column_num' ] = end[ 'column_num' ] elif end[ 'line_num' ] == rmax[ 'line_num' ]: rmax[ 'column_num' ] = max( end[ 'column_num' ], rmax[ 'column_num' ] ) # API; just implement the following, using self._bufnr and # self._latest_response as required @abc.abstractmethod def _NewRequest( self, request_range ): # prepare a new request_data and return it pass @abc.abstractmethod def _Draw( self ): # actuall paint the properties pass ================================================ FILE: python/ycm/semantic_highlighting.py ================================================ # Copyright (C) 2020, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.client.semantic_tokens_request import SemanticTokensRequest from ycm.client.base_request import BuildRequestData from ycm import vimsupport from ycm import text_properties as tp from ycm import scrolling_range as sr import vim HIGHLIGHT_GROUP = { 'namespace': 'Type', 'type': 'Type', 'class': 'Structure', 'enum': 'Structure', 'interface': 'Structure', 'struct': 'Structure', 'typeParameter': 'Identifier', 'parameter': 'Identifier', 'variable': 'Identifier', 'property': 'Identifier', 'enumMember': 'Identifier', 'enumConstant': 'Constant', 'event': 'Identifier', 'function': 'Function', 'member': 'Identifier', 'macro': 'Macro', 'method': 'Function', 'keyword': 'Keyword', 'modifier': 'Keyword', 'comment': 'Comment', 'string': 'String', 'number': 'Number', 'regexp': 'String', 'operator': 'Operator', 'decorator': 'Special', 'unknown': 'Normal', # These are not part of the spec, but are used by clangd 'bracket': 'Normal', 'concept': 'Type', # These are not part of the spec, but are used by jdt.ls 'annotation': 'Macro', } REPORTED_MISSING_TYPES = set() def Initialise(): if vimsupport.VimIsNeovim(): return props = tp.GetTextPropertyTypes() if 'YCM_HL_UNKNOWN' not in props: tp.AddTextPropertyType( 'YCM_HL_UNKNOWN', highlight = 'WarningMsg', priority = 0 ) for token_type, group in HIGHLIGHT_GROUP.items(): prop = f'YCM_HL_{ token_type }' if prop not in props and vimsupport.GetIntValue( f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ): tp.AddTextPropertyType( prop, highlight = group, priority = 0 ) # "arbitrary" base id NEXT_TEXT_PROP_ID = 70784 def NextPropID(): global NEXT_TEXT_PROP_ID try: return NEXT_TEXT_PROP_ID finally: NEXT_TEXT_PROP_ID += 1 class SemanticHighlighting( sr.ScrollingBufferRange ): """Stores the semantic highlighting state for a Vim buffer""" def __init__( self, bufnr ): self._prop_id = NextPropID() super().__init__( bufnr ) def _NewRequest( self, request_range ): request: dict = BuildRequestData( self._bufnr ) request[ 'range' ] = request_range return SemanticTokensRequest( request ) def _Draw( self ): # We requested a snapshot tokens = self._latest_response.get( 'tokens', [] ) prev_prop_id = self._prop_id self._prop_id = NextPropID() for token in tokens: prop_type = f"YCM_HL_{ token[ 'type' ] }" rng = token[ 'range' ] self.GrowRangeIfNeeded( rng ) try: tp.AddTextProperty( self._bufnr, self._prop_id, prop_type, rng ) except vim.error as e: if 'E971:' in str( e ): # Text property doesn't exist if token[ 'type' ] not in REPORTED_MISSING_TYPES: REPORTED_MISSING_TYPES.add( token[ 'type' ] ) vimsupport.PostVimMessage( f"Token type { token[ 'type' ] } not supported. " f"Define property type { prop_type }. " f"See :help youcompleteme-customising-highlight-groups" ) else: raise e tp.ClearTextProperties( self._bufnr, prop_id = prev_prop_id ) ================================================ FILE: python/ycm/signature_help.py ================================================ # Copyright (C) 2011-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import vim import json from ycm import vimsupport from ycmd import utils from ycm.vimsupport import memoize, GetIntValue class SignatureHelpState: ACTIVE = 'ACTIVE' INACTIVE = 'INACTIVE' ACTIVE_SUPPRESSED = 'ACTIVE_SUPPRESSED' def __init__( self, popup_win_id = None, state = INACTIVE ): self.popup_win_id = popup_win_id self.state = state self.anchor = None def ToggleVisibility( self ): if self.state == 'ACTIVE': self.state = 'ACTIVE_SUPPRESSED' vim.eval( f'popup_hide( { self.popup_win_id } )' ) elif self.state == 'ACTIVE_SUPPRESSED': self.state = 'ACTIVE' vim.eval( f'popup_show( { self.popup_win_id } )' ) def IsActive( self ): if self.state in ( 'ACTIVE', 'ACTIVE_SUPPRESSED' ): return 'ACTIVE' return 'INACTIVE' def _MakeSignatureHelpBuffer( signature_info ): active_parameter = int( signature_info.get( 'activeParameter', 0 ) ) lines = [] signatures = ( signature_info.get( 'signatures' ) or [] ) for sig_index, signature in enumerate( signatures ): props = [] sig_label = signature[ 'label' ] parameters = ( signature.get( 'parameters' ) or [] ) for param_index, parameter in enumerate( parameters ): param_label = parameter[ 'label' ] begin = int( param_label[ 0 ] ) end = int( param_label[ 1 ] ) if param_index == active_parameter: props.append( { 'col': begin + 1, # 1-based 'length': end - begin, 'type': 'YCM-signature-help-current-argument' } ) lines.append( { 'text': sig_label, 'props': props } ) return lines @memoize() def ShouldUseSignatureHelp(): return ( vimsupport.VimHasFunctions( 'screenpos', 'pum_getpos' ) and vimsupport.VimSupportsPopupWindows() ) def UpdateSignatureHelp( state, signature_info ): # noqa if not ShouldUseSignatureHelp(): return state signatures = signature_info.get( 'signatures' ) or [] if not signatures: if state.popup_win_id: # TODO/FIXME: Should we use popup_hide() instead ? vim.eval( f"popup_close( { state.popup_win_id } )" ) return SignatureHelpState( None, SignatureHelpState.INACTIVE ) if state.state == SignatureHelpState.INACTIVE: state.anchor = vimsupport.CurrentLineAndColumn() state.state = SignatureHelpState.ACTIVE # Generate the buffer as a list of lines buf_lines = _MakeSignatureHelpBuffer( signature_info ) screen_pos = vimsupport.ScreenPositionForLineColumnInWindow( vim.current.window, state.anchor[ 0 ] + 1, # anchor 0-based state.anchor[ 1 ] + 1 ) # anchor 0-based # Simulate 'flip' at the screen boundaries by using screenpos and hiding the # signature help menu if it overlaps the completion popup (pum). # # FIXME: revert to cursor-relative positioning and the 'flip' option when that # is implemented (if that is indeed better). # By default display above the anchor line = int( screen_pos[ 'row' ] ) - 1 # -1 to display above the cur line pos = "botleft" cursor_line = vimsupport.CurrentLineAndColumn()[ 0 ] + 1 if int( screen_pos[ 'row' ] ) <= len( buf_lines ): # No room at the top, display below line = int( screen_pos[ 'row' ] ) + 1 pos = "topleft" # Don't allow the popup to overlap the cursor if ( pos == 'topleft' and line < cursor_line and line + len( buf_lines ) >= cursor_line ): line = 0 # Don't allow the popup to overlap the pum if line > 0 and GetIntValue( 'pumvisible()' ): pum_line = GetIntValue( 'pum_getpos().row' ) + 1 if pos == 'botleft' and pum_line <= line: line = 0 elif ( pos == 'topleft' and pum_line >= line and pum_line < ( line + len( buf_lines ) ) ): line = 0 if line <= 0: # Nowhere to put it so hide it if state.popup_win_id: # TODO/FIXME: Should we use popup_hide() instead ? vim.eval( f"popup_close( { state.popup_win_id } )" ) return SignatureHelpState( None, SignatureHelpState.INACTIVE ) if int( screen_pos[ 'curscol' ] ) <= 1: col = 1 else: # -1 for padding, # -1 for the trigger character inserted (the anchor is set _after_ the # character is inserted, so we remove it). # FIXME: multi-byte characters would be wrong. Need to set anchor before # inserting the char ? col = int( screen_pos[ 'curscol' ] ) - 2 # Vim stops shifting the popup to the left if we turn on soft-wrapping. # Instead, we want to first shift the popup to the left and then # and then turn on wrapping. max_line_length = max( len( item[ 'text' ] ) for item in buf_lines ) vim_width = vimsupport.GetIntValue( '&columns' ) line_available = vim_width - max( col, 1 ) if max_line_length > line_available: col = vim_width - max_line_length if col <= 0: col = 1 options = { "line": line, "col": col, "pos": pos, "wrap": 0, # NOTE: We *dont'* use "cursorline" here - that actually uses PMenuSel, # which is just too invasive for us (it's more selected item than actual # cursorline. So instead, we manually set 'cursorline' in the popup window # and enable syntax based on the current file syntax) "flip": 1, "fixed": 1, "padding": [ 0, 1, 0, 1 ], # Pad 1 char in X axis to match completion menu "hidden": int( state.state == SignatureHelpState.ACTIVE_SUPPRESSED ) } if not state.popup_win_id: state.popup_win_id = GetIntValue( f'popup_create( { json.dumps( buf_lines ) }, ' f'{ json.dumps( options ) } )' ) else: vim.eval( f'popup_settext( { state.popup_win_id }, ' f'{ json.dumps( buf_lines ) } )' ) # Should do nothing if already visible vim.eval( f'popup_move( { state.popup_win_id }, { json.dumps( options ) } )' ) if state.state == SignatureHelpState.ACTIVE: vim.eval( f'popup_show( { state.popup_win_id } )' ) if vim.vars.get( 'ycm_signature_help_disable_syntax', False ): syntax = '' else: syntax = utils.ToUnicode( vim.current.buffer.options[ 'syntax' ] ) active_signature = int( signature_info.get( 'activeSignature', 0 ) ) vim.eval( f"win_execute( { state.popup_win_id }, " f"'set syntax={ syntax } cursorline wrap | " f"call cursor( [ { active_signature + 1 }, 1 ] )' )" ) return state ================================================ FILE: python/ycm/syntax_parse.py ================================================ # 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 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_REGION_ARGUMENT_REGEX = re.compile( r"^(?:matchgroup|start)=.*$" ) # See ":h syn-nextgroup". SYNTAX_NEXTGROUP_ARGUMENTS = { 'skipwhite', 'skipnl', 'skipempty' } # These are the parent groups from which we want to extract keywords. ROOT_GROUPS = { 'Boolean', 'Identifier', 'Statement', 'PreProc', 'Type' } class SyntaxGroup: def __init__( self, name, lines = None ): self.name = name self.lines = lines if lines else [] self.children = [] def SyntaxKeywordsForCurrentBuffer(): syntax_output = vimsupport.CaptureVimCommand( 'syntax list' ) 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 ) identifier_group = SyntaxGroup( 'Identifier' ) statement_group = SyntaxGroup( 'Statement' ) type_group = SyntaxGroup( 'Type' ) preproc_group = SyntaxGroup( 'PreProc' ) # See ":h group-name" for details on how the initial group hierarchy is built. group_name_to_group = { 'Boolean': SyntaxGroup( 'Boolean' ), 'Identifier': identifier_group, 'Statement': statement_group, 'PreProc': preproc_group, 'Type': type_group } AddToGroupMap( 'Function', identifier_group ) AddToGroupMap( 'Conditional', statement_group ) AddToGroupMap( 'Repeat' , statement_group ) AddToGroupMap( 'Label' , statement_group ) AddToGroupMap( 'Operator' , statement_group ) AddToGroupMap( 'Keyword' , statement_group ) AddToGroupMap( 'Exception' , statement_group ) AddToGroupMap( 'StorageClass', type_group ) AddToGroupMap( 'Structure' , type_group ) AddToGroupMap( 'Typedef' , type_group ) AddToGroupMap( 'Include' , preproc_group ) AddToGroupMap( 'Define' , preproc_group ) AddToGroupMap( 'Macro' , preproc_group ) AddToGroupMap( 'PreCondit', preproc_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.values(): 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 _ExtractKeywordsFromLine( line ): if line.startswith( 'links to ' ): return [] # Ignore "syntax match" lines (see ":h syn-match"). if line.startswith( 'match ' ): return [] words = line.split() if not words: return [] # Ignore "syntax region" lines (see ":h syn-region"). They always start # with matchgroup= or start= in the syntax list. if SYNTAX_REGION_ARGUMENT_REGEX.match( words[ 0 ] ): return [] # Ignore "nextgroup=" argument in first position and the arguments # "skipwhite", "skipnl", and "skipempty" that immediately come after. nextgroup_at_start = False if words[ 0 ].startswith( 'nextgroup=' ): nextgroup_at_start = True words = words[ 1: ] # Ignore "contained" argument in first position. if words[ 0 ] == 'contained': words = words[ 1: ] keywords = [] for word in words: if nextgroup_at_start and word in SYNTAX_NEXTGROUP_ARGUMENTS: continue nextgroup_at_start = False keyword_matched = KEYWORD_REGEX.match( word ) if keyword_matched: keywords.append( keyword_matched.group( 1 ) ) return keywords def _ExtractKeywordsFromGroup( group ): keywords = [] for line in group.lines: keywords.extend( _ExtractKeywordsFromLine( line ) ) return keywords ================================================ FILE: python/ycm/tests/__init__.py ================================================ # Copyright (C) 2016-2020 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import os from ycm.tests.test_utils import MockVimModule MockVimModule() import contextlib import functools import time from urllib.error import HTTPError, URLError from ycm.client.base_request import BaseRequest from ycm.tests import test_utils from ycm.youcompleteme import YouCompleteMe from ycmd.utils import CloseStandardStreams, WaitUntilProcessIsTerminated def PathToTestFile( *args ): dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) ) return os.path.join( dir_of_current_script, 'testdata', *args ) # The default options which are required for a working YouCompleteMe object. DEFAULT_CLIENT_OPTIONS = { # YCM options 'g:ycm_log_level': 'info', 'g:ycm_keep_logfiles': 0, 'g:ycm_extra_conf_vim_data': [], 'g:ycm_server_python_interpreter': '', 'g:ycm_show_diagnostics_ui': 1, 'g:ycm_enable_diagnostic_signs': 1, 'g:ycm_enable_diagnostic_highlighting': 0, 'g:ycm_echo_current_diagnostic': 1, 'g:ycm_filter_diagnostics': {}, 'g:ycm_always_populate_location_list': 0, 'g:ycm_open_loclist_on_ycm_diags': 1, 'g:ycm_collect_identifiers_from_tags_files': 0, 'g:ycm_seed_identifiers_with_syntax': 0, 'g:ycm_goto_buffer_command': 'same-buffer', 'g:ycm_update_diagnostics_in_insert_mode': 1, # ycmd options 'g:ycm_auto_trigger': 1, 'g:ycm_min_num_of_chars_for_completion': 2, 'g:ycm_semantic_triggers': {}, 'g:ycm_filetype_specific_completion_to_disable': { 'gitcommit': 1 }, 'g:ycm_max_num_candidates': 50, 'g:ycm_max_diagnostics_to_display': 30, 'g:ycm_disable_signature_help': 0, } @contextlib.contextmanager def UserOptions( options ): old_vim_options = test_utils.VIM_OPTIONS.copy() test_utils.VIM_OPTIONS.update( DEFAULT_CLIENT_OPTIONS ) test_utils.VIM_OPTIONS.update( options ) try: yield finally: test_utils.VIM_OPTIONS = old_vim_options def _IsReady(): return BaseRequest().GetDataFromHandler( 'ready' ) def WaitUntilReady( timeout = 5 ): expiration = time.time() + timeout while True: try: if time.time() > expiration: raise RuntimeError( 'Waited for the server to be ready ' f'for { timeout } seconds, aborting.' ) if _IsReady(): return except ( URLError, HTTPError ): pass finally: time.sleep( 0.1 ) def StopServer( ycm ): try: ycm.OnVimLeave() WaitUntilProcessIsTerminated( ycm._server_popen ) CloseStandardStreams( ycm._server_popen ) except Exception: pass def YouCompleteMeInstance( custom_options = {} ): """Defines a decorator function for tests that passes a unique YouCompleteMe instance as a parameter. This instance is initialized with the default options `DEFAULT_CLIENT_OPTIONS`. Use the optional parameter |custom_options| to give additional options and/or override the already existing ones. Example usage: from ycm.tests import YouCompleteMeInstance @YouCompleteMeInstance( { 'log_level': 'debug', 'keep_logfiles': 1 } ) def Debug_test( ycm ): ... """ def Decorator( test ): @functools.wraps( test ) def Wrapper( test_case_instance, *args, **kwargs ): with UserOptions( custom_options ): ycm = YouCompleteMe() WaitUntilReady() ycm.CheckIfServerIsReady() try: test_utils.VIM_PROPS_FOR_BUFFER.clear() return test( test_case_instance, ycm, *args, **kwargs ) finally: StopServer( ycm ) return Wrapper return Decorator @contextlib.contextmanager def youcompleteme_instance( custom_options = {} ): """Defines a context manager to be used in case a shared YCM state between subtests is to be avoided, as could be the case with completion caching.""" with UserOptions( custom_options ): ycm = YouCompleteMe() WaitUntilReady() try: test_utils.VIM_PROPS_FOR_BUFFER.clear() yield ycm finally: StopServer( ycm ) ================================================ FILE: python/ycm/tests/base_test.py ================================================ # Copyright (C) 2013 Google Inc. # 2020 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import contextlib from hamcrest import assert_that, equal_to from unittest import TestCase from unittest.mock import patch from ycm.tests.test_utils import MockVimModule vim_mock = MockVimModule() from ycm import base @contextlib.contextmanager def MockCurrentFiletypes( filetypes = [ '' ] ): with patch( 'ycm.vimsupport.CurrentFiletypes', return_value = filetypes ): yield @contextlib.contextmanager def MockCurrentColumnAndLineContents( column, line_contents ): with patch( 'ycm.vimsupport.CurrentColumn', return_value = column ): with patch( 'ycm.vimsupport.CurrentLineContents', return_value = line_contents ): yield @contextlib.contextmanager def MockTextAfterCursor( text ): with patch( 'ycm.vimsupport.TextAfterCursor', return_value = text ): yield class BaseTest( TestCase ): def test_AdjustCandidateInsertionText_Basic( self ): with MockTextAfterCursor( 'bar' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_ParenInTextAfterCursor( self ): with MockTextAfterCursor( 'bar(zoo' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_PlusInTextAfterCursor( self ): with MockTextAfterCursor( 'bar+zoo' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_WhitespaceInTextAfterCursor( self ): with MockTextAfterCursor( 'bar zoo' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_MoreThanWordMatchingAfterCursor( self ): with MockTextAfterCursor( 'bar.h' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar.h' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar.h', 'abbr': '' } ] ) ) ) with MockTextAfterCursor( 'bar(zoo' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar(zoo' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar(zoo', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_NotSuffix( self ): with MockTextAfterCursor( 'bar' ): assert_that( [ { 'word': 'foofoo', 'abbr': 'foofoo' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foofoo', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_NothingAfterCursor( self ): with MockTextAfterCursor( '' ): assert_that( [ { 'word': 'foofoo', 'abbr': '' }, { 'word': 'zobar', 'abbr': '' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foofoo', 'abbr': '' }, { 'word': 'zobar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_MultipleStrings( self ): with MockTextAfterCursor( 'bar' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' }, { 'word': 'zo', 'abbr': 'zobar' }, { 'word': 'q', 'abbr': 'qbar' }, { 'word': '', 'abbr': 'bar' }, ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '' }, { 'word': 'zobar', 'abbr': '' }, { 'word': 'qbar', 'abbr': '' }, { 'word': 'bar', 'abbr': '' } ] ) ) ) def test_AdjustCandidateInsertionText_DontTouchAbbr( self ): with MockTextAfterCursor( 'bar' ): assert_that( [ { 'word': 'foo', 'abbr': '1234' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar', 'abbr': '1234' } ] ) ) ) def test_AdjustCandidateInsertionText_NoAbbr( self ): with MockTextAfterCursor( 'bar' ): assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ], equal_to( base.AdjustCandidateInsertionText( [ { 'word': 'foobar' } ] ) ) ) def test_OverlapLength_Basic( self ): assert_that( 3, equal_to( base.OverlapLength( 'foo bar', 'bar zoo' ) ) ) assert_that( 3, equal_to( base.OverlapLength( 'foobar', 'barzoo' ) ) ) def test_OverlapLength_BasicWithUnicode( self ): assert_that( 3, equal_to( base.OverlapLength( 'bar fäö', 'fäö bar' ) ) ) assert_that( 3, equal_to( base.OverlapLength( 'zoofäö', 'fäözoo' ) ) ) def test_OverlapLength_OneCharOverlap( self ): assert_that( 1, equal_to( base.OverlapLength( 'foo b', 'b zoo' ) ) ) def test_OverlapLength_SameStrings( self ): assert_that( 6, equal_to( base.OverlapLength( 'foobar', 'foobar' ) ) ) def test_OverlapLength_Substring( self ): assert_that( 6, equal_to( base.OverlapLength( 'foobar', 'foobarzoo' ) ) ) assert_that( 6, equal_to( base.OverlapLength( 'zoofoobar', 'foobar' ) ) ) def test_OverlapLength_LongestOverlap( self ): assert_that( 7, equal_to( base.OverlapLength( 'bar foo foo', 'foo foo bar' ) ) ) def test_OverlapLength_EmptyInput( self ): assert_that( 0, equal_to( base.OverlapLength( '', 'goobar' ) ) ) assert_that( 0, equal_to( base.OverlapLength( 'foobar', '' ) ) ) assert_that( 0, equal_to( base.OverlapLength( '', '' ) ) ) def test_OverlapLength_NoOverlap( self ): assert_that( 0, equal_to( base.OverlapLength( 'foobar', 'goobar' ) ) ) assert_that( 0, equal_to( base.OverlapLength( 'foobar', '(^($@#$#@' ) ) ) assert_that( 0, equal_to( base.OverlapLength( 'foo bar zoo', 'foo zoo bar' ) ) ) def test_LastEnteredCharIsIdentifierChar_Basic( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 3, 'abc' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 2, 'abc' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 1, 'abc' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) def test_LastEnteredCharIsIdentifierChar_FiletypeHtml( self ): with MockCurrentFiletypes( [ 'html' ] ): with MockCurrentColumnAndLineContents( 3, 'ab-' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) def test_LastEnteredCharIsIdentifierChar_ColumnIsZero( self ): with MockCurrentColumnAndLineContents( 0, 'abc' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) def test_LastEnteredCharIsIdentifierChar_LineEmpty( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 3, '' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 0, '' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) def test_LastEnteredCharIsIdentifierChar_NotIdentChar( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 3, 'ab;' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 1, ';' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 3, 'ab-' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) def test_LastEnteredCharIsIdentifierChar_Unicode( self ): with MockCurrentFiletypes(): # CurrentColumn returns a byte offset and character ø is 2 bytes length. with MockCurrentColumnAndLineContents( 5, 'føo(' ): assert_that( not base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 4, 'føo(' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 3, 'føo(' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) with MockCurrentColumnAndLineContents( 1, 'føo(' ): assert_that( base.LastEnteredCharIsIdentifierChar() ) def test_CurrentIdentifierFinished_Basic( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 3, 'ab;' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 2, 'ab;' ): assert_that( not base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 1, 'ab;' ): assert_that( not base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_NothingBeforeColumn( self ): with MockCurrentColumnAndLineContents( 0, 'ab;' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 0, '' ): assert_that( base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_InvalidColumn( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 5, '' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 5, 'abc' ): assert_that( not base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 4, 'ab;' ): assert_that( base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_InMiddleOfLine( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 4, 'bar.zoo' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 4, 'bar(zoo' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ): assert_that( base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_Html( self ): with MockCurrentFiletypes( [ 'html' ] ): with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ): assert_that( not base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_WhitespaceOnly( self ): with MockCurrentFiletypes(): with MockCurrentColumnAndLineContents( 1, '\n' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 3, '\n ' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 3, '\t\t\t\t' ): assert_that( base.CurrentIdentifierFinished() ) def test_CurrentIdentifierFinished_Unicode( self ): with MockCurrentFiletypes(): # CurrentColumn returns a byte offset and character ø is 2 bytes length. with MockCurrentColumnAndLineContents( 6, 'føo ' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 5, 'føo ' ): assert_that( base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 4, 'føo ' ): assert_that( not base.CurrentIdentifierFinished() ) with MockCurrentColumnAndLineContents( 3, 'føo ' ): assert_that( not base.CurrentIdentifierFinished() ) ================================================ FILE: python/ycm/tests/client/__init__.py ================================================ ================================================ FILE: python/ycm/tests/client/base_request_test.py ================================================ # Copyright (C) 2017-2018 YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimBuffers, MockVimModule, VimBuffer MockVimModule() from hamcrest import assert_that, has_entry from unittest import TestCase from unittest.mock import patch from ycm.client.base_request import BuildRequestData class BaseRequestTest( TestCase ): @patch( 'ycm.client.base_request.GetCurrentDirectory', return_value = '/some/dir' ) def test_BuildRequestData_AddWorkingDir( self, *args ): current_buffer = VimBuffer( 'foo' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): assert_that( BuildRequestData(), has_entry( 'working_dir', '/some/dir' ) ) @patch( 'ycm.client.base_request.GetCurrentDirectory', return_value = '/some/dir' ) def test_BuildRequestData_AddWorkingDirWithFileName( self, *args ): current_buffer = VimBuffer( 'foo' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): assert_that( BuildRequestData( current_buffer.number ), has_entry( 'working_dir', '/some/dir' ) ) ================================================ FILE: python/ycm/tests/client/command_request_test.py ================================================ # Copyright (C) 2016 YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import ExtendedMock, MockVimModule MockVimModule() import json from hamcrest import assert_that from unittest import TestCase from unittest.mock import patch, call from ycm.client.command_request import CommandRequest def GoToTest( command, response ): with patch( 'ycm.vimsupport.JumpToLocation' ) as jump_to_location: request = CommandRequest( [ command ] ) request._response = response request.RunPostCommandActionsIfNeeded( 'rightbelow' ) jump_to_location.assert_called_with( response[ 'filepath' ], response[ 'line_num' ], response[ 'column_num' ], 'rightbelow', 'same-buffer' ) def GoToListTest( command, response ): # Note: the detail of these called are tested by # GoToResponse_QuickFix_test, so here we just check that the right call is # made with patch( 'ycm.vimsupport.SetQuickFixList' ) as set_qf_list: with patch( 'ycm.vimsupport.OpenQuickFixList' ) as open_qf_list: request = CommandRequest( [ command ] ) request._response = response request.RunPostCommandActionsIfNeeded( 'tab' ) assert_that( set_qf_list.called ) assert_that( open_qf_list.called ) BASIC_GOTO = { 'filepath': 'test', 'line_num': 10, 'column_num': 100, } BASIC_FIXIT = { 'fixits': [ { 'resolve': False, 'chunks': [ { 'dummy chunk contents': True } ] } ] } BASIC_FIXIT_CHUNKS = BASIC_FIXIT[ 'fixits' ][ 0 ][ 'chunks' ] MULTI_FIXIT = { 'fixits': [ { 'text': 'first', 'resolve': False, 'chunks': [ { 'dummy chunk contents': True } ] }, { 'text': 'second', 'resolve': False, 'chunks': [ { 'dummy chunk contents': False } ] } ] } MULTI_FIXIT_FIRST_CHUNKS = MULTI_FIXIT[ 'fixits' ][ 0 ][ 'chunks' ] MULTI_FIXIT_SECOND_CHUNKS = MULTI_FIXIT[ 'fixits' ][ 1 ][ 'chunks' ] class GoToResponse_QuickFixTest( TestCase ): """This class tests the generation of QuickFix lists for GoTo responses which return multiple locations, such as the Python completer and JavaScript completer. It mostly proves that we use 1-based indexing for the column number.""" def setUp( self ): self._request = CommandRequest( [ 'GoToTest' ] ) def tearDown( self ): self._request = None def test_GoTo_EmptyList( self ): self._CheckGoToList( [], [] ) def test_GoTo_SingleItem_List( self ): self._CheckGoToList( [ { 'filepath': 'dummy_file', 'line_num': 10, 'column_num': 1, 'description': 'this is some text', } ], [ { 'filename': 'dummy_file', 'text': 'this is some text', 'lnum': 10, 'col': 1 } ] ) def test_GoTo_MultiItem_List( self ): self._CheckGoToList( [ { 'filepath': 'dummy_file', 'line_num': 10, 'column_num': 1, 'description': 'this is some other text', }, { 'filepath': 'dummy_file2', 'line_num': 1, 'column_num': 21, 'description': 'this is some text', } ], [ { 'filename': 'dummy_file', 'text': 'this is some other text', 'lnum': 10, 'col': 1 }, { 'filename': 'dummy_file2', 'text': 'this is some text', 'lnum': 1, 'col': 21 } ] ) @patch( 'ycm.vimsupport.VariableExists', return_value = True ) @patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' ) @patch( 'vim.command', new_callable = ExtendedMock ) @patch( 'vim.eval', new_callable = ExtendedMock ) def _CheckGoToList( self, completer_response, expected_qf_list, vim_eval, vim_command, set_fitting_height, variable_exists ): self._request._response = completer_response self._request.RunPostCommandActionsIfNeeded( 'aboveleft' ) vim_eval.assert_has_exact_calls( [ call( f'setqflist( { json.dumps( expected_qf_list ) } )' ) ] ) vim_command.assert_has_exact_calls( [ call( 'botright copen' ), call( 'augroup ycmquickfix' ), call( 'autocmd! * ' ), call( 'autocmd WinLeave ' 'if bufnr( "%" ) == expand( "" ) | q | endif ' '| autocmd! ycmquickfix' ), call( 'augroup END' ), call( 'doautocmd User YcmQuickFixOpened' ) ] ) set_fitting_height.assert_called_once_with() class Response_Detection_Test( TestCase ): def test_BasicResponse( self ): def _BasicResponseTest( command, response ): with patch( 'vim.command' ) as vim_command: request = CommandRequest( [ command ] ) request._response = response request.RunPostCommandActionsIfNeeded( 'belowright' ) vim_command.assert_called_with( f"echo '{ response }'" ) for command, response in [ [ 'AnythingYouLike', True ], [ 'GoToEvenWorks', 10 ], [ 'FixItWorks', 'String!' ], [ 'and8434fd andy garbag!', 10.3 ], ]: with self.subTest( command = command, response = response ): _BasicResponseTest( command, response ) def test_FixIt_Response_Empty( self ): # Ensures we recognise and handle fixit responses which indicate that there # are no fixits available def EmptyFixItTest( command ): with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks: with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message: request = CommandRequest( [ command ] ) request._response = { 'fixits': [] } request.RunPostCommandActionsIfNeeded( 'botright' ) post_vim_message.assert_called_with( 'No fixits found for current line', warning = False ) replace_chunks.assert_not_called() for command in [ 'FixIt', 'Refactor', 'GoToHell', 'any_old_garbade!!!21' ]: with self.subTest( command = command ): EmptyFixItTest( command ) def test_FixIt_Response( self ): # Ensures we recognise and handle fixit responses with some dummy chunk data def FixItTest( command, response, chunks, selection, silent ): with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks: with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message: with patch( 'ycm.vimsupport.SelectFromList', return_value = selection ): request = CommandRequest( [ command ] ) request._response = response request.RunPostCommandActionsIfNeeded( 'leftabove' ) replace_chunks.assert_called_with( chunks, silent = silent ) post_vim_message.assert_not_called() for command, response, chunks, selection, silent in [ [ 'AnythingYouLike', BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ], [ 'GoToEvenWorks', BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ], [ 'FixItWorks', BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ], [ 'and8434fd andy garbag!', BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ], [ 'Format', BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, True ], [ 'select from multiple 1', MULTI_FIXIT, MULTI_FIXIT_FIRST_CHUNKS, 0, False ], [ 'select from multiple 2', MULTI_FIXIT, MULTI_FIXIT_SECOND_CHUNKS, 1, False ], ]: with self.subTest( command = command, response = response, chunks = chunks, selection = selection, silent = silent ): FixItTest( command, response, chunks, selection, silent ) def test_Message_Response( self ): # Ensures we correctly recognise and handle responses with a message to show # to the user def MessageTest( command, message ): with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message: request = CommandRequest( [ command ] ) request._response = { 'message': message } request.RunPostCommandActionsIfNeeded( 'rightbelow' ) post_vim_message.assert_called_with( message, warning = False ) for command, message in [ [ '___________', 'This is a message' ], [ '', 'this is also a message' ], [ 'GetType', 'std::string' ], ]: with self.subTest( command = command, message = message ): MessageTest( command, message ) def test_Detailed_Info( self ): # Ensures we correctly detect and handle detailed_info responses which are # used to display information in the preview window def DetailedInfoTest( command, info ): with patch( 'ycm.vimsupport.WriteToPreviewWindow' ) as write_to_preview: request = CommandRequest( [ command ] ) request._response = { 'detailed_info': info } request.RunPostCommandActionsIfNeeded( 'topleft' ) write_to_preview.assert_called_with( info, 'topleft' ) for command, info in [ [ '___________', 'This is a message' ], [ '', 'this is also a message' ], [ 'GetDoc', 'std::string\netc\netc' ], ]: with self.subTest( command = command, info = info ): DetailedInfoTest( command, info ) def test_GoTo_Single( self ): for test, command, response in [ [ GoToTest, 'AnythingYouLike', BASIC_GOTO ], [ GoToTest, 'GoTo', BASIC_GOTO ], [ GoToTest, 'FindAThing', BASIC_GOTO ], [ GoToTest, 'FixItGoto', BASIC_GOTO ], [ GoToListTest, 'AnythingYouLike', [ BASIC_GOTO ] ], [ GoToListTest, 'GoTo', [] ], [ GoToListTest, 'FixItGoto', [ BASIC_GOTO, BASIC_GOTO ] ], ]: with self.subTest( test = test, command = command, response = response ): test( command, response ) ================================================ FILE: python/ycm/tests/client/completion_request_test.py ================================================ # Copyright (C) 2015-2019 YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import json from hamcrest import assert_that, equal_to from unittest import TestCase from ycm.tests import UserOptions from ycm.tests.test_utils import MockVimModule vim_mock = MockVimModule() from ycm.client import completion_request class ConvertCompletionResponseToVimDatasTest( TestCase ): """ This class tests the completion_request.ConvertCompletionResponseToVimDatas method """ def _Check( self, completion_data, expected_vim_data ): vim_data = completion_request.ConvertCompletionDataToVimData( completion_data ) try: assert_that( vim_data, equal_to( expected_vim_data ) ) except Exception: print( "Expected:\n" f"'{ expected_vim_data }'\n" "when parsing:\n'" f"{ completion_data }'\n" "But found:\n" f"'{ vim_data }'" ) raise def test_AllFields( self ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': extra_data, }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILED INFO\nDOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_OnlyInsertionTextField( self ): self._Check( { 'insertion_text': 'INSERTION TEXT' }, { 'word' : 'INSERTION TEXT', 'abbr' : '', 'menu' : '', 'kind' : '', 'info' : '', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': '{}', } ) def test_JustDetailedInfo( self ): self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED INFO', }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILED INFO', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': '{}', } ) def test_JustDocString( self ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'extra_data': extra_data, }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_ExtraInfoNoDocString( self ): self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'extra_data': { }, }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : '', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': '{}', } ) def test_NullCharactersInExtraInfoAndDocString( self ): extra_data = { 'doc_string': 'DOC\x00STRING' } self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED\x00INFO', 'extra_data': extra_data, }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILEDINFO\nDOCSTRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_ExtraInfoNoDocStringWithDetailedInfo( self ): self._Check( { 'insertion_text': 'INSERTION TEXT', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': { }, }, { 'word' : 'INSERTION TEXT', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILED INFO', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': '{}', } ) def test_EmptyInsertionText( self ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': '', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': extra_data, }, { 'word' : '', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILED INFO\nDOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_TruncateForPopup( self, *args ): with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': '', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': extra_data, }, { 'word' : '', 'abbr' : 'MENU TEXT', 'menu' : 'ESPECIALLY LONG E...', 'kind' : 'k', 'info' : 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR\n\n' + 'DETAILED INFO\nDOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_OnlyTruncateForPopupIfNecessary( self, *args ): with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': '', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'EXTRA MENU INFO', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': extra_data, }, { 'word' : '', 'abbr' : 'MENU TEXT', 'menu' : 'EXTRA MENU INFO', 'kind' : 'k', 'info' : 'DETAILED INFO\nDOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_DontTruncateIfNotPopup( self, *args ): with UserOptions( { '&columns': 60, '&completeopt': b'preview,menuone' } ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': '', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR', 'kind': 'K', 'detailed_info': 'DETAILED INFO', 'extra_data': extra_data, }, { 'word' : '', 'abbr' : 'MENU TEXT', 'menu' : 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR', 'kind' : 'k', 'info' : 'DETAILED INFO\nDOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) def test_TruncateForPopupWithoutDuplication( self, *args ): with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ): extra_data = { 'doc_string': 'DOC STRING', } self._Check( { 'insertion_text': '', 'menu_text': 'MENU TEXT', 'extra_menu_info': 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM', 'kind': 'K', 'detailed_info': 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM', 'extra_data': extra_data, }, { 'word' : '', 'abbr' : 'MENU TEXT', 'menu' : 'ESPECIALLY LONG M...', 'kind' : 'k', 'info' : 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM\n' + 'DOC STRING', 'equal' : 1, 'dup' : 1, 'empty' : 1, 'user_data': json.dumps( extra_data ), } ) ================================================ FILE: python/ycm/tests/client/debug_info_request_test.py ================================================ # Copyright (C) 2017 YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from copy import deepcopy from hamcrest import assert_that, contains_string, equal_to from unittest import TestCase from ycm.client.debug_info_request import FormatDebugInfoResponse GENERIC_RESPONSE = { 'clang': { 'has_support': True, 'version': 'Clang version' }, 'completer': { 'items': [ { 'key': 'key', 'value': 'value' } ], 'name': 'Completer name', 'servers': [ { 'address': '127.0.0.1', 'executable': '/path/to/executable', 'extras': [ { 'key': 'key', 'value': 'value' } ], 'is_running': True, 'logfiles': [ '/path/to/stdout/logfile', '/path/to/stderr/logfile' ], 'name': 'Server name', 'pid': 12345, 'port': 1234 } ] }, 'extra_conf': { 'is_loaded': False, 'path': '/path/to/extra/conf' }, 'python': { 'executable': '/path/to/python/interpreter', 'version': 'Python version' } } class DebugInfoRequestTest( TestCase ): def test_FormatDebugInfoResponse_NoResponse( self ): assert_that( FormatDebugInfoResponse( None ), equal_to( 'Server errored, no debug info from server\n' ) ) def test_FormatDebugInfoResponse_NoExtraConf( self ): response = deepcopy( GENERIC_RESPONSE ) response[ 'extra_conf' ].update( { 'is_loaded': False, 'path': None } ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'No extra configuration file found\n' ) ) def test_FormatDebugInfoResponse_ExtraConfFoundButNotLoaded( self ): response = deepcopy( GENERIC_RESPONSE ) response[ 'extra_conf' ].update( { 'is_loaded': False, 'path': '/path/to/extra/conf' } ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'Extra configuration file found but not loaded\n' 'Extra configuration path: /path/to/extra/conf\n' ) ) def test_FormatDebugInfoResponse_ExtraConfFoundAndLoaded( self ): response = deepcopy( GENERIC_RESPONSE ) response[ 'extra_conf' ].update( { 'is_loaded': True, 'path': '/path/to/extra/conf' } ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'Extra configuration file found and loaded\n' 'Extra configuration path: /path/to/extra/conf\n' ) ) def test_FormatDebugInfoResponse_Completer_ServerRunningWithHost( self ): response = deepcopy( GENERIC_RESPONSE ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'Completer name completer debug information:\n' ' Server name running at: http://127.0.0.1:1234\n' ' Server name process ID: 12345\n' ' Server name executable: /path/to/executable\n' ' Server name logfiles:\n' ' /path/to/stdout/logfile\n' ' /path/to/stderr/logfile\n' ' Server name key: value\n' ' Key: value\n' ) ) def test_FormatDebugInfoResponse_Completer_ServerRunningWithoutHost( self ): response = deepcopy( GENERIC_RESPONSE ) response[ 'completer' ][ 'servers' ][ 0 ].update( { 'address': None, 'port': None } ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'Completer name completer debug information:\n' ' Server name running\n' ' Server name process ID: 12345\n' ' Server name executable: /path/to/executable\n' ' Server name logfiles:\n' ' /path/to/stdout/logfile\n' ' /path/to/stderr/logfile\n' ' Server name key: value\n' ' Key: value\n' ) ) def test_FormatDebugInfoResponse_Completer_ServerNotRunningWithNoLogfiles( self ): response = deepcopy( GENERIC_RESPONSE ) response[ 'completer' ][ 'servers' ][ 0 ].update( { 'is_running': False, 'logfiles': [] } ) assert_that( FormatDebugInfoResponse( response ), contains_string( 'Completer name completer debug information:\n' ' Server name not running\n' ' Server name executable: /path/to/executable\n' ' No logfiles available\n' ' Server name key: value\n' ' Key: value\n' ) ) ================================================ FILE: python/ycm/tests/client/messages_request_test.py ================================================ # Copyright (C) 2017 YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule MockVimModule() from hamcrest import assert_that, equal_to from unittest import TestCase from unittest.mock import patch, call from ycm.client.messages_request import _HandlePollResponse from ycm.tests.test_utils import ExtendedMock class MessagesRequestTest( TestCase ): def test_HandlePollResponse_NoMessages( self ): assert_that( _HandlePollResponse( True, None ), equal_to( True ) ) # Other non-False responses mean the same thing assert_that( _HandlePollResponse( '', None ), equal_to( True ) ) assert_that( _HandlePollResponse( 1, None ), equal_to( True ) ) assert_that( _HandlePollResponse( {}, None ), equal_to( True ) ) def test_HandlePollResponse_PollingNotSupported( self ): assert_that( _HandlePollResponse( False, None ), equal_to( False ) ) # 0 is not False assert_that( _HandlePollResponse( 0, None ), equal_to( True ) ) @patch( 'ycm.client.messages_request.PostVimMessage', new_callable = ExtendedMock ) def test_HandlePollResponse_SingleMessage( self, post_vim_message ): assert_that( _HandlePollResponse( [ { 'message': 'this is a message' } ] , None ), equal_to( True ) ) post_vim_message.assert_has_exact_calls( [ call( 'this is a message', warning=False, truncate=True ) ] ) @patch( 'ycm.client.messages_request.PostVimMessage', new_callable = ExtendedMock ) def test_HandlePollResponse_MultipleMessages( self, post_vim_message ): assert_that( _HandlePollResponse( [ { 'message': 'this is a message' }, { 'message': 'this is another one' } ] , None ), equal_to( True ) ) post_vim_message.assert_has_exact_calls( [ call( 'this is a message', warning=False, truncate=True ), call( 'this is another one', warning=False, truncate=True ) ] ) def test_HandlePollResponse_SingleDiagnostic( self ): diagnostics_handler = ExtendedMock() messages = [ { 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER' ] }, ] assert_that( _HandlePollResponse( messages, diagnostics_handler ), equal_to( True ) ) diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [ call( 'foo', [ 'PLACEHOLDER' ] ) ] ) def test_HandlePollResponse_MultipleDiagnostics( self ): diagnostics_handler = ExtendedMock() messages = [ { 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] }, { 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] }, { 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] }, { 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] }, ] assert_that( _HandlePollResponse( messages, diagnostics_handler ), equal_to( True ) ) diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [ call( 'foo', [ 'PLACEHOLDER1' ] ), call( 'bar', [ 'PLACEHOLDER2' ] ), call( 'baz', [ 'PLACEHOLDER3' ] ), call( 'foo', [ 'PLACEHOLDER4' ] ) ] ) @patch( 'ycm.client.messages_request.PostVimMessage', new_callable = ExtendedMock ) def test_HandlePollResponse_MultipleMessagesAndDiagnostics( self, post_vim_message ): diagnostics_handler = ExtendedMock() messages = [ { 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] }, { 'message': 'On the first day of Christmas, my VimScript gave to me' }, { 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] }, { 'message': 'A test file in a Command-T' }, { 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] }, { 'message': 'On the second day of Christmas, my VimScript gave to me' }, { 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] }, { 'message': 'Two popup menus, and a test file in a Command-T' }, ] assert_that( _HandlePollResponse( messages, diagnostics_handler ), equal_to( True ) ) diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [ call( 'foo', [ 'PLACEHOLDER1' ] ), call( 'bar', [ 'PLACEHOLDER2' ] ), call( 'baz', [ 'PLACEHOLDER3' ] ), call( 'foo', [ 'PLACEHOLDER4' ] ) ] ) post_vim_message.assert_has_exact_calls( [ call( 'On the first day of Christmas, my VimScript gave to me', warning=False, truncate=True ), call( 'A test file in a Command-T', warning=False, truncate=True ), call( 'On the second day of Christmas, my VimScript gave to me', warning=False, truncate=True ), call( 'Two popup menus, and a test file in a Command-T', warning=False, truncate=True ), ] ) ================================================ FILE: python/ycm/tests/client/omni_completion_request_test.py ================================================ # Copyright (C) 2020 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from unittest import TestCase from unittest.mock import MagicMock from hamcrest import assert_that, has_entries from ycm.client.omni_completion_request import OmniCompletionRequest def BuildOmnicompletionRequest( results, start_column = 1 ): omni_completer = MagicMock() omni_completer.ComputeCandidates = MagicMock( return_value = results ) request_data = { 'line_num': 1, 'column_num': 1, 'start_column': start_column } request = OmniCompletionRequest( omni_completer, request_data ) request.Start() return request class OmniCompletionRequestTest( TestCase ): def test_Done_AlwaysTrue( self ): request = BuildOmnicompletionRequest( [] ) assert_that( request.Done() ) def test_Response_FromOmniCompleter( self ): results = [ { "word": "test" } ] request = BuildOmnicompletionRequest( results ) assert_that( request.Response(), has_entries( { 'line': 1, 'column': 1, 'completion_start_column': 1, 'completions': results } ) ) ================================================ FILE: python/ycm/tests/command_test.py ================================================ # Copyright (C) 2016-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule, MockVimBuffers, VimBuffer MockVimModule() from hamcrest import assert_that, contains_exactly, has_entries from unittest.mock import patch from unittest import TestCase from ycm.tests import YouCompleteMeInstance class CommandTest( TestCase ): @YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'tempname()' ] } ) def test_SendCommandRequest_ExtraConfVimData_Works( self, ycm ): current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'GoTo' ], 'aboveleft', False, 1, 1 ) assert_that( # Positional arguments passed to SendCommandRequest. send_request.call_args[ 0 ], contains_exactly( contains_exactly( 'GoTo' ), 'aboveleft', 'same-buffer', has_entries( { 'options': has_entries( { 'tab_size': 2, 'insert_spaces': True, } ), 'extra_conf_data': has_entries( { 'tempname()': '_TEMP_FILE_' } ), } ), ) ) @YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'undefined_value' ] } ) def test_SendCommandRequest_ExtraConfData_UndefinedValue( self, ycm ): current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'GoTo' ], 'belowright', False, 1, 1 ) assert_that( # Positional arguments passed to SendCommandRequest. send_request.call_args[ 0 ], contains_exactly( contains_exactly( 'GoTo' ), 'belowright', 'same-buffer', has_entries( { 'options': has_entries( { 'tab_size': 2, 'insert_spaces': True, } ) } ), ) ) @YouCompleteMeInstance() def test_SendCommandRequest_BuildRange_NoVisualMarks( self, ycm, *args ): current_buffer = VimBuffer( 'buffer', contents = [ 'first line', 'second line' ] ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'GoTo' ], '', True, 1, 2 ) send_request.assert_called_once_with( [ 'GoTo' ], '', 'same-buffer', { 'options': { 'tab_size': 2, 'insert_spaces': True }, 'range': { 'start': { 'line_num': 1, 'column_num': 1 }, 'end': { 'line_num': 2, 'column_num': 12 } } }, ) @YouCompleteMeInstance() def test_SendCommandRequest_BuildRange_VisualMarks( self, ycm, *args ): current_buffer = VimBuffer( 'buffer', contents = [ 'first line', 'second line' ], visual_start = [ 1, 4 ], visual_end = [ 2, 8 ] ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'GoTo' ], 'tab', True, 1, 2 ) send_request.assert_called_once_with( [ 'GoTo' ], 'tab', 'same-buffer', { 'options': { 'tab_size': 2, 'insert_spaces': True }, 'range': { 'start': { 'line_num': 1, 'column_num': 5 }, 'end': { 'line_num': 2, 'column_num': 9 } } }, ) @YouCompleteMeInstance() def test_SendCommandRequest_IgnoreFileTypeOption( self, ycm, *args ): current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): expected_args = ( [ 'GoTo' ], '', 'same-buffer', { 'completer_target': 'python', 'options': { 'tab_size': 2, 'insert_spaces': True }, }, ) with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'ft=python', 'GoTo' ], '', False, 1, 1 ) send_request.assert_called_once_with( *expected_args ) with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request: ycm.SendCommandRequest( [ 'GoTo', 'ft=python' ], '', False, 1, 1 ) send_request.assert_called_once_with( *expected_args ) ================================================ FILE: python/ycm/tests/completion_test.py ================================================ # Copyright (C) 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock, MockVimModule, MockVimBuffers, VimBuffer ) MockVimModule() import contextlib from hamcrest import ( assert_that, contains_exactly, empty, equal_to, has_entries ) from unittest import TestCase from unittest.mock import call, MagicMock, patch from ycm.tests import PathToTestFile, YouCompleteMeInstance from ycmd.responses import ServerError import json @contextlib.contextmanager def MockCompletionRequest( response_method ): """Mock out the CompletionRequest, replacing the response handler JsonFromFuture with the |response_method| parameter.""" # We don't want the requests to actually be sent to the server, just have it # return success. with patch( 'ycm.client.completer_available_request.' 'CompleterAvailableRequest.PostDataToHandler', return_value = True ): with patch( 'ycm.client.completion_request.CompletionRequest.' 'PostDataToHandlerAsync', return_value = MagicMock( return_value=True ) ): # We set up a fake response. with patch( 'ycm.client.base_request._JsonFromFuture', side_effect = response_method ): yield @contextlib.contextmanager def MockResolveRequest( response_method ): """Mock out the CompletionRequest, replacing the response handler JsonFromFuture with the |response_method| parameter.""" with patch( 'ycm.client.resolve_completion_request.ResolveCompletionRequest.' 'PostDataToHandlerAsync', return_value = MagicMock( return_value=True ) ): # We set up a fake response. with patch( 'ycm.client.base_request._JsonFromFuture', side_effect = response_method ): yield class CompletionTest( TestCase ): @YouCompleteMeInstance() def test_SendCompletionRequest_UnicodeWorkingDirectory( self, ycm ): unicode_dir = PathToTestFile( 'uni¢od€' ) current_buffer = VimBuffer( PathToTestFile( 'uni¢𐍈d€', 'current_buffer' ) ) def ServerResponse( *args ): return { 'completions': [], 'completion_start_column': 1 } with CurrentWorkingDirectory( unicode_dir ): with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( ServerResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 1 } ) ) @YouCompleteMeInstance() @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_SendCompletionRequest_ResponseContainingError( self, ycm, post_vim_message ): current_buffer = VimBuffer( 'buffer' ) def ServerResponse( *args ): return { 'completions': [ { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string' } } ], 'completion_start_column': 3, 'errors': [ { 'exception': { 'TYPE': 'Exception' }, 'message': 'message', 'traceback': 'traceback' } ] } with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( ServerResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_has_exact_calls( [ call( 'Exception: message', truncate = True ) ] ) assert_that( response, has_entries( { 'completions': contains_exactly( has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string', 'kind': 'k', 'dup': 1, 'empty': 1 } ) ), 'completion_start_column': 3 } ) ) @YouCompleteMeInstance() @patch( 'ycm.client.base_request._logger', autospec = True ) @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_SendCompletionRequest_ErrorFromServer( self, ycm, post_vim_message, logger ): current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( ServerError( 'Server error' ) ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() logger.exception.assert_called_with( 'Error while handling server ' 'response' ) post_vim_message.assert_has_exact_calls( [ call( 'Server error', truncate = True ) ] ) assert_that( response, has_entries( { 'completions': empty(), 'completion_start_column': -1 } ) ) @YouCompleteMeInstance() @patch( 'ycm.client.base_request._logger', autospec = True ) @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_ResolveCompletionRequest_Resolves( self, ycm, post_vim_message, logger ): def CompletionResponse( *args ): return { 'completions': [ { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string', 'resolve': 10 } } ], 'completion_start_column': 3, 'errors': [] } def ResolveResponse( *args ): return { 'completion': { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string with more info' } }, 'errors': [] } current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( CompletionResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_not_called() assert_that( response, has_entries( { 'completions': contains_exactly( has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string', 'kind': 'k', 'dup': 1, 'empty': 1 } ) ), 'completion_start_column': 3 } ) ) item = response[ 'completions' ][ 0 ] assert_that( json.loads( item[ 'user_data' ] ), has_entries( { 'resolve': 10 } ) ) with MockResolveRequest( ResolveResponse ): assert_that( ycm.ResolveCompletionItem( item ), equal_to( True ) ) assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_not_called() assert_that( response, has_entries( { 'completion': has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string with more info', 'kind': 'k', 'dup': 1, 'empty': 1 } ) } ) ) item = response[ 'completion' ] with MockResolveRequest( ServerError( 'must not be called' ) ): assert_that( ycm.ResolveCompletionItem( item ), equal_to( False ) ) post_vim_message.assert_not_called() @YouCompleteMeInstance() @patch( 'ycm.client.base_request._logger', autospec = True ) @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_ResolveCompletionRequest_ResponseContainsErrors( self, ycm, post_vim_message, logger ): def CompletionResponse( *args ): return { 'completions': [ { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string', 'resolve': 10 } } ], 'completion_start_column': 3, 'errors': [] } def ResolveResponse( *args ): return { 'completion': { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string with more info' } }, 'errors': [ { 'exception': { 'TYPE': 'Exception' }, 'message': 'message', 'traceback': 'traceback' } ] } current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( CompletionResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_not_called() assert_that( response, has_entries( { 'completions': contains_exactly( has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string', 'kind': 'k', 'dup': 1, 'empty': 1 } ) ), 'completion_start_column': 3 } ) ) item = response[ 'completions' ][ 0 ] assert_that( json.loads( item[ 'user_data' ] ), has_entries( { 'resolve': 10 } ) ) with MockResolveRequest( ResolveResponse ): assert_that( ycm.ResolveCompletionItem( item ), equal_to( True ) ) assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_has_exact_calls( [ call( 'Exception: message', truncate = True ) ] ) assert_that( response, has_entries( { 'completion': has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string with more info', 'kind': 'k', 'dup': 1, 'empty': 1 } ) } ) ) @YouCompleteMeInstance() @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_ResolveCompletionItem_NoUserData( self, ycm, post_vim_message ): def CompletionResponse( *args ): return { 'completions': [ { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind' } ], 'completion_start_column': 3, 'errors': [] } current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( CompletionResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_not_called() assert_that( response, has_entries( { 'completions': contains_exactly( has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info', 'kind': 'k', 'dup': 1, 'empty': 1 } ) ), 'completion_start_column': 3 } ) ) item = response[ 'completions' ][ 0 ] item.pop( 'user_data' ) with MockResolveRequest( ServerError( 'must not be called' ) ): assert_that( ycm.ResolveCompletionItem( item ), equal_to( False ) ) post_vim_message.assert_not_called() @YouCompleteMeInstance() def test_ResolveCompletionItem_NoRequest( self, ycm ): assert_that( ycm.GetCurrentCompletionRequest(), equal_to( None ) ) assert_that( ycm.ResolveCompletionItem( {} ), equal_to( False ) ) @YouCompleteMeInstance() @patch( 'ycm.client.base_request._logger', autospec = True ) @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) def test_ResolveCompletionRequest_ServerError( self, ycm, post_vim_message, logger ): def ServerResponse( *args ): return { 'completions': [ { 'insertion_text': 'insertion_text', 'menu_text': 'menu_text', 'extra_menu_info': 'extra_menu_info', 'detailed_info': 'detailed_info', 'kind': 'kind', 'extra_data': { 'doc_string': 'doc_string', 'resolve': 10 } } ], 'completion_start_column': 3, 'errors': [] } current_buffer = VimBuffer( 'buffer' ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): with MockCompletionRequest( ServerResponse ): ycm.SendCompletionRequest() assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() post_vim_message.assert_not_called() assert_that( response, has_entries( { 'completions': contains_exactly( has_entries( { 'word': 'insertion_text', 'abbr': 'menu_text', 'menu': 'extra_menu_info', 'info': 'detailed_info\ndoc_string', 'kind': 'k', 'dup': 1, 'empty': 1 } ) ), 'completion_start_column': 3 } ) ) item = response[ 'completions' ][ 0 ] assert_that( json.loads( item[ 'user_data' ] ), has_entries( { 'resolve': 10 } ) ) with MockResolveRequest( ServerError( 'Server error' ) ): ycm.ResolveCompletionItem( item ) assert_that( ycm.CompletionRequestReady() ) response = ycm.GetCompletionResponse() logger.exception.assert_called_with( 'Error while handling server ' 'response' ) post_vim_message.assert_has_exact_calls( [ call( 'Server error', truncate = True ) ] ) ================================================ FILE: python/ycm/tests/diagnostic_filter_test.py ================================================ # Copyright (C) 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule MockVimModule() from hamcrest import assert_that, equal_to from unittest import TestCase from ycm.diagnostic_filter import DiagnosticFilter def _assert_accept_equals( filter, text_or_obj, expected ): if not isinstance( text_or_obj, dict ): text_or_obj = { 'text': text_or_obj } assert_that( filter.IsAllowed( text_or_obj ), equal_to( expected ) ) def _assert_accepts( filter, text ): _assert_accept_equals( filter, text, True ) def _assert_rejects( filter, text ): _assert_accept_equals( filter, text, False ) def _JavaFilter( config ): return { 'filter_diagnostics' : { 'java': config } } def _CreateFilterForTypes( opts, types ): return DiagnosticFilter.CreateFromOptions( opts ).SubsetForTypes( types ) class DiagnosticFilterTest( TestCase ): def test_RegexFilter( self ): opts = _JavaFilter( { 'regex' : 'taco' } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_rejects( f, 'This is a Taco' ) _assert_accepts( f, 'This is a Burrito' ) def test_RegexSingleList( self ): opts = _JavaFilter( { 'regex' : [ 'taco' ] } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_rejects( f, 'This is a Taco' ) _assert_accepts( f, 'This is a Burrito' ) def test_RegexMultiList( self ): opts = _JavaFilter( { 'regex' : [ 'taco', 'burrito' ] } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_rejects( f, 'This is a Taco' ) _assert_rejects( f, 'This is a Burrito' ) def test_RegexNotFiltered( self ): opts = _JavaFilter( { 'regex' : 'taco' } ) f = _CreateFilterForTypes( opts, [ 'cs' ] ) _assert_accepts( f, 'This is a Taco' ) _assert_accepts( f, 'This is a Burrito' ) def test_LevelWarnings( self ): opts = _JavaFilter( { 'level' : 'warning' } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_rejects( f, { 'text' : 'This is an unimportant taco', 'kind' : 'WARNING' } ) _assert_accepts( f, { 'text' : 'This taco will be shown', 'kind' : 'ERROR' } ) def test_LevelErrors( self ): opts = _JavaFilter( { 'level' : 'error' } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_accepts( f, { 'text' : 'This is an IMPORTANT taco', 'kind' : 'WARNING' } ) _assert_rejects( f, { 'text' : 'This taco will NOT be shown', 'kind' : 'ERROR' } ) def test_MultipleFilterTypesTypeTest( self ): opts = _JavaFilter( { 'regex' : '.*taco.*', 'level' : 'warning' } ) f = _CreateFilterForTypes( opts, [ 'java' ] ) _assert_rejects( f, { 'text' : 'This is an unimportant taco', 'kind' : 'WARNING' } ) _assert_rejects( f, { 'text' : 'This taco will NOT be shown', 'kind' : 'ERROR' } ) _assert_accepts( f, { 'text' : 'This burrito WILL be shown', 'kind' : 'ERROR' } ) def test_MergeMultipleFiletypes( self ): opts = { 'filter_diagnostics' : { 'java' : { 'regex' : '.*taco.*' }, 'xml' : { 'regex' : '.*burrito.*' } } } f = _CreateFilterForTypes( opts, [ 'java', 'xml' ] ) _assert_rejects( f, 'This is a Taco' ) _assert_rejects( f, 'This is a Burrito' ) _assert_accepts( f, 'This is some Nachos' ) def test_CommaSeparatedFiletypes( self ): opts = { 'filter_diagnostics' : { 'java,c,cs' : { 'regex' : '.*taco.*' } } } f = _CreateFilterForTypes( opts, [ 'cs' ] ) _assert_rejects( f, 'This is a Taco' ) _assert_accepts( f, 'This is a Burrito' ) ================================================ FILE: python/ycm/tests/diagnostic_interface_test.py ================================================ # Copyright (C) 2015-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm import diagnostic_interface from ycm.tests.test_utils import VimBuffer, MockVimModule, MockVimBuffers from hamcrest import ( assert_that, contains_exactly, equal_to, has_entries, has_item ) from unittest import TestCase MockVimModule() def SimpleDiagnosticToJson( start_line, start_col, end_line, end_col ): return { 'kind': 'ERROR', 'location': { 'line_num': start_line, 'column_num': start_col }, 'location_extent': { 'start': { 'line_num': start_line, 'column_num': start_col }, 'end': { 'line_num': end_line, 'column_num': end_col } }, 'ranges': [ { 'start': { 'line_num': start_line, 'column_num': start_col }, 'end': { 'line_num': end_line, 'column_num': end_col } } ] } def SimpleDiagnosticToJsonWithInvalidLineNum( start_line, start_col, end_line, end_col ): return { 'kind': 'ERROR', 'location': { 'line_num': start_line, 'column_num': start_col }, 'location_extent': { 'start': { 'line_num': start_line, 'column_num': start_col }, 'end': { 'line_num': end_line, 'column_num': end_col } }, 'ranges': [ { 'start': { 'line_num': 0, 'column_num': 0 }, 'end': { 'line_num': 0, 'column_num': 0 } }, { 'start': { 'line_num': start_line, 'column_num': start_col }, 'end': { 'line_num': end_line, 'column_num': end_col } } ] } def YcmTextPropertyTupleMatcher( start_line, start_col, end_line, end_col ): return has_item( contains_exactly( start_line, start_col, 'YcmErrorProperty', has_entries( { 'end_col': end_col, 'end_lnum': end_line } ) ) ) class DiagnosticInterfaceTest( TestCase ): def test_ConvertDiagnosticToTextProperties( self ): for diag, contents, result in [ # Error in middle of the line [ SimpleDiagnosticToJson( 1, 16, 1, 23 ), [ 'Highlight this error please' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 23 ) ], # Error at the end of the line [ SimpleDiagnosticToJson( 1, 16, 1, 21 ), [ 'Highlight this warning' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 21 ) ], [ SimpleDiagnosticToJson( 1, 16, 1, 19 ), [ 'Highlight unicøde' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 19 ) ], # Non-positive position [ SimpleDiagnosticToJson( 0, 0, 0, 0 ), [ 'Some contents' ], {} ], [ SimpleDiagnosticToJson( -1, -2, -3, -4 ), [ 'Some contents' ], YcmTextPropertyTupleMatcher( 1, 1, 1, 1 ) ], ]: with self.subTest( diag = diag, contents = contents, result = result ): current_buffer = VimBuffer( 'foo', number = 1, contents = [ '' ] ) target_buffer = VimBuffer( 'bar', number = 2, contents = contents ) with MockVimBuffers( [ current_buffer, target_buffer ], [ current_buffer, target_buffer ] ): actual = diagnostic_interface._ConvertDiagnosticToTextProperties( target_buffer.number, diag ) print( actual ) assert_that( actual, result ) def test_ConvertDiagnosticWithInvalidLineNum( self ): for diag, contents, result in [ # Error in middle of the line [ SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 23 ), [ 'Highlight this error please' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 23 ) ], # Error at the end of the line [ SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 21 ), [ 'Highlight this warning' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 21 ) ], [ SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 19 ), [ 'Highlight unicøde' ], YcmTextPropertyTupleMatcher( 1, 16, 1, 19 ) ], ]: with self.subTest( diag = diag, contents = contents, result = result ): current_buffer = VimBuffer( 'foo', number = 1, contents = [ '' ] ) target_buffer = VimBuffer( 'bar', number = 2, contents = contents ) with MockVimBuffers( [ current_buffer, target_buffer ], [ current_buffer, target_buffer ] ): actual = diagnostic_interface._ConvertDiagnosticToTextProperties( target_buffer.number, diag ) print( actual ) assert_that( actual, result ) def test_IsValidRange( self ): for start_line, start_col, end_line, end_col, expect in ( ( 1, 1, 1, 1, True ), ( 1, 1, 0, 0, False ), ( 1, 1, 2, 1, True ), ( 1, 2, 2, 1, True ), ( 2, 1, 1, 1, False ), ( 2, 2, 2, 1, False ), ): with self.subTest( start=( start_line, start_col ), end=( end_line, end_col ), expect = expect ): assert_that( diagnostic_interface._IsValidRange( start_line, start_col, end_line, end_col ), equal_to( expect ) ) ================================================ FILE: python/ycm/tests/event_notification_test.py ================================================ # Copyright (C) 2015-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock, MockVimBuffers, MockVimModule, VimBuffer, VimSign ) MockVimModule() import contextlib import os from ycm.tests import ( PathToTestFile, test_utils, YouCompleteMeInstance, WaitUntilReady ) from ycmd.responses import ( BuildDiagnosticData, Diagnostic, Location, Range, UnknownExtraConf, ServerError ) from hamcrest import ( assert_that, contains_exactly, empty, equal_to, has_entries, has_entry, has_item, has_items, has_key, is_not ) from unittest import TestCase from unittest.mock import call, MagicMock, patch def PresentDialog_Confirm_Call( message ): """Return a mock.call object for a call to vimsupport.PresentDialog, as called why vimsupport.Confirm with the supplied confirmation message""" return call( message, [ 'Ok', 'Cancel' ] ) @contextlib.contextmanager def MockArbitraryBuffer( filetype ): """Used via the with statement, set up a single buffer with an arbitrary name and no contents. Its filetype is set to the supplied filetype.""" # Arbitrary, but valid, single buffer open. current_buffer = VimBuffer( os.path.realpath( 'TEST_BUFFER' ), filetype = filetype ) with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): yield @contextlib.contextmanager def MockEventNotification( response_method, native_filetype_completer = True ): """Mock out the EventNotification client request object, replacing the Response handler's JsonFromFuture with the supplied |response_method|. Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype method to return the supplied |native_filetype_completer| parameter, rather than querying the server""" # We don't want the event to actually be sent to the server, just have it # return success with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync', return_value = MagicMock( return_value=True ) ): # We set up a fake a Response (as called by EventNotification.Response) # which calls the supplied callback method. Generally this callback just # raises an apropriate exception, otherwise it would have to return a mock # future object. with patch( 'ycm.client.base_request._JsonFromFuture', side_effect = response_method ): # Filetype available information comes from the server, so rather than # relying on that request, we mock out the check. The caller decides if # filetype completion is available with patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype', return_value = native_filetype_completer ): yield def _Check_FileReadyToParse_Diagnostic_Error( ycm ): # Tests Vim sign placement and error/warning count python API # when one error is returned. def DiagnosticResponse( *args ): start = Location( 1, 2, 'TEST_BUFFER' ) end = Location( 1, 4, 'TEST_BUFFER' ) extent = Range( start, end ) diagnostic = Diagnostic( [], start, extent, 'expected ;', 'ERROR' ) return [ BuildDiagnosticData( diagnostic ) ] with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( DiagnosticResponse ): ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, contains_exactly( VimSign( 1, 'YcmError', 1 ) ) ) assert_that( ycm.GetErrorCount(), equal_to( 1 ) ) assert_that( ycm.GetWarningCount(), equal_to( 0 ) ) # Consequent calls to HandleFileParseRequest shouldn't mess with # existing diagnostics, when there is no new parse request. ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, contains_exactly( VimSign( 1, 'YcmError', 1 ) ) ) assert_that( ycm.GetErrorCount(), equal_to( 1 ) ) assert_that( ycm.GetWarningCount(), equal_to( 0 ) ) assert_that( not ycm.ShouldResendFileParseRequest() ) # New identical requests should result in the same diagnostics. ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, contains_exactly( VimSign( 1, 'YcmError', 1 ) ) ) assert_that( ycm.GetErrorCount(), equal_to( 1 ) ) assert_that( ycm.GetWarningCount(), equal_to( 0 ) ) assert_that( not ycm.ShouldResendFileParseRequest() ) def _Check_FileReadyToParse_Diagnostic_Warning( ycm ): # Tests Vim sign placement/unplacement and error/warning count python API # when one warning is returned. # Should be called after _Check_FileReadyToParse_Diagnostic_Error def DiagnosticResponse( *args ): start = Location( 2, 2, 'TEST_BUFFER' ) end = Location( 2, 4, 'TEST_BUFFER' ) extent = Range( start, end ) diagnostic = Diagnostic( [], start, extent, 'cast', 'WARNING' ) return [ BuildDiagnosticData( diagnostic ) ] with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( DiagnosticResponse ): ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, contains_exactly( VimSign( 2, 'YcmWarning', 1 ) ) ) assert_that( ycm.GetErrorCount(), equal_to( 0 ) ) assert_that( ycm.GetWarningCount(), equal_to( 1 ) ) # Consequent calls to HandleFileParseRequest shouldn't mess with # existing diagnostics, when there is no new parse request. ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, contains_exactly( VimSign( 2, 'YcmWarning', 1 ) ) ) assert_that( ycm.GetErrorCount(), equal_to( 0 ) ) assert_that( ycm.GetWarningCount(), equal_to( 1 ) ) assert_that( not ycm.ShouldResendFileParseRequest() ) def _Check_FileReadyToParse_Diagnostic_Clean( ycm ): # Tests Vim sign unplacement and error/warning count python API # when there are no errors/warnings left. # Should be called after _Check_FileReadyToParse_Diagnostic_Warning with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( MagicMock( return_value = [] ) ): ycm.OnFileReadyToParse() ycm.HandleFileParseRequest() assert_that( test_utils.VIM_SIGNS, empty() ) assert_that( ycm.GetErrorCount(), equal_to( 0 ) ) assert_that( ycm.GetWarningCount(), equal_to( 0 ) ) assert_that( not ycm.ShouldResendFileParseRequest() ) class EventNotificationTest( TestCase ): @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) @YouCompleteMeInstance() def test_EventNotification_FileReadyToParse_NonDiagnostic_Error( self, ycm, post_vim_message ): # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest # in combination with YouCompleteMe.OnFileReadyToParse when the completer # raises an exception handling FileReadyToParse event notification ERROR_TEXT = 'Some completer response text' def ErrorResponse( *args ): raise ServerError( ERROR_TEXT ) with MockArbitraryBuffer( 'some_filetype' ): with MockEventNotification( ErrorResponse ): ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() # The first call raises a warning post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ) ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ) ] ) assert_that( not ycm.ShouldResendFileParseRequest() ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ), call( ERROR_TEXT, truncate = True ) ] ) assert_that( not ycm.ShouldResendFileParseRequest() ) @YouCompleteMeInstance() def test_EventNotification_FileReadyToParse_NonDiagnostic_Error_NonNative( self, ycm ): test_utils.VIM_MATCHES = [] test_utils.VIM_SIGNS = [] with MockArbitraryBuffer( 'some_filetype' ): with MockEventNotification( None, False ): ycm.OnFileReadyToParse() ycm.HandleFileParseRequest() assert_that( test_utils.VIM_MATCHES, empty() ) assert_that( test_utils.VIM_SIGNS, empty() ) assert_that( not ycm.ShouldResendFileParseRequest() ) @YouCompleteMeInstance() def test_EventNotification_FileReadyToParse_NonDiagnostic_ConfirmExtraConf( self, ycm ): # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest # in combination with YouCompleteMe.OnFileReadyToParse when the completer # raises the (special) UnknownExtraConf exception FILE_NAME = 'a_file' MESSAGE = ( 'Found ' + FILE_NAME + '. Load? \n\n(Question can be ' 'turned off with options, see YCM docs)' ) def UnknownExtraConfResponse( *args ): raise UnknownExtraConf( FILE_NAME ) with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandler', new_callable = ExtendedMock ) as post_data_to_handler: with MockArbitraryBuffer( 'some_filetype' ): with MockEventNotification( UnknownExtraConfResponse ): # When the user accepts the extra conf, we load it with patch( 'ycm.vimsupport.PresentDialog', return_value = 0, new_callable = ExtendedMock ) as present_dialog: ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' ) ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ) ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' ) ] ) assert_that( ycm.ShouldResendFileParseRequest() ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), PresentDialog_Confirm_Call( MESSAGE ), ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' ), call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' ) ] ) assert_that( ycm.ShouldResendFileParseRequest() ) post_data_to_handler.reset_mock() # When the user rejects the extra conf, we reject it with patch( 'ycm.vimsupport.PresentDialog', return_value = 1, new_callable = ExtendedMock ) as present_dialog: ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' ) ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ) ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' ) ] ) assert_that( ycm.ShouldResendFileParseRequest() ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() assert_that( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), PresentDialog_Confirm_Call( MESSAGE ), ] ) post_data_to_handler.assert_has_exact_calls( [ call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' ), call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' ) ] ) assert_that( ycm.ShouldResendFileParseRequest() ) @YouCompleteMeInstance() def test_EventNotification_FileReadyToParse_Diagnostic_Error_Native( self, ycm ): test_utils.VIM_SIGNS = [] _Check_FileReadyToParse_Diagnostic_Error( ycm ) _Check_FileReadyToParse_Diagnostic_Warning( ycm ) _Check_FileReadyToParse_Diagnostic_Clean( ycm ) @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' ) @YouCompleteMeInstance( { 'g:ycm_collect_identifiers_from_tags_files': 1 } ) def test_EventNotification_FileReadyToParse_TagFiles_UnicodeWorkingDirectory( self, ycm, *args ): unicode_dir = PathToTestFile( 'uni¢od€' ) current_buffer_file = PathToTestFile( 'uni¢𐍈d€', 'current_buffer' ) current_buffer = VimBuffer( name = current_buffer_file, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype' ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with CurrentWorkingDirectory( unicode_dir ): with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ): ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entries( { 'filepath': current_buffer_file, 'line_num': 1, 'column_num': 6, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'FileReadyToParse', 'tag_files': has_item( PathToTestFile( 'uni¢od€', 'tags' ) ) } ), 'event_notification' ) ) @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' ) @YouCompleteMeInstance() def test_EventNotification_BufferVisit_BuildRequestForCurrentAndUnsavedBuffers( # noqa self, ycm, *args ): current_buffer_file = os.path.realpath( 'current_buffer' ) current_buffer = VimBuffer( name = current_buffer_file, number = 1, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype', modified = False ) modified_buffer_file = os.path.realpath( 'modified_buffer' ) modified_buffer = VimBuffer( name = modified_buffer_file, number = 2, contents = [ 'modified_buffer_contents' ], filetype = 'some_filetype', modified = True ) unmodified_buffer_file = os.path.realpath( 'unmodified_buffer' ) unmodified_buffer = VimBuffer( name = unmodified_buffer_file, number = 3, contents = [ 'unmodified_buffer_contents' ], filetype = 'some_filetype', modified = False ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer, modified_buffer, unmodified_buffer ], [ current_buffer ], ( 1, 5 ) ): ycm.OnBufferVisit() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entries( { 'filepath': current_buffer_file, 'line_num': 1, 'column_num': 6, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ), modified_buffer_file: has_entries( { 'contents': 'modified_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'BufferVisit' } ), 'event_notification' ) ) @YouCompleteMeInstance() def test_EventNotification_BufferUnload_BuildRequestForDeletedAndUnsavedBuffers( # noqa self, ycm ): current_buffer_file = os.path.realpath( 'current_βuffer' ) current_buffer = VimBuffer( name = current_buffer_file, number = 1, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype', modified = True ) deleted_buffer_file = os.path.realpath( 'deleted_βuffer' ) deleted_buffer = VimBuffer( name = deleted_buffer_file, number = 2, contents = [ 'deleted_buffer_contents' ], filetype = 'some_filetype', modified = False ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer, deleted_buffer ], [ current_buffer ] ): ycm.OnBufferUnload( deleted_buffer.number ) assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entries( { 'filepath': deleted_buffer_file, 'line_num': 1, 'column_num': 1, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ), deleted_buffer_file: has_entries( { 'contents': 'deleted_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'BufferUnload' } ), 'event_notification' ) ) @patch( 'ycm.vimsupport.CaptureVimCommand', return_value = """ fooGroup xxx foo bar links to Statement""" ) @YouCompleteMeInstance( { 'g:ycm_seed_identifiers_with_syntax': 1 } ) def test_EventNotification_FileReadyToParse_SyntaxKeywords_SeedWithCache( self, ycm, *args ): current_buffer = VimBuffer( name = 'current_buffer', filetype = 'some_filetype' ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ), 'event_notification' ) ) # Do not send again syntax keywords in subsequent requests. ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( is_not( has_key( 'syntax_keywords' ) ), 'event_notification' ) ) @patch( 'ycm.vimsupport.CaptureVimCommand', return_value = """ fooGroup xxx foo bar links to Statement""" ) @YouCompleteMeInstance( { 'g:ycm_seed_identifiers_with_syntax': 1 } ) def test_EventNotification_FileReadyToParse_SyntaxKeywords_ClearCacheIfRestart( # noqa self, ycm, *args ): current_buffer = VimBuffer( name = 'current_buffer', filetype = 'some_filetype' ) with patch( 'ycm.client.event_notification.EventNotification.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer ], [ current_buffer ] ): ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ), 'event_notification' ) ) # Send again the syntax keywords after restarting the server. ycm.RestartServer() WaitUntilReady() ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains_exactly( has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ), 'event_notification' ) ) ================================================ FILE: python/ycm/tests/mock_utils.py ================================================ # Copyright (C) 2017 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . import json from unittest import mock HTTP_OK = 200 class FakeResponse: """A fake version of a requests response object, just about suitable for mocking a server response. Not usually used directly. See MockServerResponse* methods""" def __init__( self, response, exception ): self._json = response self._exception = exception self.code = HTTP_OK def read( self ): if self._exception: raise self._exception return json.dumps( self._json ).encode( 'utf-8' ) def close( self ): pass class FakeFuture: """A fake version of a future response object, just about suitable for mocking a server response as generated by PostDataToHandlerAsync. Not usually used directly. See MockAsyncServerResponse* methods""" def __init__( self, done, response = None, exception = None ): self._done = done if not done: self._result = None else: self._result = FakeResponse( response, exception ) def done( self ): return self._done def result( self ): return self._result def MockAsyncServerResponseDone( response ): """Return a MessagePoll containing a fake future object that is complete with the supplied response message. Suitable for mocking a response future within a client request. For example: with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v: mock_response = MockAsyncServerResponseDone( response ) with patch.dict( ycm._message_poll_requests, {} ): ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer ) ycm._message_poll_requests[ filetype ]._response_future = mock_response # Needed to keep a reference to the mocked dictionary mock_future = ycm._message_poll_requests[ filetype ]._response_future ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ... """ return mock.MagicMock( wraps = FakeFuture( True, response ) ) def MockAsyncServerResponseInProgress(): """Return a fake future object that is incomplete. Suitable for mocking a response future within a client request. For example: with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v: mock_response = MockAsyncServerResponseInProgress() with patch.dict( ycm._message_poll_requests, {} ): ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer ) ycm._message_poll_requests[ filetype ]._response_future = mock_response # Needed to keep a reference to the mocked dictionary mock_future = ycm._message_poll_requests[ filetype ]._response_future ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ... """ return mock.MagicMock( wraps = FakeFuture( False ) ) def MockAsyncServerResponseException( exception ): """Return a fake future object that is complete, but raises an exception. Suitable for mocking a response future within a client request. For example: with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v: mock_response = MockAsyncServerResponseException( exception ) with patch.dict( ycm._message_poll_requests, {} ): ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer ) ycm._message_poll_requests[ filetype ]._response_future = mock_response # Needed to keep a reference to the mocked dictionary mock_future = ycm._message_poll_requests[ filetype ]._response_future ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ... """ return mock.MagicMock( wraps = FakeFuture( True, None, exception ) ) # TODO: In future, implement MockServerResponse and MockServerResponseException # for synchronous cases when such test cases are needed. ================================================ FILE: python/ycm/tests/omni_completer_test.py ================================================ # encoding: utf-8 # # Copyright (C) 2016-2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from hamcrest import assert_that, contains_exactly, empty, has_entries from unittest import TestCase from ycm.tests.test_utils import MockVimBuffers, MockVimModule, VimBuffer MockVimModule() from ycm import vimsupport from ycm.tests import YouCompleteMeInstance, youcompleteme_instance FILETYPE = 'ycmtest' TRIGGERS = { 'ycmtest': [ '.' ] } def StartColumnCompliance( ycm, omnifunc_start_column, ycm_completions, ycm_start_column ): def Omnifunc( findstart, base ): if findstart: return omnifunc_start_column return [ 'foo' ] current_buffer = VimBuffer( 'buffer', contents = [ 'fo' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 2 ) ): ycm.SendCompletionRequest( force_semantic = True ) r = ycm.GetCompletionResponse() assert_that( r, has_entries( { 'completions': ycm_completions, 'completion_start_column': ycm_start_column } ) ) class OmniCompleterTest( TestCase ): @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_List( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_ListFilter( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_List( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_ListFilter( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() # Actual result is that the results are not filtered, as we expect the # omnifunc or vim itself to do this filtering. assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_UseFindStart( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 0 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() # Actual result is that the results are not filtered, as we expect the # omnifunc or vim itself to do this filtering. assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 1 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_UseFindStart( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 0 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() # There are no results because the query 'test.t' doesn't match any # candidate (and cache_omnifunc=1, so we FilterAndSortCandidates). assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 1 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_Object( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return { 'words': [ 'a', 'b', 'CDtEF' ] } current_buffer = VimBuffer( 'buffer', contents = [ 'test.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'CDtEF', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_ObjectList( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ { 'word': 'a', 'abbr': 'ABBR', 'menu': 'MENU', 'info': 'INFO', 'kind': 'K' }, { 'word': 'test', 'abbr': 'ABBRTEST', 'menu': 'MENUTEST', 'info': 'INFOTEST', 'kind': 'T' } ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.tt' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': contains_exactly( { 'word' : 'test', 'abbr' : 'ABBRTEST', 'menu' : 'MENUTEST', 'info' : 'INFOTEST', 'kind' : 'T', 'equal': 1 } ), 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_ObjectList( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ { 'word': 'a', 'abbr': 'ABBR', 'menu': 'MENU', 'info': 'INFO', 'kind': 'K' }, { 'word': 'test', 'abbr': 'ABBRTEST', 'menu': 'MENUTEST', 'info': 'INFOTEST', 'kind': 'T' } ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.tt' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ): ycm.SendCompletionRequest() # We don't filter the result - we expect the omnifunc to do that # based on the query we supplied (Note: that means no fuzzy matching!). assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word' : 'a', 'abbr' : 'ABBR', 'menu' : 'MENU', 'info' : 'INFO', 'kind' : 'K', 'equal': 1 }, { 'word' : 'test', 'abbr' : 'ABBRTEST', 'menu' : 'MENUTEST', 'info' : 'INFOTEST', 'kind' : 'T', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_ObjectListObject( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return { 'words': [ { 'word': 'a', 'abbr': 'ABBR', 'menu': 'MENU', 'info': 'INFO', 'kind': 'K' }, { 'word': 'test', 'abbr': 'ABBRTEST', 'menu': 'MENUTEST', 'info': 'INFOTEST', 'kind': 'T' } ] } current_buffer = VimBuffer( 'buffer', contents = [ 'test.tt' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word' : 'test', 'abbr' : 'ABBRTEST', 'menu' : 'MENUTEST', 'info' : 'INFOTEST', 'kind' : 'T', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_ObjectListObject( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return { 'words': [ { 'word': 'a', 'abbr': 'ABBR', 'menu': 'MENU', 'info': 'INFO', 'kind': 'K' }, { 'word': 'test', 'abbr': 'ABBRTEST', 'menu': 'MENUTEST', 'info': 'INFOTEST', 'kind': 'T' } ] } current_buffer = VimBuffer( 'buffer', contents = [ 'test.tt' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ): ycm.SendCompletionRequest() # No FilterAndSortCandidates for cache_omnifunc=0 (we expect the omnifunc # to do the filtering?) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word' : 'a', 'abbr' : 'ABBR', 'menu' : 'MENU', 'info' : 'INFO', 'kind' : 'K', 'equal': 1 }, { 'word' : 'test', 'abbr' : 'ABBRTEST', 'menu' : 'MENUTEST', 'info' : 'INFOTEST', 'kind' : 'T', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_List_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ] current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 12 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'å_unicode_identifier', 'equal': 1 }, { 'word': 'πππππππ yummy πie', 'equal': 1 }, { 'word': '†est', 'equal': 1 } ], 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_List_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ] current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 12 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': '†est', 'equal': 1 }, { 'word': 'å_unicode_identifier', 'equal': 1 }, { 'word': 'πππππππ yummy πie', 'equal': 1 } ], 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_List_Filter_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ] current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.ππ' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'πππππππ yummy πie', 'equal': 1 } ], 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_List_Filter_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return [ 'πππππππ yummy πie' ] current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.ππ' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'πππππππ yummy πie', 'equal': 1 } ], 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_ObjectList_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return [ { 'word': 'ålpha∫et', 'abbr': 'å∫∫®', 'menu': 'µ´~¨á', 'info': '^~fo', 'kind': '˚' }, { 'word': 'π†´ß†π', 'abbr': 'ÅııÂʉÍÊ', 'menu': '˜‰ˆËʉÍÊ', 'info': 'ÈˆÏØÊ‰ÍÊ', 'kind': 'Ê' } ] current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.ππ' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word' : 'π†´ß†π', 'abbr' : 'ÅııÂʉÍÊ', 'menu' : '˜‰ˆËʉÍÊ', 'info' : 'ÈˆÏØÊ‰ÍÊ', 'kind' : 'Ê', 'equal': 1 } ], 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_Cache_ObjectListObject_Unicode( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 12 return { 'words': [ { 'word': 'ålpha∫et', 'abbr': 'å∫∫®', 'menu': 'µ´~¨á', 'info': '^~fo', 'kind': '˚' }, { 'word': 'π†´ß†π', 'abbr': 'ÅııÂʉÍÊ', 'menu': '˜‰ˆËʉÍÊ', 'info': 'ÈˆÏØÊ‰ÍÊ', 'kind': 'Ê' }, { 'word': 'test', 'abbr': 'ÅııÂʉÍÊ', 'menu': '˜‰ˆËʉÍÊ', 'info': 'ÈˆÏØÊ‰ÍÊ', 'kind': 'Ê' } ] } current_buffer = VimBuffer( 'buffer', contents = [ '†åsty_π.t' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 13 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': contains_exactly( { 'word' : 'test', 'abbr' : 'ÅııÂʉÍÊ', 'menu' : '˜‰ˆËʉÍÊ', 'info' : 'ÈˆÏØÊ‰ÍÊ', 'kind' : 'Ê', 'equal': 1 }, { 'word' : 'ålpha∫et', 'abbr' : 'å∫∫®', 'menu' : 'µ´~¨á', 'info' : '^~fo', 'kind' : '˚', 'equal': 1 } ), 'completion_start_column': 13 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_RestoreCursorPositionAfterOmnifuncCall( self, ycm ): # This omnifunc moves the cursor to the test definition like # ccomplete#Complete would. def Omnifunc( findstart, base ): vimsupport.SetCurrentLineAndColumn( 0, 0 ) if findstart: return 5 return [ 'length' ] current_buffer = VimBuffer( 'buffer', contents = [ 'String test', '', 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 3, 5 ) ): ycm.SendCompletionRequest() assert_that( vimsupport.CurrentLineAndColumn(), contains_exactly( 2, 5 ) ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'length', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_MoveCursorPositionAtStartColumn( self, ycm ): # This omnifunc relies on the cursor being moved at the start column when # called the second time like LanguageClient#complete from the # LanguageClient-neovim plugin. def Omnifunc( findstart, base ): if findstart: return 5 if vimsupport.CurrentColumn() == 5: return [ 'length' ] return [] current_buffer = VimBuffer( 'buffer', contents = [ 'String test', '', 'test.le' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 3, 7 ) ): ycm.SendCompletionRequest() assert_that( vimsupport.CurrentLineAndColumn(), contains_exactly( 2, 7 ) ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'length', 'equal': 1 } ], 'completion_start_column': 6 } ) ) def test_OmniCompleter_GetCompletions_StartColumnCompliance( self ): for omnifunc_start_column, ycm_completions, ycm_start_column in [ [ -4, [ { 'word': 'foo', 'equal': 1 } ], 3 ], [ -3, [], 1 ], [ -2, [], 1 ], [ -1, [ { 'word': 'foo', 'equal': 1 } ], 3 ], [ 0, [ { 'word': 'foo', 'equal': 1 } ], 1 ], [ 1, [ { 'word': 'foo', 'equal': 1 } ], 2 ], [ 2, [ { 'word': 'foo', 'equal': 1 } ], 3 ], [ 3, [ { 'word': 'foo', 'equal': 1 } ], 3 ] ]: with youcompleteme_instance( { 'g:ycm_cache_omnifunc': 1 } ) as ycm: with self.subTest( omnifunc_start_column = omnifunc_start_column, ycm_completions = ycm_completions, ycm_start_column = ycm_start_column ): StartColumnCompliance( ycm, omnifunc_start_column, ycm_completions, ycm_start_column ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_NoSemanticTrigger( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 0 return [ 'test' ] current_buffer = VimBuffer( 'buffer', contents = [ 'te' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 3 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 1 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_NoCache_ForceSemantic( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 0 return [ 'test' ] current_buffer = VimBuffer( 'buffer', contents = [ 'te' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 3 ) ): ycm.SendCompletionRequest( force_semantic = True ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'test', 'equal': 1 } ], 'completion_start_column': 1 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_ConvertStringsToDictionaries( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ { 'word': 'a' }, 'b' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_filetype_specific_completion_to_disable': { FILETYPE: 1 }, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_FiletypeDisabled_SemanticTrigger( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_filetype_specific_completion_to_disable': { '*': 1 }, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_AllFiletypesDisabled_SemanticTrigger( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest() assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': empty(), 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_filetype_specific_completion_to_disable': { FILETYPE: 1 }, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_FiletypeDisabled_ForceSemantic( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest( force_semantic = True ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 6 } ) ) @YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0, 'g:ycm_filetype_specific_completion_to_disable': { '*': 1 }, 'g:ycm_semantic_triggers': TRIGGERS } ) def test_OmniCompleter_GetCompletions_AllFiletypesDisabled_ForceSemantic( self, ycm ): def Omnifunc( findstart, base ): if findstart: return 5 return [ 'a', 'b', 'cdef' ] current_buffer = VimBuffer( 'buffer', contents = [ 'test.' ], filetype = FILETYPE, omnifunc = Omnifunc ) with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ): ycm.SendCompletionRequest( force_semantic = True ) assert_that( ycm.GetCompletionResponse(), has_entries( { 'completions': [ { 'word': 'a', 'equal': 1 }, { 'word': 'b', 'equal': 1 }, { 'word': 'cdef', 'equal': 1 } ], 'completion_start_column': 6 } ) ) ================================================ FILE: python/ycm/tests/paths_test.py ================================================ # Copyright (C) 2016-2017 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule MockVimModule() from hamcrest import assert_that from unittest import TestCase from ycm.paths import _EndsWithPython def EndsWithPython_Good( path ): assert_that( _EndsWithPython( path ), f'Path { path } does not end with a Python name.' ) def EndsWithPython_Bad( path ): assert_that( not _EndsWithPython( path ), f'Path { path } does end with a Python name.' ) class PathTest( TestCase ): def test_EndsWithPython_Python3Paths( self ): for path in [ 'python3', '/usr/bin/python3.6', '/home/user/.pyenv/shims/python3.6', r'C:\Python36\python.exe' ]: with self.subTest( path = path ): EndsWithPython_Good( path ) def test_EndsWithPython_BadPaths( self ): for path in [ None, '', '/opt/local/bin/vim', r'C:\Program Files\Vim\vim74\gvim.exe', '/usr/bin/python2.7', '/home/user/.pyenv/shims/python3.2', ]: with self.subTest( path = path ): EndsWithPython_Bad( path ) ================================================ FILE: python/ycm/tests/postcomplete_test.py ================================================ # encoding: utf-8 # # Copyright (C) 2015-2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule MockVimModule() import contextlib import json from hamcrest import assert_that, contains_exactly, empty, equal_to, none from unittest import TestCase from unittest.mock import MagicMock, DEFAULT, patch from ycm import vimsupport from ycmd.utils import ToBytes from ycm.client.completion_request import ( CompletionRequest, _FilterToMatchingCompletions, _GetRequiredNamespaceImport ) from ycm.client.omni_completion_request import OmniCompletionRequest def CompleteItemIs( word, abbr = None, menu = None, info = None, kind = None, **kwargs ): item = { 'word': ToBytes( word ), 'abbr': ToBytes( abbr ), 'menu': ToBytes( menu ), 'info': ToBytes( info ), 'kind': ToBytes( kind ), } item.update( **kwargs ) return item def GetVariableValue_CompleteItemIs( word, abbr = None, menu = None, info = None, kind = None, **kwargs ): def Result( variable ): if variable == 'v:completed_item': return CompleteItemIs( word, abbr, menu, info, kind, **kwargs ) return DEFAULT return MagicMock( side_effect = Result ) def BuildCompletion( insertion_text = 'Test', menu_text = None, extra_menu_info = None, detailed_info = None, kind = None, extra_data = None ): completion = { 'insertion_text': insertion_text } if extra_menu_info: completion[ 'extra_menu_info' ] = extra_menu_info if menu_text: completion[ 'menu_text' ] = menu_text if detailed_info: completion[ 'detailed_info' ] = detailed_info if kind: completion[ 'kind' ] = kind if extra_data: completion[ 'extra_data' ] = extra_data return completion def BuildCompletionNamespace( namespace = None, insertion_text = 'Test', menu_text = None, extra_menu_info = None, detailed_info = None, kind = None ): return BuildCompletion( insertion_text = insertion_text, menu_text = menu_text, extra_menu_info = extra_menu_info, detailed_info = detailed_info, kind = kind, extra_data = { 'required_namespace_import': namespace } ) def BuildCompletionFixIt( fixits, insertion_text = 'Test', menu_text = None, extra_menu_info = None, detailed_info = None, kind = None ): return BuildCompletion( insertion_text = insertion_text, menu_text = menu_text, extra_menu_info = extra_menu_info, detailed_info = detailed_info, kind = kind, extra_data = { 'fixits': fixits, } ) @contextlib.contextmanager def _SetupForCsharpCompletionDone( completions ): with patch( 'ycm.vimsupport.InsertNamespace' ): with _SetUpCompleteDone( completions ) as request: yield request @contextlib.contextmanager def _SetUpCompleteDone( completions ): with patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Test' ): request = CompletionRequest( None ) request.Done = MagicMock( return_value = True ) request._RawResponse = MagicMock( return_value = { 'completions': completions } ) yield request class PostcompleteTest( TestCase ): @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] ) def test_OnCompleteDone_DefaultFixIt( self, *args ): request = CompletionRequest( None ) request.Done = MagicMock( return_value = True ) request._OnCompleteDone_Csharp = MagicMock() request._OnCompleteDone_FixIt = MagicMock() request.OnCompleteDone() request._OnCompleteDone_Csharp.assert_not_called() request._OnCompleteDone_FixIt.assert_called_once_with() @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'cs' ] ) def test_OnCompleteDone_CsharpFixIt( self, *args ): request = CompletionRequest( None ) request.Done = MagicMock( return_value = True ) request._OnCompleteDone_Csharp = MagicMock() request._OnCompleteDone_FixIt = MagicMock() request.OnCompleteDone() request._OnCompleteDone_Csharp.assert_called_once_with() request._OnCompleteDone_FixIt.assert_not_called() @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] ) def test_OnCompleteDone_NoFixItIfNotDone( self, *args ): request = CompletionRequest( None ) request.Done = MagicMock( return_value = False ) request._OnCompleteDone_Csharp = MagicMock() request._OnCompleteDone_FixIt = MagicMock() request.OnCompleteDone() request._OnCompleteDone_Csharp.assert_not_called() request._OnCompleteDone_FixIt.assert_not_called() @patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] ) def test_OnCompleteDone_NoFixItForOmnifunc( self, *args ): request = OmniCompletionRequest( 'omnifunc', None ) request.Done = MagicMock( return_value = True ) request._OnCompleteDone_Csharp = MagicMock() request._OnCompleteDone_FixIt = MagicMock() request.OnCompleteDone() request._OnCompleteDone_Csharp.assert_not_called() request._OnCompleteDone_FixIt.assert_not_called() def test_FilterToCompletedCompletions_MatchIsReturned( self ): completions = [ BuildCompletion( insertion_text = 'Test' ) ] result = _FilterToMatchingCompletions( CompleteItemIs( 'Test' ), completions ) assert_that( list( result ), contains_exactly( {} ) ) def test_FilterToCompletedCompletions_ShortTextDoesntRaise( self ): completions = [ BuildCompletion( insertion_text = 'AAA' ) ] result = _FilterToMatchingCompletions( CompleteItemIs( 'A' ), completions ) assert_that( list( result ), empty() ) def test_FilterToCompletedCompletions_ExactMatchIsReturned( self ): completions = [ BuildCompletion( insertion_text = 'Test' ) ] result = _FilterToMatchingCompletions( CompleteItemIs( 'Test' ), completions ) assert_that( list( result ), contains_exactly( {} ) ) def test_FilterToCompletedCompletions_NonMatchIsntReturned( self ): completions = [ BuildCompletion( insertion_text = 'A' ) ] result = _FilterToMatchingCompletions( CompleteItemIs( ' Quote' ), completions ) assert_that( list( result ), empty() ) def test_FilterToCompletedCompletions_Unicode( self ): completions = [ BuildCompletion( insertion_text = '†es†' ) ] result = _FilterToMatchingCompletions( CompleteItemIs( '†es†' ), completions ) assert_that( list( result ), contains_exactly( {} ) ) def test_GetRequiredNamespaceImport_ReturnNoneForNoExtraData( self ): assert_that( _GetRequiredNamespaceImport( {} ), none() ) def test_GetRequiredNamespaceImport_ReturnNamespaceFromExtraData( self ): namespace = 'A_NAMESPACE' assert_that( _GetRequiredNamespaceImport( BuildCompletionNamespace( namespace )[ 'extra_data' ] ), equal_to( namespace ) ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Te' ) ) def test_GetExtraDataUserMayHaveCompleted_ReturnEmptyIfPendingMatches( *args ): completions = [ BuildCompletionNamespace( None ) ] with _SetupForCsharpCompletionDone( completions ) as request: assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() ) def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfExactMatches( self, *args ): info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] completions = [ BuildCompletionNamespace( *info ) ] with _SetupForCsharpCompletionDone( completions ) as request: with patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): assert_that( request._GetExtraDataUserMayHaveCompleted(), contains_exactly( completions[ 0 ][ 'extra_data' ] ) ) def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfExactMatchesEvenIfPartial( self ): # noqa info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] completions = [ BuildCompletionNamespace( *info ), BuildCompletion( insertion_text = 'TestTest' ) ] with _SetupForCsharpCompletionDone( completions ) as request: with patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): assert_that( request._GetExtraDataUserMayHaveCompleted(), contains_exactly( completions[ 0 ][ 'extra_data' ] ) ) def test_GetExtraDataUserMayHaveCompleted_DontReturnMatchIfNoExactMatchesAndPartial( self ): # noqa info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ] completions = [ BuildCompletion( insertion_text = info[ 0 ] ), BuildCompletion( insertion_text = 'TestTest' ) ] with _SetupForCsharpCompletionDone( completions ) as request: with patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( *info[ 1: ] ) ): assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfMatches( self, *args ): completions = [ BuildCompletionNamespace( None ) ] with _SetupForCsharpCompletionDone( completions ) as request: assert_that( request._GetExtraDataUserMayHaveCompleted(), contains_exactly( completions[ 0 ][ 'extra_data' ] ) ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test', user_data=json.dumps( { 'required_namespace_import': 'namespace1' } ) ) ) def test_GetExtraDataUserMayHaveCompleted_UseUserData0( self, *args ): # Identical completions but we specify the first one via user_data. completions = [ BuildCompletionNamespace( 'namespace1' ), BuildCompletionNamespace( 'namespace2' ) ] with _SetupForCsharpCompletionDone( completions ) as request: assert_that( request._GetExtraDataUserMayHaveCompleted(), contains_exactly( BuildCompletionNamespace( 'namespace1' )[ 'extra_data' ] ) ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test', user_data=json.dumps( { 'required_namespace_import': 'namespace2' } ) ) ) def test_GetExtraDataUserMayHaveCompleted_UseUserData1( self, *args ): # Identical completions but we specify the second one via user_data. completions = [ BuildCompletionNamespace( 'namespace1' ), BuildCompletionNamespace( 'namespace2' ) ] with _SetupForCsharpCompletionDone( completions ) as request: assert_that( request._GetExtraDataUserMayHaveCompleted(), contains_exactly( BuildCompletionNamespace( 'namespace2' )[ 'extra_data' ] ) ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test', user_data='' ) ) def test_GetExtraDataUserMayHaveCompleted_EmptyUserData( self, *args ): # Identical completions but none is selected. completions = [ BuildCompletionNamespace( 'namespace1' ), BuildCompletionNamespace( 'namespace2' ) ] with _SetupForCsharpCompletionDone( completions ) as request: assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) def test_PostCompleteCsharp_EmptyDoesntInsertNamespace( self, *args ): with _SetupForCsharpCompletionDone( [] ) as request: request._OnCompleteDone_Csharp() assert_that( not vimsupport.InsertNamespace.called ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) def test_PostCompleteCsharp_ExistingWithoutNamespaceDoesntInsertNamespace( self, *args ): completions = [ BuildCompletionNamespace( None ) ] with _SetupForCsharpCompletionDone( completions ) as request: request._OnCompleteDone_Csharp() assert_that( not vimsupport.InsertNamespace.called ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) def test_PostCompleteCsharp_ValueDoesInsertNamespace( self, *args ): namespace = 'A_NAMESPACE' completions = [ BuildCompletionNamespace( namespace ) ] with _SetupForCsharpCompletionDone( completions ) as request: request._OnCompleteDone_Csharp() vimsupport.InsertNamespace.assert_called_once_with( namespace ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) @patch( 'ycm.vimsupport.PresentDialog', return_value = 1 ) def test_PostCompleteCsharp_InsertSecondNamespaceIfSelected( self, *args ): namespace = 'A_NAMESPACE' namespace2 = 'ANOTHER_NAMESPACE' completions = [ BuildCompletionNamespace( namespace ), BuildCompletionNamespace( namespace2 ), ] with _SetupForCsharpCompletionDone( completions ) as request: request._OnCompleteDone_Csharp() vimsupport.InsertNamespace.assert_called_once_with( namespace2 ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_NoFixIts( self, replace_chunks, *args ): completions = [ BuildCompletionFixIt( [] ) ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_not_called() @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_EmptyFixIt( self, replace_chunks, *args ): completions = [ BuildCompletionFixIt( [ { 'chunks': [] } ] ) ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_called_once_with( [], silent = True ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_NoFixIt( self, replace_chunks, *args ): completions = [ BuildCompletion() ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_not_called() @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test' ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_PickFirst( self, replace_chunks, *args ): completions = [ BuildCompletionFixIt( [ { 'chunks': 'one' } ] ), BuildCompletionFixIt( [ { 'chunks': 'two' } ] ), ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_called_once_with( 'one', silent = True ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test', user_data=json.dumps( { 'fixits': [ { 'chunks': 'one' } ] } ) ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_PickFirstUserData( self, replace_chunks, *args ): completions = [ BuildCompletionFixIt( [ { 'chunks': 'one' } ] ), BuildCompletionFixIt( [ { 'chunks': 'two' } ] ), ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_called_once_with( 'one', silent = True ) @patch( 'ycm.vimsupport.GetVariableValue', GetVariableValue_CompleteItemIs( 'Test', user_data=json.dumps( { 'fixits': [ { 'chunks': 'two' } ] } ) ) ) @patch( 'ycm.vimsupport.ReplaceChunks' ) def test_PostCompleteFixIt_ApplyFixIt_PickSecond( self, replace_chunks, *args ): completions = [ BuildCompletionFixIt( [ { 'chunks': 'one' } ] ), BuildCompletionFixIt( [ { 'chunks': 'two' } ] ), ] with _SetUpCompleteDone( completions ) as request: request._OnCompleteDone_FixIt() replace_chunks.assert_called_once_with( 'two', silent = True ) ================================================ FILE: python/ycm/tests/signature_help_test.py ================================================ # Copyright (C) 2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from hamcrest import ( assert_that, empty ) from unittest import TestCase from ycm import signature_help as sh class SignatureHelpTest( TestCase ): def test_MakeSignatureHelpBuffer_Empty( self ): assert_that( sh._MakeSignatureHelpBuffer( {} ), empty() ) assert_that( sh._MakeSignatureHelpBuffer( { 'activeSignature': 0, 'activeParameter': 0, 'signatures': [] } ), empty() ) assert_that( sh._MakeSignatureHelpBuffer( { 'activeSignature': 0, 'activeParameter': 0, } ), empty() ) assert_that( sh._MakeSignatureHelpBuffer( { 'signatures': [] } ), empty() ) ================================================ FILE: python/ycm/tests/syntax_parse_test.py ================================================ # Copyright (C) 2013 Google Inc. # 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from ycm.tests.test_utils import MockVimModule MockVimModule() import os from hamcrest import assert_that, contains_inanyorder, has_item, has_items from unittest import TestCase from ycm import syntax_parse from ycmd.utils import ReadFile def ContentsOfTestFile( test_file ): dir_of_script = os.path.dirname( os.path.abspath( __file__ ) ) full_path_to_test_file = os.path.join( dir_of_script, 'testdata', test_file ) return ReadFile( full_path_to_test_file ) class SyntaxTest( TestCase ): def test_KeywordsFromSyntaxListOutput_PythonSyntax( self ): expected_keywords = ( 'bytearray', 'IndexError', 'all', 'help', 'vars', 'SyntaxError', 'global', 'elif', 'unicode', 'sorted', 'memoryview', 'isinstance', 'except', 'nonlocal', 'NameError', 'finally', 'BytesWarning', 'dict', 'IOError', 'pass', 'oct', 'bin', 'SystemExit', 'return', 'StandardError', 'format', 'TabError', 'break', 'next', 'not', 'UnicodeDecodeError', 'False', 'RuntimeWarning', 'list', 'iter', 'try', 'reload', 'Warning', 'round', 'dir', 'cmp', 'set', 'bytes', 'UnicodeTranslateError', 'intern', 'issubclass', 'yield', 'Ellipsis', 'hash', 'locals', 'BufferError', 'slice', 'for', 'FloatingPointError', 'sum', 'VMSError', 'getattr', 'abs', 'print', 'import', 'True', 'FutureWarning', 'ImportWarning', 'None', 'EOFError', 'len', 'frozenset', 'ord', 'super', 'raise', 'TypeError', 'KeyboardInterrupt', 'UserWarning', 'filter', 'range', 'staticmethod', 'SystemError', 'or', 'BaseException', 'pow', 'RuntimeError', 'float', 'MemoryError', 'StopIteration', 'globals', 'divmod', 'enumerate', 'apply', 'LookupError', 'open', 'basestring', 'from', 'UnicodeError', 'zip', 'hex', 'long', 'IndentationError', 'int', 'chr', '__import__', 'type', 'Exception', 'continue', 'tuple', 'reduce', 'reversed', 'else', 'assert', 'UnicodeEncodeError', 'input', 'with', 'hasattr', 'delattr', 'setattr', 'raw_input', 'PendingDeprecationWarning', 'compile', 'ArithmeticError', 'while', 'del', 'str', 'property', 'def', 'and', 'GeneratorExit', 'ImportError', 'xrange', 'is', 'EnvironmentError', 'KeyError', 'coerce', 'SyntaxWarning', 'file', 'in', 'unichr', 'ascii', 'any', 'as', 'if', 'OSError', 'DeprecationWarning', 'min', 'UnicodeWarning', 'execfile', 'id', 'complex', 'bool', 'ValueError', 'NotImplemented', 'map', 'exec', 'buffer', 'max', 'class', 'object', 'repr', 'callable', 'ZeroDivisionError', 'eval', '__debug__', 'ReferenceError', 'AssertionError', 'classmethod', 'UnboundLocalError', 'NotImplementedError', 'lambda', 'AttributeError', 'OverflowError', 'WindowsError' ) assert_that( syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'python_syntax' ) ), contains_inanyorder( *expected_keywords ) ) def test_KeywordsFromSyntaxListOutput_CppSyntax( self ): expected_keywords = ( 'int_fast32_t', 'FILE', 'size_t', 'bitor', 'typedef', 'const', 'struct', 'uint8_t', 'fpos_t', 'thread_local', 'unsigned', 'uint_least16_t', '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' ) assert_that( syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'cpp_syntax' ) ), contains_inanyorder( *expected_keywords ) ) def test_KeywordsFromSyntaxListOutput_JavaSyntax( self ): expected_keywords = ( 'code', 'text', 'cols', 'datetime', 'disabled', 'shape', 'codetype', 'alt', 'compact', 'style', 'valuetype', 'short', 'finally', 'continue', 'extends', 'valign', 'bordercolor', 'do', 'return', 'rel', 'rules', 'void', 'nohref', 'abbr', 'background', 'scrolling', 'instanceof', 'name', 'summary', 'try', 'default', 'noshade', 'coords', 'dir', 'frame', 'usemap', 'ismap', 'static', 'hspace', 'vlink', 'for', 'selected', 'rev', 'vspace', 'content', 'method', 'version', 'volatile', 'above', 'new', 'charoff', 'public', 'alink', 'enum', 'codebase', 'if', 'noresize', 'interface', 'checked', 'byte', 'super', 'throw', 'src', 'language', 'package', 'standby', 'script', 'longdesc', 'maxlength', 'cellpadding', 'throws', 'tabindex', 'color', 'colspan', 'accesskey', 'float', 'while', 'private', 'height', 'boolean', 'wrap', 'prompt', 'nowrap', 'size', 'rows', 'span', 'clip', 'bgcolor', 'top', 'long', 'start', 'scope', 'scheme', 'type', 'final', 'lang', 'visibility', 'else', 'assert', 'transient', 'link', 'catch', 'true', 'serializable', 'target', 'lowsrc', 'this', 'double', 'align', 'value', 'cite', 'headers', 'below', 'protected', 'declare', 'classid', 'defer', 'false', 'synchronized', 'int', 'abstract', 'accept', 'hreflang', 'char', 'border', 'id', 'native', 'rowspan', 'charset', 'archive', 'strictfp', 'readonly', 'axis', 'cellspacing', 'profile', 'multiple', 'object', 'action', 'pagex', 'pagey', 'marginheight', 'data', 'class', 'frameborder', 'enctype', 'implements', 'break', 'gutter', 'url', 'clear', 'face', 'switch', 'marginwidth', 'width', 'left' ) assert_that( syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'java_syntax' ) ), contains_inanyorder( *expected_keywords ) ) def test_KeywordsFromSyntaxListOutput_PhpSyntax_ContainsFunctions( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'php_syntax' ) ), has_items( 'array_change_key_case' ) ) def test_KeywordsFromSyntaxListOutput_PhpSyntax_ContainsPreProc( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( ContentsOfTestFile( 'php_syntax' ) ), has_items( 'skip', 'function' ) ) def test_KeywordsFromSyntaxListOutput_Basic( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ foogroup xxx foo bar zoo goo links to Statement""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_KeywordsFromSyntaxListOutput_Function( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ foogroup xxx foo bar zoo goo links to Function""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_KeywordsFromSyntaxListOutput_ContainedArgAllowed( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ phpFunctions xxx contained gzclose yaz_syntax html_entity_decode fbsql_read_blob png2wbmp mssql_init cpdf_set_title gztell fbsql_insert_id empty cpdf_restore mysql_field_type closelog swftext ldap_search curl_errno gmp_div_r mssql_data_seek getmyinode printer_draw_pie mcve_initconn ncurses_getmaxyx defined contained replace_child has_attributes specified insertdocument assign node_name hwstat addshape get_attribute_node html_dump_mem userlist links to Function""" ), # noqa has_items( 'gzclose', 'userlist', 'ldap_search' ) ) def test_KeywordsFromSyntaxListOutput_JunkIgnored( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ --- Syntax items --- foogroup xxx foo bar zoo goo links to Statement Spell cluster=NONE NoSpell cluster=NONE""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_KeywordsFromSyntaxListOutput_MultipleStatementGroups( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ foogroup xxx foo bar links to Statement bargroup xxx zoo goo links to Statement""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_KeywordsFromSyntaxListOutput_StatementAndTypeGroups( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ foogroup xxx foo bar links to Statement bargroup xxx zoo goo links to Type""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_KeywordsFromSyntaxListOutput_StatementHierarchy( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ baa xxx foo bar links to Foo Foo xxx zoo goo links to Bar Bar xxx qux moo links to Statement""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo' ) ) def test_KeywordsFromSyntaxListOutput_TypeHierarchy( self ): assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """ baa xxx foo bar links to Foo Foo xxx zoo goo links to Bar Bar xxx qux moo links to Type""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo' ) ) def test_KeywordsFromSyntaxListOutput_StatementAndTypeHierarchy( self ): assert_that( 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""" ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo', 'na', 'nb', 'nc' ) ) def test_SyntaxGroupsFromOutput_Basic( self ): assert_that( syntax_parse._SyntaxGroupsFromOutput( """ foogroup xxx foo bar zoo goo links to Statement""" ), has_item( 'foogroup' ) ) def test_ExtractKeywordsFromGroup_Basic( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'foo bar', 'zoo goo', ] ) ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_Commas( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'foo, bar,', 'zoo goo', ] ) ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_WithLinksTo( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'foo bar', 'zoo goo', 'links to Statement' ] ) ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_KeywordStarts( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'foo bar', 'contained boo baa', 'zoo goo', ] ) ), contains_inanyorder( 'foo', 'bar', 'boo', 'baa', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_KeywordMiddle( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'foo contained bar', 'zoo goo' ] ) ), contains_inanyorder( 'foo', 'contained', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_KeywordAssign( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'nextgroup=zoo skipwhite foo bar', 'zoo goo', ] ) ), contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_KeywordAssignAndMiddle( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'nextgroup=zoo foo skipnl bar', 'zoo goo', ] ) ), contains_inanyorder( 'foo', 'skipnl', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_KeywordWithoutNextgroup( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'skipempty foo bar', 'zoo goo', ] ) ), contains_inanyorder( 'skipempty', 'foo', 'bar', 'zoo', 'goo' ) ) def test_ExtractKeywordsFromGroup_ContainedSyntaxArgAllowed( self ): assert_that( syntax_parse._ExtractKeywordsFromGroup( syntax_parse.SyntaxGroup( '', [ 'contained foo zoq', 'contained bar goo', 'far' ] ) ), contains_inanyorder( 'foo', 'zoq', 'bar', 'goo', 'far' ) ) ================================================ FILE: python/ycm/tests/test_utils.py ================================================ # Copyright (C) 2011-2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see . from collections import defaultdict, namedtuple from unittest.mock import DEFAULT, MagicMock, patch from unittest import skip from hamcrest import ( assert_that, contains_exactly, contains_inanyorder, equal_to ) import contextlib import functools import json import os import re import sys from unittest import skipIf from ycmd.utils import GetCurrentDirectory, OnMac, OnWindows, ToUnicode BUFNR_REGEX = re.compile( '^bufnr\\( \'(?P.+)\'(, ([01]))? \\)$' ) BUFWINNR_REGEX = re.compile( '^bufwinnr\\( (?P[0-9]+) \\)$' ) BWIPEOUT_REGEX = re.compile( '^(?:silent! )bwipeout!? (?P[0-9]+)$' ) GETBUFVAR_REGEX = re.compile( '^getbufvar\\((?P[0-9]+), "(?P